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/4/0x98E8e3DebA2bC44d1924Da805fA4daB9ba6Fd8Fa/sources/browser/Untitled.sol
Minting according to luck percent of the given token id
function mintToken(uint256 _tokenID) public returns(bool) { require(!globalHalt, "paused by admin"); address caller = niftyMoji(niftyMojiContractAddress).ownerOf(_tokenID); require(!blackListedUser[caller], "you are not allowed"); require(!blackListedToken[_tokenID], "this token is blacklisted"); require(caller == msg.sender,"caller is not the owner of this tokenID"); uint256 dt = dayTracker[_tokenID]; if(maxTokenID < _tokenID) maxTokenID = _tokenID; if (dt != 0) { uint256 secPassed = now - dt ; require(secPassed > 0 , "already minted for the day"); (uint256 powerPercent,uint256 luckPercent ) = niftyMoji(niftyMojiContractAddress).powerNLucks(_tokenID); currentLuck[_tokenID] = luckPercent; currentPower[_tokenID] = powerPercent; uint256 mintAmount = (( (mintingMultiplier * (10 ** 18) * ((luckPercent + 9 ) / 10 ) ) / 100000 ) / 86400 ) * secPassed ; dayTracker[_tokenID] = now ; totalMintedForTokenId[_tokenID] = totalMintedForTokenId[_tokenID].add(mintAmount); lifeTimeMintedForTokenId[_tokenID] = lifeTimeMintedForTokenId[_tokenID].add(mintAmount); lifeTimeMintedByUser[caller] = lifeTimeMintedByUser[caller].add(mintAmount); claimMyTokens(_tokenID,caller); } else { dayTracker[_tokenID] = now; } return true; } event claimMyTokensEv(address user, uint256 tokenID, uint256 amountClaimed);
745,990
pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./PLGToken.sol"; import "./Whitelist.sol"; /// @title Pledgecamp Crowdsale /// @author Sam Pullman /// @notice Capped crowdsale with bonuses for the Pledgecamp platform contract PLGCrowdsale is Ownable { using SafeMath for uint256; /// @notice Indicates successful token purchase /// @param buyer Fund provider for the token purchase. Must either be `owner` or equal to `beneficiary` /// @param beneficiary Account that ultimately receives purchased tokens /// @param value Amount in wei of investment /// @param tokenAmount Number of tokens purchased (not including bonus) /// @param bonusAmount Number of bonus tokens received event TokenPurchase(address indexed buyer, address indexed beneficiary, uint256 value, uint256 tokenAmount, uint256 bonusAmount); /// @notice Emitted when the ETH to PLG exchange rate has been updated /// @param oldRate The previous exchange rate /// @param newRate The new exchange rate event ExchangeRateUpdated(uint256 oldRate, uint256 newRate); /// @notice Emitted when the crowdsale ends event Closed(); /// True if the sale is active bool public saleActive; /// ERC20 token the crowdsale is based on PLGToken plgToken; /// Timestamp for when the crowdsale may start uint256 public startTime; /// Timestamp set when crowdsale purchasing stops uint256 public endTime; /// Token to ether conversion rate uint256 public tokensPerEther; /// Amount raised so far in wei uint256 public amountRaised; /// The minimum purchase amount in wei uint256 public minimumPurchase; /// The address from which bonus tokens are distributed address public bonusPool; /// The strategy for assigning bonus tokens from bonusPool and assigning vesting contracts Whitelist whitelist; /// @notice Constructor for the Pledgecamp crowdsale contract /// @param _plgToken ERC20 token contract used in the crowdsale /// @param _startTime Timestamp for when the crowdsale may start /// @param _rate Token to ether conversion rate /// @param _minimumPurchase The minimum purchase amount in wei constructor(address _plgToken, uint256 _startTime, uint256 _rate, uint256 _minimumPurchase) public { require(_startTime >= now); require(_rate > 0); require(_plgToken != address(0)); startTime = _startTime; tokensPerEther = _rate; minimumPurchase = _minimumPurchase; plgToken = PLGToken(_plgToken); } /// @notice Set the address of the bonus pool, which provides tokens /// @notice during bonus periods if it contains sufficient PLG /// @param _bonusPool Address of PLG holder function setBonusPool(address _bonusPool) public onlyOwner { bonusPool = _bonusPool; } /// @notice Set the contract that whitelists and calculates how many bonus tokens to award each purchase. /// @param _whitelist The address of the whitelist, which must be a `Whitelist` function setWhitelist(address _whitelist) public onlyOwner { require(_whitelist != address(0)); whitelist = Whitelist(_whitelist); } /// @notice Starts the crowdsale under appropriate conditions function start() public onlyOwner { require(!saleActive); require(now > startTime); require(endTime == 0); require(plgToken.initialized()); require(plgToken.lockExceptions(address(this))); require(bonusPool != address(0)); require(whitelist != address(0)); saleActive = true; } /// @notice End the crowdsale if the sale is active /// @notice Transfer remaining tokens to reserve pool function end() public onlyOwner { require(saleActive); require(bonusPool != address(0)); saleActive = false; endTime = now; withdrawTokens(); owner.transfer(address(this).balance); } /// @notice Withdraw crowdsale ETH to owner wallet function withdrawEth() public onlyOwner { owner.transfer(address(this).balance); } /// @notice Send remaining crowdsale tokens to `bonusPool` after sale is over function withdrawTokens() public onlyOwner { require(!saleActive); uint256 remainingTokens = plgToken.balanceOf(this); plgToken.transfer(bonusPool, remainingTokens); } /// Default function tries to make a token purchase function () external payable { buyTokensInternal(msg.sender); } /// @notice Public crowdsale purchase method function buyTokens() external payable { buyTokensInternal(msg.sender); } /// @notice Owner only method for purchasing on behalf of another person /// @param beneficiary Address to receive the tokens function buyTokensFor(address beneficiary) external payable onlyOwner { require(beneficiary != address(0)); buyTokensInternal(beneficiary); } /// @notice Main crowdsale purchase method, which validates the purchase and assigns bonuses /// @param beneficiary Address to receive the tokens function buyTokensInternal(address beneficiary) private { require(whitelist != address(0)); require(bonusPool != address(0)); require(validPurchase(msg.value)); uint256 weiAmount = msg.value; // This is the whitelist/max purchase check require(whitelist.isValidPurchase(beneficiary, weiAmount)); // Calculate the amount of PLG that's been purchased uint256 tokens = weiAmount.mul(tokensPerEther); // update state amountRaised = amountRaised.add(weiAmount); // Record the purchase in the whitelist contract whitelist.recordPurchase(beneficiary, weiAmount); plgToken.transfer(beneficiary, tokens); uint256 bonusPercent = whitelist.getBonusPercent(beneficiary); uint256 bonusTokens = tokens.mul(bonusPercent) / 100; if(bonusTokens > 0) { plgToken.transferFrom(bonusPool, beneficiary, bonusTokens); } emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, bonusTokens); } /// @notice Set a new ETH to PLG exchange rate /// @param _tokensPerEther Exchange rate function setExchangeRate(uint256 _tokensPerEther) external onlyOwner { emit ExchangeRateUpdated(tokensPerEther, _tokensPerEther); tokensPerEther = _tokensPerEther; } /// @notice Check various conditions to determine whether a purchase is currently valid /// @param amount The amount of tokens to be purchased function validPurchase(uint256 amount) public view returns (bool) { bool nonZeroPurchase = amount != 0; bool isMinPurchase = (amount >= minimumPurchase); return saleActive && nonZeroPurchase && isMinPurchase; } }
Starts the crowdsale under appropriate conditions
function start() public onlyOwner { require(!saleActive); require(now > startTime); require(endTime == 0); require(plgToken.initialized()); require(plgToken.lockExceptions(address(this))); require(bonusPool != address(0)); require(whitelist != address(0)); saleActive = true; }
6,427,157
./partial_match/1/0xDE40A471589752bEdf46e5A437AE1A50AFCd4C81/sources/contracts/PresaleV3.sol
To claim tokens after claiming starts/
function claim() external whenNotPaused returns (bool) { require(saleToken != address(0), "Sale token not added"); require(block.timestamp >= claimStart, "Claim has not started yet"); require(!isBlacklisted[_msgSender()], "This Address is Blacklisted"); if (whitelistClaimOnly) { require( isWhitelisted[_msgSender()], "User not whitelisted for claim" ); } require(!hasClaimed[_msgSender()], "Already claimed"); hasClaimed[_msgSender()] = true; uint256 amount = userDeposits[_msgSender()]; require(amount > 0, "Nothing to claim"); delete userDeposits[_msgSender()]; bool success = IERC20Upgradeable(saleToken).transfer( _msgSender(), amount ); require(success, "Token transfer failed"); emit TokensClaimed(_msgSender(), amount, block.timestamp); return true; }
4,009,910
./partial_match/1/0x5B17f168829968D9fb5F049b45b14b7601AFf85B/sources/ions/ERC721_Remote_Store.sol
See {IERC721-setApprovalForAll}./
function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "436"); _ristore.setTokenOperatorApproval(_msgSender(), operator, approved); emit ApprovalForAll(_msgSender(), operator, approved); }
11,032,352
./partial_match/1/0x711014785D1CFdBe90c2946c4caF768A6dab3e48/sources/hpos12i.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("hpos12i", "HPOS12I") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyCharityFee = 12; uint256 _buyMarketingFee = 12; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellCharityFee = 12; uint256 _sellMarketingFee = 12; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 69420420 * 1e18; buyCharityFee = _buyCharityFee; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee; sellCharityFee = _sellCharityFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellCharityFee + sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
2,588,509
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Pair { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface IUniswapV2Router02 is IUniswapV2Router01 {} abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // Hostilezone ERC-721 Contract interface HostileZoneNft { function walletOfOwner(address _owner) external view returns (uint256[] memory); function ownerOf(uint256 tokenId) external view returns (address owner); } contract HostileZone is Ownable, IERC20{ // pairs in AMM mapping (address => bool) public _isPool; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; // Fees wallets. address public marketWallet; address public developerWallet; address public GameDevelopWallet; address public liquidityWallet; // token string private _name = "HostileZoneOfficial"; string private _symbol = "Htz"; uint8 private _decimals = 18; // supply uint256 public _total = 500000000; uint256 private _totalSupply; // addresses address public _uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public _pair = address(0); // pause the contract at start bool public paused = true; bool public poolCreated; // set time based limitation bool public isLimited = true; uint256 public maxTransactionAmount = 100000 * 10 ** 18; uint256 public buyTotalFees; uint256 public sellTotalFees; // exclusions mapping (address => bool) public _isExcludedFromBuyFees; // buy fees exclusion mapping (address => bool) public _isExcludedFromSellFees; // sell fees exclusion mapping (address => bool) public _isExcludedMaxTransactionAmount; // max amount per transactions (any time) exclusion mapping (address => bool) public _isExcludedFromTimeTx; // max number of transactions in lower time scale exclusion mapping (address => bool) public _isExcludedFromTimeAmount; // max amount traded in higher time scale exclusion mapping (address => bool) public _isExcludedFromMaxWallet; // max wallet amount exclusion // wallets metrics mapping(address => uint256) public _previousFirstTradeTime; // first transaction in lower time scale mapping(address => uint256) public _numberOfTrades; // number of trades in lower time scale mapping(address => uint256) public _largerPreviousFirstTradeTime; // first transaction in larger time scale mapping(address => uint256) public _largerCurrentAmountTraded; // amount traded in large time scale // limitations values uint256 public largerTimeLimitBetweenTx = 7 days; // larger time scale uint256 public timeLimitBetweenTx = 1 hours; // lower time scale uint256 public txLimitByTime = 3; // number limit of transactions (lower scale) uint256 public largerAmountLimitByTime = 1500000 * 10 ** _decimals; // transaction amounts limits (larger scale) uint256 public maxByWallet = 600000 * 10 ** 18; // max token in wallet // Buy Fees uint256 _buyMarketingFee; uint256 _buyLiquidityFee; uint256 _buyDevFee; uint256 _buyGameDevelopingFee; uint256 public buyDiscountLv1; uint256 public buyDiscountLv2; // Sell Fees uint256 _sellMarketingFee; uint256 _sellLiquidityFee; uint256 _sellDevFee; uint256 _sellGameDevelopingFee; uint256 public sellDiscountLv1; uint256 public sellDiscountLv2; // Tokens routing uint256 public tokensForMarketing; uint256 public tokensForDev; uint256 public tokensForGameDev; uint256 public tokensForLiquidity; // uniswap v2 interface IUniswapV2Router02 private UniV2Router; // nft address to check discount address hostileZoneNftAddress; //Legendary NFTs uint256[] public legendaryNFTs; constructor() { // initial supply to mint _totalSupply = 100000000 * 10 ** _decimals; _balances[_msgSender()] += _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); // set router v2 UniV2Router = IUniswapV2Router02(_uniRouter); // wallets setting marketWallet = 0x7F22B4D77EAa010C53Ad7383F93725Db405f44C7; developerWallet = 0xaE859cc7FD075cBff43E2E659694fb1F7aeE0ecF; GameDevelopWallet = 0xab9cc7E0E2B86d77bE6059bC69C4db3A9B53a6bf; liquidityWallet = 0xCD01C9F709535FdfdB1cd943C7C01D58714a0Ca6; // pair address _pair = IUniswapV2Factory(UniV2Router.factory()).createPair(address(this), UniV2Router.WETH()); // pair is set as pair _isPool[_pair] = true; // basic exclusions // buy fees exclusions _isExcludedFromBuyFees[_msgSender()] = true; _isExcludedFromBuyFees[address(this)] = true; // sell fees exclusions _isExcludedFromSellFees[_msgSender()] = true; _isExcludedFromSellFees[address(this)] = true; // max transaction amount any time _isExcludedMaxTransactionAmount[_msgSender()] = true; _isExcludedMaxTransactionAmount[_pair] = true; _isExcludedMaxTransactionAmount[address(this)] = true; // lower scale time number of transactions exclusions _isExcludedFromTimeTx[_msgSender()] = true; _isExcludedFromTimeTx[_pair] = true; _isExcludedFromTimeTx[address(this)] = true; // larger scale time amount exclusion _isExcludedFromTimeAmount[_msgSender()] = true; _isExcludedFromTimeAmount[_pair] = true; _isExcludedFromTimeAmount[address(this)] = true; // max wallet in exclusions _isExcludedFromMaxWallet[_msgSender()] = true; _isExcludedFromMaxWallet[_pair] = true; _isExcludedFromMaxWallet[address(this)] = true; // buy fees _buyMarketingFee = 4; _buyLiquidityFee = 5; _buyDevFee = 2; _buyGameDevelopingFee = 2; buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; // 13% buyDiscountLv1 = 1; buyDiscountLv2 = 4; // Sell Fees _sellMarketingFee = 5; _sellLiquidityFee = 9; _sellDevFee = 2; _sellGameDevelopingFee = 3; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; // 19% sellDiscountLv1 = 2; sellDiscountLv2 = 5; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require (_allowances[sender][_msgSender()] >= amount, "ERC20: transfer amount exceeds allowance"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(_balances[sender] >= amount, "ERC20: transfer exceeds balance"); require(amount > 450 * 10 ** 18, "HostileZone: cannot transfer less than 450 tokens."); require(!paused, "HostileZone: trading isn't enabled yet."); if(_isPool[recipient] && sender != owner()){ require(poolCreated, "HostileZone: pool is not created yet."); } if(_isPool[sender] ){ require(_isExcludedMaxTransactionAmount[recipient] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed."); } if(_isPool[recipient] ){ require(_isExcludedMaxTransactionAmount[sender] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed."); } // amount limit // check max transactions exclusion or max transaction amount limits require(_isExcludedMaxTransactionAmount[sender] || amount <= maxTransactionAmount, "HostileZone: amount is higher than max transaction allowed."); // check max wallet in exclusion or max transaction amount limits require(_isExcludedFromMaxWallet[recipient] || amount + _balances[recipient] <= maxByWallet, "HostileZone: amount is higher than max wallet amount allowed."); // time scales limitation if(isLimited){ // check if it's a buy or sell transaction // some limits only to apply on buy and sell if( _isPool[recipient] ) { checkTimeLimits(sender, amount); } else if(_isPool[sender] ){ checkTimeLimits(recipient, amount); } } uint256 fees = 0; bool takeBuyFee; bool takeSellFee; // Should contract take buy fees if( !_isExcludedFromBuyFees[recipient] && _isPool[sender] && buyTotalFees > 0 ) { takeBuyFee = true; } // Should contract take sell fees if( !_isExcludedFromSellFees[sender] && _isPool[recipient] && sellTotalFees > 0 ) { takeSellFee = true; } if(takeBuyFee){ // check discount for buy fees uint256 buyTotalFeesWithDiscount = calculateFeeBuyAmount(recipient); if(buyTotalFeesWithDiscount > 0){ // add total buy fees to fees fees += uint256(uint256(amount * buyTotalFeesWithDiscount) / 100); // Buy: liquidity fees calculation tokensForLiquidity = uint256(uint256(fees * _buyLiquidityFee) / buyTotalFeesWithDiscount); _balances[liquidityWallet] += tokensForLiquidity; emit Transfer(sender, liquidityWallet, tokensForLiquidity); // Buy: dev fees calculation tokensForDev = uint256(uint256(fees * _buyDevFee) / buyTotalFeesWithDiscount); _balances[developerWallet] += tokensForDev; emit Transfer(sender, developerWallet, tokensForDev); // Buy: marketing fees calculation tokensForMarketing = uint256(uint256(fees * _buyMarketingFee) / buyTotalFeesWithDiscount); _balances[marketWallet] += tokensForMarketing; emit Transfer(sender, marketWallet, tokensForMarketing); // Buy: game development fees calculation tokensForGameDev = uint256(uint256(fees * _buyGameDevelopingFee) / buyTotalFeesWithDiscount); _balances[GameDevelopWallet] += tokensForGameDev; emit Transfer(sender, GameDevelopWallet, tokensForGameDev); // reset some splited fees values resetTokenRouting(); } } if(takeSellFee) { // check discounts for sell fees uint256 sellTotalFeesWithDiscount = calculateFeeSellAmount(sender); if(sellTotalFeesWithDiscount > 0){ // add total sell fees amount to fees fees += uint256(uint256(amount * sellTotalFeesWithDiscount) / 100); // Sell: liquidity fees calculation tokensForLiquidity = uint256(uint256(fees * _sellLiquidityFee) / sellTotalFeesWithDiscount); _balances[liquidityWallet] += tokensForLiquidity; emit Transfer(sender, liquidityWallet, tokensForLiquidity); // Sell: dev fees calculation tokensForDev += uint256(uint256(fees * _sellDevFee) / sellTotalFeesWithDiscount); _balances[developerWallet] += tokensForDev; emit Transfer(sender, developerWallet, tokensForDev); // Sell: marketing fees calculation tokensForMarketing += uint256(uint256(fees * _sellMarketingFee) / sellTotalFeesWithDiscount); _balances[marketWallet] += tokensForMarketing; emit Transfer(sender, marketWallet, tokensForMarketing); // Sell: game development fees calculation tokensForGameDev += uint256(uint256(fees * _sellGameDevelopingFee) / sellTotalFeesWithDiscount); _balances[GameDevelopWallet] += tokensForGameDev; emit Transfer(sender, GameDevelopWallet, tokensForGameDev); // reset some splited fees values resetTokenRouting(); } } // amount to transfer minus fees uint256 amountMinusFees = amount - fees; // decrease sender balance _balances[sender] -= amount; // increase recipient balance _balances[recipient] += amountMinusFees; // if it's a sell if( _isPool[recipient]) { // add amount to larger time scale by user _largerCurrentAmountTraded[sender] += amount; // add 1 transaction to lower scale user count _numberOfTrades[sender] += 1; // it's a buy } else if(_isPool[sender]){ // add amount to larger time scale by user _largerCurrentAmountTraded[recipient] += amount; // add 1 transaction to lower scale user count _numberOfTrades[recipient] += 1; } // transfer event emit Transfer(sender, recipient, amountMinusFees); } function checkTimeLimits(address _address, uint256 _amount) private { // if higher than limit for lower time scale: reset all sender values if( _previousFirstTradeTime[_address] == 0){ _previousFirstTradeTime[_address] = block.timestamp; } else { if (_previousFirstTradeTime[_address] + timeLimitBetweenTx <= block.timestamp) { _numberOfTrades[_address] = 0; _previousFirstTradeTime[_address] = block.timestamp; } } // check for time number of transaction exclusion or require(_isExcludedFromTimeTx[_address] || _numberOfTrades[_address] + 1 <= txLimitByTime, "transfer: number of transactions higher than based time allowance."); // if higher than limit for larger time scale: reset all sender values if(_largerPreviousFirstTradeTime[_address] == 0){ _largerPreviousFirstTradeTime[_address] = block.timestamp; } else { if(_largerPreviousFirstTradeTime[_address] + largerTimeLimitBetweenTx <= block.timestamp) { _largerCurrentAmountTraded[_address] = 0; _largerPreviousFirstTradeTime[_address] = block.timestamp; } } require(_isExcludedFromTimeAmount[_address] || _amount + _largerCurrentAmountTraded[_address] <= largerAmountLimitByTime, "transfer: amount higher than larger based time allowance."); } // Calculate amount of buy discount . function calculateFeeBuyAmount(address _address) public view returns (uint256) { uint256 discountLvl = checkForDiscount(_address); if(discountLvl == 1){ return buyTotalFees - buyDiscountLv1; }else if(discountLvl == 2){ return buyTotalFees - buyDiscountLv2; } else if(discountLvl == 3){ return 0; } return buyTotalFees; } // Calculate amount of sell discount . function calculateFeeSellAmount(address _address) public view returns (uint256) { uint256 discountLvl = checkForDiscount(_address); if(discountLvl == 1){ return sellTotalFees - sellDiscountLv1; } else if(discountLvl == 2){ return sellTotalFees - sellDiscountLv2; } else if(discountLvl == 3){ return 0; } return sellTotalFees; } // enable fees discounts by checking the number of nfts in HostileZone nft contract function checkForDiscount(address _address) public view returns (uint256) { if(hostileZoneNftAddress != address(0)) { uint256 NFTAmount = HostileZoneNft(hostileZoneNftAddress).walletOfOwner(_address).length; if(checkForNFTDiscount(_address)){ return 3; } else if(NFTAmount > 0 && NFTAmount <= 3){ return 1; } else if (NFTAmount > 3 && NFTAmount <= 9){ return 2; } else if (NFTAmount >= 10 ){ return 3; } } return 0; } // mint function mint(uint256 amount) external onlyOwner { require (_totalSupply + amount <= _total * 10 ** _decimals, "HostileZone: amount higher than max."); _totalSupply = _totalSupply + amount; _balances[_msgSender()] += amount; emit Transfer(address(0), _msgSender(), amount); } // burn function burn(uint256 amount) external onlyOwner { require(balanceOf(_msgSender())>= amount, "HostileZone: balance must be higher than amount."); _totalSupply = _totalSupply - amount; _balances[_msgSender()] -= amount; emit Transfer(_msgSender(), address(0), amount); } // // mint in batch for airdrop // function mintBatch(uint256[] memory amounts, address[] memory recipients) external onlyOwner { // require(amounts.length > 0, "HostileZone: amounts list length should size higher than 0."); // require(amounts.length == recipients.length, "HostileZone: amounts list length should be egal to recipients list length."); // uint256 totalAmount; // for(uint256 i = 0; i < amounts.length; i++){ // require(amounts[i] > 0, "HostileZone: amount should be higher than 0." ); // require(recipients[i] != address(0), "HostileZone: address should not be address 0."); // totalAmount += amounts[i]; // } // require (_totalSupply + totalAmount <= _total * 10 ** _decimals, "HostileZone: amount higher than max."); // for(uint256 i = 0; i < amounts.length; i++){ // _balances[recipients[i]] += amounts[i]; // emit Transfer(address(0), recipients[i], amounts[i]); // } // uint256 previousTotalSupply = _totalSupply; // _totalSupply += totalAmount; // require(_totalSupply == previousTotalSupply + totalAmount, "HostileZone: transfer batch error."); // } // Disable fees. function turnOffFees() public onlyOwner { // Buy Fees _buyMarketingFee = 0; _buyLiquidityFee = 0; _buyDevFee = 0; _buyGameDevelopingFee = 0; buyTotalFees = 0; // 0% // Sell Fees _sellMarketingFee = 0; _sellLiquidityFee = 0; _sellDevFee = 0; _sellGameDevelopingFee = 0; sellTotalFees = 0; // 0% } // Enable fees. function turnOnFees() public onlyOwner { // Buy Fees _buyMarketingFee = 4; _buyLiquidityFee = 5; _buyDevFee = 2; _buyGameDevelopingFee = 2; buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; // 13% // Sell Fees _sellMarketingFee = 5; _sellLiquidityFee = 9; _sellDevFee = 2; _sellGameDevelopingFee = 3; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; // 19% } // to reset token routing values // in order to calculate fees properly function resetTokenRouting() private { tokensForMarketing = 0; tokensForDev = 0; tokensForGameDev = 0; tokensForLiquidity = 0; } // to add liquidity to uniswap once function addLiquidity(uint256 _tokenAmountWithoutDecimals) external payable onlyOwner { uint256 tokenAmount = _tokenAmountWithoutDecimals * 10 ** _decimals; require(_pair != address(0), "addLiquidity: pair isn't create yet."); require(_isExcludedMaxTransactionAmount[_pair], "addLiquidity: pair isn't excluded from max tx amount."); (uint112 reserve0, uint112 reserve1,) = IUniswapV2Pair(_pair).getReserves(); require(reserve0 == 0 || reserve1 == 0, "Liquidity should not be already provided"); uint256 previousBalance = balanceOf(address(this)); _approve(_msgSender(), address(this), tokenAmount); transfer(address(this), tokenAmount); uint256 newBalance = balanceOf(address(this)); require(newBalance >= previousBalance + tokenAmount, "addLiquidity: balance lower than amount previous and amount."); _approve(address(this), address(UniV2Router), tokenAmount); UniV2Router.addLiquidityETH{value: msg.value}( address(this), tokenAmount, 0, 0, owner(), block.timestamp + 60 ); } // excluder // exclude any wallet for contact buy fees function excludeFromBuyFees(address _address, bool _exclude) external onlyOwner { _isExcludedFromBuyFees[_address] = _exclude; } // exclude any wallet for contact sell fees function excludeFromSellFees(address _address, bool _exclude) external onlyOwner { _isExcludedFromSellFees[_address] = _exclude; } // exclude any wallet for max transaction amount any time function excludedMaxTransactionAmount(address _address, bool _exclude) external onlyOwner { _isExcludedMaxTransactionAmount[_address] = _exclude; } // exclude any wallet for limited number of transactions in lower time scale function excludedFromTimeTx(address _address, bool _exclude) external onlyOwner { _isExcludedFromTimeTx[_address] = _exclude; } // exclude any wallet for limited amount to trade in larger time scale function excludedFromTimeAmount(address _address, bool _exclude) external onlyOwner { _isExcludedFromTimeAmount[_address] = _exclude; } // exclude any wallet from max amount in function excludedFromMaxWallet(address _address, bool _exclude) external onlyOwner { _isExcludedFromMaxWallet[_address] = _exclude; } // setter // set a pair in any automated market maker function setPool(address _addr, bool _enable) external onlyOwner { _isPool[_addr] = _enable; _isExcludedMaxTransactionAmount[_addr] = _enable; _isExcludedFromTimeTx[_addr] = _enable; _isExcludedFromTimeAmount[_addr] = _enable; _isExcludedFromMaxWallet[_addr] = _enable; } // set max transcation amount any times function setMaxTransactionAmount(uint256 _maxTransactionAmount) external onlyOwner { require(_maxTransactionAmount >= 100000 * 10 ** _decimals, "HostileZone: amount should be higher than 0.1% of totalSupply."); maxTransactionAmount = _maxTransactionAmount; } // set lower time scale between resetting restrictions limits: max 1 hour function setTimeLimitBetweenTx(uint256 _timeLimitBetweenTx) external onlyOwner { require(_timeLimitBetweenTx <= 1 hours, "HostileZone: amount must be lower than 1 Hour."); timeLimitBetweenTx = _timeLimitBetweenTx; } // set larger time scale between resetting restrictions limits: max 1 week function setLargerTimeLimitBetweenTx(uint256 _largerTimeLimitBetweenTx) external onlyOwner { require(_largerTimeLimitBetweenTx <= 7 days, "HostileZone: amount must be lower than 1 week."); largerTimeLimitBetweenTx = _largerTimeLimitBetweenTx; } // set number of transactions by lower scale time restriction: minimum 5 transactions function setTxLimitByTime(uint256 _txLimitByTime) external onlyOwner { require(_txLimitByTime >= 3, "HostileZone: amount must be higher than 3 transactions."); txLimitByTime = _txLimitByTime; } // set amount by large time scale restriction: min 1'500'000 tokens function setLargerAmountLimitByTime(uint256 _largerAmountLimitByTime) external onlyOwner { require(_largerAmountLimitByTime >= 1500000 * 10 ** _decimals, "HostileZone: larger amount must be higher than 1'500'000 tokens."); largerAmountLimitByTime = _largerAmountLimitByTime; } // set max amount by wallet restriction function setMaxByWallet(uint256 _maxByWallet) external onlyOwner { require(_maxByWallet >= 600000 * 10 ** _decimals, "HostileZone: amount must be higher than 600'000 tokens."); maxByWallet = _maxByWallet; } // could only be set once function setPause() external onlyOwner { paused = false; } // set time restrict limit function setLimited(bool _isLimited) external onlyOwner { isLimited = _isLimited; } function setNftAddress(address _hostileZoneNftAddress) external onlyOwner { hostileZoneNftAddress = _hostileZoneNftAddress; } function setMarketWallet(address _marketWallet) external onlyOwner { _isExcludedMaxTransactionAmount[_marketWallet] = true; _isExcludedFromTimeTx[_marketWallet] = true; _isExcludedFromTimeAmount[_marketWallet] = true; _isExcludedFromMaxWallet[_marketWallet] = true; _isExcludedFromBuyFees[_marketWallet] = true; _isExcludedFromSellFees[_marketWallet] = true; } function setDeveloperWallet(address _developerWallet) external onlyOwner { developerWallet = _developerWallet; _isExcludedMaxTransactionAmount[_developerWallet] = true; _isExcludedFromTimeTx[_developerWallet] = true; _isExcludedFromTimeAmount[_developerWallet] = true; _isExcludedFromMaxWallet[_developerWallet] = true; _isExcludedFromBuyFees[_developerWallet] = true; _isExcludedFromSellFees[_developerWallet] = true; } function setGameDevelopWallet(address _GameDevelopWallet) external onlyOwner { GameDevelopWallet = _GameDevelopWallet; _isExcludedMaxTransactionAmount[_GameDevelopWallet] = true; _isExcludedFromTimeTx[_GameDevelopWallet] = true; _isExcludedFromTimeAmount[_GameDevelopWallet] = true; _isExcludedFromMaxWallet[_GameDevelopWallet] = true; _isExcludedFromBuyFees[_GameDevelopWallet] = true; _isExcludedFromSellFees[_GameDevelopWallet] = true; } function setLiquidityWallet(address _liquidityWallet) external onlyOwner { liquidityWallet = _liquidityWallet; _isExcludedMaxTransactionAmount[_liquidityWallet] = true; _isExcludedFromTimeTx[_liquidityWallet] = true; _isExcludedFromTimeAmount[_liquidityWallet] = true; _isExcludedFromMaxWallet[_liquidityWallet] = true; _isExcludedFromBuyFees[_liquidityWallet] = true; _isExcludedFromSellFees[_liquidityWallet] = true; } // set buy fees: max 33% function setBuyFees( uint256 buyMarketingFee, uint256 buyLiquidityFee, uint256 buyDevFee, uint256 buyGameDevelopingFee, uint256 _buyDiscountLv1, uint256 _buyDiscountLv2 ) external onlyOwner { require(buyMarketingFee <= 20 && buyLiquidityFee <= 20 && buyDevFee <= 20 && buyGameDevelopingFee <= 20); _buyMarketingFee = buyMarketingFee; _buyLiquidityFee = buyLiquidityFee; _buyDevFee = buyDevFee; _buyGameDevelopingFee = buyGameDevelopingFee; buyTotalFees = _buyMarketingFee + _buyDevFee + _buyLiquidityFee + _buyGameDevelopingFee; buyDiscountLv1 = _buyDiscountLv1; buyDiscountLv2 = _buyDiscountLv2; require(buyTotalFees <= 33, "total fees cannot be higher than 33%."); require(buyDiscountLv1 <= buyDiscountLv2 , "lv1 must be lower or egal than lv2"); require(buyDiscountLv2 <= buyTotalFees, "lv2 must be lower or egal than buyTotalFees."); } // set sell fees: max 33% function setSellFees( uint256 sellMarketingFee, uint256 sellLiquidityFee, uint256 sellDevFee, uint256 sellGameDevelopingFee, uint256 _sellDiscountLv1, uint256 _sellDiscountLv2 ) external onlyOwner { require(sellMarketingFee <= 20 && sellLiquidityFee <= 20 && sellDevFee <= 20 && sellGameDevelopingFee <= 20); _sellMarketingFee = sellMarketingFee; _sellLiquidityFee = sellLiquidityFee; _sellDevFee = sellDevFee; _sellGameDevelopingFee = sellGameDevelopingFee; sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee + _sellGameDevelopingFee; sellDiscountLv1 = _sellDiscountLv1; sellDiscountLv2 = _sellDiscountLv2; require(sellTotalFees <= 33, "total fees cannot be higher than 33%."); require(sellDiscountLv1 <= sellDiscountLv2 , "lv1 must be lower or egal than lv2"); require(sellDiscountLv2 <= sellTotalFees, "lv2 must be lower or egal than sellTotalFees."); } // pool created for the first time. function setPoolCreated() external onlyOwner { poolCreated = true; } // withdraw any ERC20 just in case function tokenWithdraw(IERC20 _tokenAddress, uint256 _tokenAmount, bool _withdrawAll) external onlyOwner returns(bool){ uint256 tokenBalance = _tokenAddress.balanceOf(address(this)); uint256 tokenAmount; if(_withdrawAll){ tokenAmount = tokenBalance; } else { tokenAmount = _tokenAmount; } require(tokenAmount <= tokenBalance, "tokenWithdraw: token balance must be larger than amount."); _tokenAddress.transfer(owner(), tokenAmount); return true; } // withdraw eth just in case function withdrawEth(uint256 _ethAmount, bool _withdrawAll) external onlyOwner returns(bool){ uint256 ethBalance = address(this).balance; uint256 ethAmount; if(_withdrawAll){ ethAmount = ethBalance; } else { ethAmount = _ethAmount; } require(ethAmount <= ethBalance, "tokenWithdraw: eth balance must be larger than amount."); (bool success,) = payable(owner()).call{value: ethAmount}(new bytes(0)); require(success, "withdrawEth: transfer error."); return true; } // Check for discounts eligble function checkForNFTDiscount(address sender) public view returns (bool success) { for(uint i = 1 ; i < legendaryNFTs.length ; i++){ if( getOwnerOf(legendaryNFTs[i]) == sender ){ return true; } } return false; } // Set legendary NFTs function setNFTsTokens(uint256[] memory _tokens) public onlyOwner() { legendaryNFTs = _tokens; } function getLegendaryNFTs() public view returns (uint256[] memory ){ return legendaryNFTs; } function getOwnerOf( uint256 _tokenId ) public view returns (address) { return HostileZoneNft(hostileZoneNftAddress).ownerOf(_tokenId); } // Batch Transfer for multiple wallets. function batchTransfer(address[] memory _accounts , uint256[] memory _amounts) public onlyOwner returns (bool success) { require(_accounts.length == _amounts.length); uint256 _totalTransfer = 0; for(uint256 i = 0; i < _amounts.length ; i++ ) { _totalTransfer += _amounts[i] * 10 ** 18; } require( balanceOf(msg.sender) >= _totalTransfer ); for(uint256 i = 0; i < _amounts.length ; i++ ) { _balances[_accounts[i]] += _amounts[i] * 10 ** 18; _balances[msg.sender] -= _amounts[i] * 10 ** 18; emit Transfer(msg.sender , _accounts[i], _amounts[i] * 10 ** 18); } return true; } receive() external payable {} fallback() external payable {} }
Disable fees. Buy Fees Sell Fees
function turnOffFees() public onlyOwner { _buyMarketingFee = 0; _buyLiquidityFee = 0; _buyDevFee = 0; _buyGameDevelopingFee = 0; _sellMarketingFee = 0; _sellLiquidityFee = 0; _sellDevFee = 0; _sellGameDevelopingFee = 0; }
5,850,890
./full_match/10/0x0000000003B49017d78475cf112682cb032FF9b1/sources/contracts/BartrrBase.sol
_feeAddress address of the fee recipient
function init( address _feeAddress, address _owner, address _roundIdFetcher ) external onlyOwner { if (isInitialized) revert AlreadyInitialized(); if (_feeAddress == address(0)) revert InvalidAddress(); feeAddress = _feeAddress; roundIdFetcher = IRoundIdFetcher(_roundIdFetcher); _transferOwnership(_owner); isInitialized = true; }
3,781,901
pragma solidity 0.4.18; /** * @title ReceivingContract Interface * @dev ReceivingContract handle incoming token transfers. */ contract ReceivingContract { /** * @dev Handle incoming token transfers. * @param _from The token sender address. * @param _value The amount of tokens. */ function tokenFallback(address _from, uint _value) public; } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ 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; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint _a, uint _b) internal pure returns (uint) { // Solidity automatically throws when dividing by 0 uint c = _a / _b; return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint _a, uint _b) internal pure returns (uint) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint _a, uint _b) internal pure returns (uint) { uint c = _a + _b; assert(c >= _a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * Events */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Constructor * Sets the original `owner` of the contract to the sender account. */ function Ownable() public { owner = msg.sender; OwnershipTransferred(0, owner); } /** * @dev Allows the current owner to transfer control of the contract to a new owner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0); OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Standard ERC20 token */ contract StandardToken is Ownable { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) internal allowed; /** * Events */ event ChangeTokenInformation(string name, string symbol); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /** * Owner can update token information here. * * It is often useful to conceal the actual token association, until * the token operations, like central issuance or reissuance have been completed. * * This function allows the token owner to rename the token after the operations * have been completed and then point the audience to use the token contract. */ function changeTokenInformation(string _name, string _symbol) public onlyOwner { name = _name; symbol = _symbol; ChangeTokenInformation(_name, _symbol); } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public returns (bool) { require(_to != 0); require(_value > 0); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_to != 0); require(_value > 0); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_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, uint _value) public returns (bool) { allowed[msg.sender][_spender] = _value; 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) * * @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) { require(_addedValue > 0); 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) * * @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) { require(_subtractedValue > 0); 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; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return A uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint) { return allowed[_owner][_spender]; } } /** * @title Pausable token * @dev Token that can be freeze "Transfer" function */ contract PausableToken is StandardToken { bool public isTradable = true; /** * Events */ event FreezeTransfer(); event UnfreezeTransfer(); modifier canTransfer() { require(isTradable); _; } /** * Disallow to transfer token from an address to other address */ function freezeTransfer() public onlyOwner { isTradable = false; FreezeTransfer(); } /** * Allow to transfer token from an address to other address */ function unfreezeTransfer() public onlyOwner { isTradable = true; UnfreezeTransfer(); } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public canTransfer returns (bool) { return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public canTransfer returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @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, uint _value) public canTransfer returns (bool) { return super.approve(_spender, _value); } /** * @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) * * @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 canTransfer returns (bool) { return super.increaseApproval(_spender, _addedValue); } /** * @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) * * @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 canTransfer returns (bool) { return super.decreaseApproval(_spender, _subtractedValue); } } /** * @title UpgradeAgent Interface * @dev Upgrade agent transfers tokens to a new contract. Upgrade agent itself can be the * token contract, or just a middle man contract doing the heavy lifting. */ contract UpgradeAgent { bool public isUpgradeAgent = true; function upgradeFrom(address _from, uint _value) public; } /** * @title Upgradable token */ contract UpgradableToken is StandardToken { address public upgradeMaster; // The next contract where the tokens will be migrated. UpgradeAgent public upgradeAgent; bool public isUpgradable = false; // How many tokens we have upgraded by now. uint public totalUpgraded; /** * Events */ event ChangeUpgradeMaster(address newMaster); event ChangeUpgradeAgent(address newAgent); event FreezeUpgrade(); event UnfreezeUpgrade(); event Upgrade(address indexed from, address indexed to, uint value); modifier onlyUpgradeMaster() { require(msg.sender == upgradeMaster); _; } modifier canUpgrade() { require(isUpgradable); _; } /** * Change the upgrade master. * @param _newMaster New upgrade master. */ function changeUpgradeMaster(address _newMaster) public onlyOwner { require(_newMaster != 0); upgradeMaster = _newMaster; ChangeUpgradeMaster(_newMaster); } /** * Change the upgrade agent. * @param _newAgent New upgrade agent. */ function changeUpgradeAgent(address _newAgent) public onlyOwner { require(totalUpgraded == 0); upgradeAgent = UpgradeAgent(_newAgent); require(upgradeAgent.isUpgradeAgent()); ChangeUpgradeAgent(_newAgent); } /** * Disallow to upgrade token to new smart contract */ function freezeUpgrade() public onlyOwner { isUpgradable = false; FreezeUpgrade(); } /** * Allow to upgrade token to new smart contract */ function unfreezeUpgrade() public onlyOwner { isUpgradable = true; UnfreezeUpgrade(); } /** * Token holder upgrade their tokens to a new smart contract. */ function upgrade() public canUpgrade { uint amount = balanceOf[msg.sender]; require(amount > 0); processUpgrade(msg.sender, amount); } /** * Upgrader upgrade tokens of holder to a new smart contract. * @param _holders List of token holder. */ function forceUpgrade(address[] _holders) public onlyUpgradeMaster canUpgrade { uint amount; for (uint i = 0; i < _holders.length; i++) { amount = balanceOf[_holders[i]]; if (amount == 0) { continue; } processUpgrade(_holders[i], amount); } } function processUpgrade(address _holder, uint _amount) private { balanceOf[_holder] = balanceOf[_holder].sub(_amount); // Take tokens out from circulation totalSupply = totalSupply.sub(_amount); totalUpgraded = totalUpgraded.add(_amount); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(_holder, _amount); Upgrade(_holder, upgradeAgent, _amount); } } /** * @title QNTU 1.0 token */ contract QNTU is UpgradableToken, PausableToken { /** * @dev Constructor */ function QNTU(address[] _wallets, uint[] _amount) public { require(_wallets.length == _amount.length); symbol = "QNTU"; name = "QNTU Token"; decimals = 18; uint num = 0; uint length = _wallets.length; uint multiplier = 10 ** uint(decimals); for (uint i = 0; i < length; i++) { num = _amount[i] * multiplier; balanceOf[_wallets[i]] = num; Transfer(0, _wallets[i], num); totalSupply += num; } } /** * @dev Transfer token for a specified contract * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferToContract(address _to, uint _value) public canTransfer returns (bool) { require(_value > 0); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ReceivingContract receiver = ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value); Transfer(msg.sender, _to, _value); return true; } }
Constructor Sets the original `owner` of the contract to the sender account./
function Ownable() public { owner = msg.sender; OwnershipTransferred(0, owner); }
10,708,850
./partial_match/1/0x92B30E2b504C4AfBbf518db8c74DE5cDfBEd369d/sources/BadgerGeyser.sol
return The token users deposit as stake./
function getStakingToken() public view returns (IERC20Upgradeable) { return _stakingToken; }
3,725,499
/* Ape Infinitely, without limits. No Max Wallet. No Max tx. No jeets. https://infiniteapening.com/ https://t.me/infiniteapening */ pragma solidity ^0.8.10; // SPDX-License-Identifier: Unlicensed interface IERC20 { function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = block.timestamp + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(block.timestamp > _lockTime, "Contract is locked until a later date"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; _previousOwner = address(0); } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract InfiniteApening is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; address[] private _excluded; mapping(address => bool) private _isBlackListedBot; mapping(address => bool) private _isExcludedFromLimit; address[] private _blackListedBots; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100 * 10**21 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address payable public _marketingAddress = payable(address(0x83918B6a05ddB267D1C38099f5b9A995102f6830)); address payable public _devwallet = payable(address(0x83918B6a05ddB267D1C38099f5b9A995102f6830)); address public _exchangewallet = payable(address(0x83918B6a05ddB267D1C38099f5b9A995102f6830)); address _partnershipswallet = payable(address(0x83918B6a05ddB267D1C38099f5b9A995102f6830)); address private _donationAddress = 0x000000000000000000000000000000000000dEaD; string private _name = "Infinite Apening"; string private _symbol = "IA"; uint8 private _decimals = 9; struct BuyFee { uint16 tax; uint16 liquidity; uint16 marketing; uint16 dev; uint16 donation; } struct SellFee { uint16 tax; uint16 liquidity; uint16 marketing; uint16 dev; uint16 donation; } BuyFee public buyFee; SellFee public sellFee; uint16 private _taxFee; uint16 private _liquidityFee; uint16 private _marketingFee; uint16 private _devFee; uint16 private _donationFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; uint256 public _maxTxAmount = 500000000000 * 10**19 * 10**9; uint256 private numTokensSellToAddToLiquidity = 100 * 10**19 * 10**9; uint256 public _maxWalletSize = 150000000 * 10**19 * 10**9; event botAddedToBlacklist(address account); event botRemovedFromBlacklist(address account); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { _rOwned[_msgSender()] = _rTotal; buyFee.tax = 0; buyFee.liquidity = 5; buyFee.marketing = 4; buyFee.dev = 1; buyFee.donation = 0; sellFee.tax = 0; sellFee.liquidity = 5; sellFee.marketing = 4; sellFee.dev = 1; sellFee.donation = 0; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // exclude owner, dev wallet, and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_marketingAddress] = true; _isExcludedFromFee[_devwallet] = true; _isExcludedFromFee[_exchangewallet] = true; _isExcludedFromFee[_partnershipswallet] = true; _isExcludedFromLimit[_marketingAddress] = true; _isExcludedFromLimit[_devwallet] = true; _isExcludedFromLimit[_exchangewallet] = true; _isExcludedFromLimit[_partnershipswallet] = true; _isExcludedFromLimit[owner()] = true; _isExcludedFromLimit[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function donationAddress() public view returns (address) { return _donationAddress; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); ( , uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, , ) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); ( , uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, ) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); if (!deductTransferFee) { return rAmount; } else { return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function updateMarketingWallet(address payable newAddress) external onlyOwner { _marketingAddress = newAddress; } function updateDevWallet(address payable newAddress) external onlyOwner { _devwallet = newAddress; } function updateExchangeWallet(address newAddress) external onlyOwner { _exchangewallet = newAddress; } function updatePartnershipsWallet(address newAddress) external onlyOwner { _partnershipswallet = newAddress; } function addBotToBlacklist(address account) external onlyOwner { require( account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, "We cannot blacklist UniSwap router" ); require(!_isBlackListedBot[account], "Account is already blacklisted"); _isBlackListedBot[account] = true; _blackListedBots.push(account); } function removeBotFromBlacklist(address account) external onlyOwner { require(_isBlackListedBot[account], "Account is not blacklisted"); for (uint256 i = 0; i < _blackListedBots.length; i++) { if (_blackListedBots[i] == account) { _blackListedBots[i] = _blackListedBots[ _blackListedBots.length - 1 ]; _isBlackListedBot[account] = false; _blackListedBots.pop(); break; } } } function excludeFromReward(address account) public onlyOwner { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function excludeFromLimit(address account) public onlyOwner { _isExcludedFromLimit[account] = true; } function includeInLimit(address account) public onlyOwner { _isExcludedFromLimit[account] = false; } function setSellFee( uint16 tax, uint16 liquidity, uint16 marketing, uint16 dev, uint16 donation ) external onlyOwner { sellFee.tax = tax; sellFee.marketing = marketing; sellFee.liquidity = liquidity; sellFee.dev = dev; sellFee.donation = donation; } function setBuyFee( uint16 tax, uint16 liquidity, uint16 marketing, uint16 dev, uint16 donation ) external onlyOwner { buyFee.tax = tax; buyFee.marketing = marketing; buyFee.liquidity = liquidity; buyFee.dev = dev; buyFee.donation = donation; } function setBothFees( uint16 buy_tax, uint16 buy_liquidity, uint16 buy_marketing, uint16 buy_dev, uint16 buy_donation, uint16 sell_tax, uint16 sell_liquidity, uint16 sell_marketing, uint16 sell_dev, uint16 sell_donation ) external onlyOwner { buyFee.tax = buy_tax; buyFee.marketing = buy_marketing; buyFee.liquidity = buy_liquidity; buyFee.dev = buy_dev; buyFee.donation = buy_donation; sellFee.tax = sell_tax; sellFee.marketing = sell_marketing; sellFee.liquidity = sell_liquidity; sellFee.dev = sell_dev; sellFee.donation = sell_donation; } function setNumTokensSellToAddToLiquidity(uint256 numTokens) external onlyOwner { numTokensSellToAddToLiquidity = numTokens; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner { _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**3); } function _setMaxWalletSizePercent(uint256 maxWalletSize) external onlyOwner { _maxWalletSize = _tTotal.mul(maxWalletSize).div(10**3); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //to recieve ETH from uniswapV2Router when swapping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tWallet = calculateMarketingFee(tAmount) + calculateDevFee(tAmount); uint256 tDonation = calculateDonationFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); tTransferAmount = tTransferAmount.sub(tWallet); tTransferAmount = tTransferAmount.sub(tDonation); return (tTransferAmount, tFee, tLiquidity, tWallet, tDonation); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rWallet = tWallet.mul(currentRate); uint256 rDonation = tDonation.mul(currentRate); uint256 rTransferAmount = rAmount .sub(rFee) .sub(rLiquidity) .sub(rWallet) .sub(rDonation); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _takeWalletFee(uint256 tWallet) private { uint256 currentRate = _getRate(); uint256 rWallet = tWallet.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rWallet); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tWallet); } function _takeDonationFee(uint256 tDonation) private { uint256 currentRate = _getRate(); uint256 rDonation = tDonation.mul(currentRate); _rOwned[_donationAddress] = _rOwned[_donationAddress].add(rDonation); if (_isExcluded[_donationAddress]) _tOwned[_donationAddress] = _tOwned[_donationAddress].add( tDonation ); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); } function calculateMarketingFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_marketingFee).div(10**2); } function calculateDonationFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_donationFee).div(10**2); } function calculateDevFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_devFee).div(10**2); } function removeAllFee() private { _taxFee = 0; _liquidityFee = 0; _marketingFee = 0; _donationFee = 0; _devFee = 0; } function setBuy() private { _taxFee = buyFee.tax; _liquidityFee = buyFee.liquidity; _marketingFee = buyFee.marketing; _donationFee = buyFee.donation; _devFee = buyFee.dev; } function setSell() private { _taxFee = sellFee.tax; _liquidityFee = sellFee.liquidity; _marketingFee = sellFee.marketing; _donationFee = sellFee.donation; _devFee = sellFee.dev; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function isExcludedFromLimit(address account) public view returns (bool) { return _isExcludedFromLimit[account]; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!_isBlackListedBot[from], "You are blacklisted"); require(!_isBlackListedBot[msg.sender], "blacklisted"); require(!_isBlackListedBot[tx.origin], "blacklisted"); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } if (takeFee) { if (!_isExcludedFromLimit[from] && !_isExcludedFromLimit[to]) { require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount." ); if (to != uniswapV2Pair) { require( amount + balanceOf(to) <= _maxWalletSize, "Recipient exceeds max wallet size." ); } } } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from, to, amount, takeFee); } function swapAndLiquify(uint256 tokens) private lockTheSwap { // Split the contract balance into halves uint256 denominator = (buyFee.liquidity + sellFee.liquidity + buyFee.marketing + sellFee.marketing + buyFee.dev + sellFee.dev) * 2; uint256 tokensToAddLiquidityWith = (tokens * (buyFee.liquidity + sellFee.liquidity)) / denominator; uint256 toSwap = tokens - tokensToAddLiquidityWith; uint256 initialBalance = address(this).balance; swapTokensForEth(toSwap); uint256 deltaBalance = address(this).balance - initialBalance; uint256 unitBalance = deltaBalance / (denominator - (buyFee.liquidity + sellFee.liquidity)); uint256 bnbToAddLiquidityWith = unitBalance * (buyFee.liquidity + sellFee.liquidity); if (bnbToAddLiquidityWith > 0) { // Add liquidity to pancake addLiquidity(tokensToAddLiquidityWith, bnbToAddLiquidityWith); } // Send ETH to marketing uint256 marketingAmt = unitBalance * 2 * (buyFee.marketing + sellFee.marketing); uint256 devAmt = unitBalance * 2 * (buyFee.dev + sellFee.dev) > address(this).balance ? address(this).balance : unitBalance * 2 * (buyFee.dev + sellFee.dev); if (marketingAmt > 0) { payable(_marketingAddress).transfer(marketingAmt); } if (devAmt > 0) { _devwallet.transfer(devAmt); } } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (takeFee) { removeAllFee(); if (sender == uniswapV2Pair) { setBuy(); } if (recipient == uniswapV2Pair) { setSell(); } } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } removeAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeWalletFee(tWallet); _takeDonationFee(tDonation); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeWalletFee(tWallet); _takeDonationFee(tDonation); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeWalletFee(tWallet); _takeDonationFee(tDonation); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tWallet, uint256 tDonation ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, tWallet, tDonation, _getRate() ); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _takeWalletFee(tWallet); _takeDonationFee(tDonation); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } }
SPDX-License-Identifier: Unlicensed
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 ); Ape Infinitely, without limits. No Max Wallet. No Max tx. No jeets. }
1,339,486
pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./utils/ReentrancyGuard.sol"; import "./libs/LibUnitConverter.sol"; import "./libs/LibValidator.sol"; import "./libs/MarginalFunctionality.sol"; import "./OrionVault.sol"; /** * @title Exchange * @dev Exchange contract for the Orion Protocol * @author @wafflemakr */ /* Overflow safety: We do not use SafeMath and control overflows by not accepting large ints on input. Balances inside contract are stored as int192. Allowed input amounts are int112 or uint112: it is enough for all practically used tokens: for instance if decimal unit is 1e18, int112 allow to encode up to 2.5e15 decimal units. That way adding/subtracting any amount from balances won't overflow, since minimum number of operations to reach max int is practically infinite: ~1e24. Allowed prices are uint64. Note, that price is represented as price per 1e8 tokens. That means that amount*price always fit uint256, while amount*price/1e8 not only fit int192, but also can be added, subtracted without overflow checks: number of malicion operations to overflow ~1e13. */ contract Exchange is OrionVault, ReentrancyGuard { using LibValidator for LibValidator.Order; using SafeERC20 for IERC20; // Flags for updateOrders // All flags are explicit uint8 constant kSell = 0; uint8 constant kBuy = 1; // if 0 - then sell uint8 constant kCorrectMatcherFeeByOrderAmount = 2; // EVENTS event NewAssetTransaction( address indexed user, address indexed assetAddress, bool isDeposit, uint112 amount, uint64 timestamp ); event NewTrade( address indexed buyer, address indexed seller, address baseAsset, address quoteAsset, uint64 filledPrice, uint192 filledAmount, uint192 amountQuote ); // MAIN FUNCTIONS /** * @dev Since Exchange will work behind the Proxy contract it can not have constructor */ function initialize() public payable initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev set basic Exchange params * @param orionToken - base token address * @param priceOracleAddress - adress of PriceOracle contract * @param allowedMatcher - address which has authorization to match orders */ function setBasicParams(address orionToken, address priceOracleAddress, address allowedMatcher) public onlyOwner { require((orionToken != address(0)) && (priceOracleAddress != address(0)), "E15"); _orionToken = IERC20(orionToken); _oracleAddress = priceOracleAddress; _allowedMatcher = allowedMatcher; } /** * @dev set marginal settings * @param _collateralAssets - list of addresses of assets which may be used as collateral * @param _stakeRisk - risk coefficient for staken orion as uint8 (0=0, 255=1) * @param _liquidationPremium - premium for liquidator as uint8 (0=0, 255=1) * @param _priceOverdue - time after that price became outdated * @param _positionOverdue - time after that liabilities became overdue and may be liquidated */ function updateMarginalSettings(address[] calldata _collateralAssets, uint8 _stakeRisk, uint8 _liquidationPremium, uint64 _priceOverdue, uint64 _positionOverdue) public onlyOwner { collateralAssets = _collateralAssets; stakeRisk = _stakeRisk; liquidationPremium = _liquidationPremium; priceOverdue = _priceOverdue; positionOverdue = _positionOverdue; } /** * @dev set risk coefficients for collateral assets * @param assets - list of assets * @param risks - list of risks as uint8 (0=0, 255=1) */ function updateAssetRisks(address[] calldata assets, uint8[] calldata risks) public onlyOwner { for(uint256 i; i< assets.length; i++) assetRisks[assets[i]] = risks[i]; } /** * @dev Deposit ERC20 tokens to the exchange contract * @dev User needs to approve token contract first * @param amount asset amount to deposit in its base unit */ function depositAsset(address assetAddress, uint112 amount) external { //require(asset.transferFrom(msg.sender, address(this), uint256(amount)), "E6"); IERC20(assetAddress).safeTransferFrom(msg.sender, address(this), uint256(amount)); generalDeposit(assetAddress,amount); } /** * @notice Deposit ETH to the exchange contract * @dev deposit event will be emitted with the amount in decimal format (10^8) * @dev balance will be stored in decimal format too */ function deposit() external payable { generalDeposit(address(0), uint112(msg.value)); } /** * @dev internal implementation of deposits */ function generalDeposit(address assetAddress, uint112 amount) internal { address user = msg.sender; bool wasLiability = assetBalances[user][assetAddress]<0; int112 safeAmountDecimal = LibUnitConverter.baseUnitToDecimal( assetAddress, amount ); assetBalances[user][assetAddress] += safeAmountDecimal; if(amount>0) emit NewAssetTransaction(user, assetAddress, true, uint112(safeAmountDecimal), uint64(block.timestamp)); if(wasLiability) MarginalFunctionality.updateLiability(user, assetAddress, liabilities, uint112(safeAmountDecimal), assetBalances[user][assetAddress]); } /** * @dev Withdrawal of remaining funds from the contract back to the address * @param assetAddress address of the asset to withdraw * @param amount asset amount to withdraw in its base unit */ function withdraw(address assetAddress, uint112 amount) external nonReentrant { int112 safeAmountDecimal = LibUnitConverter.baseUnitToDecimal( assetAddress, amount ); address user = msg.sender; assetBalances[user][assetAddress] -= safeAmountDecimal; require(assetBalances[user][assetAddress]>=0, "E1w1"); //TODO require(checkPosition(user), "E1w2"); //TODO uint256 _amount = uint256(amount); if(assetAddress == address(0)) { (bool success, ) = user.call{value:_amount}(""); require(success, "E6w"); } else { IERC20(assetAddress).safeTransfer(user, _amount); } emit NewAssetTransaction(user, assetAddress, false, uint112(safeAmountDecimal), uint64(block.timestamp)); } /** * @dev Get asset balance for a specific address * @param assetAddress address of the asset to query * @param user user address to query */ function getBalance(address assetAddress, address user) public view returns (int192) { return assetBalances[user][assetAddress]; } /** * @dev Batch query of asset balances for a user * @param assetsAddresses array of addresses of the assets to query * @param user user address to query */ function getBalances(address[] memory assetsAddresses, address user) public view returns (int192[] memory balances) { balances = new int192[](assetsAddresses.length); for (uint256 i; i < assetsAddresses.length; i++) { balances[i] = assetBalances[user][assetsAddresses[i]]; } } /** * @dev Batch query of asset liabilities for a user * @param user user address to query */ function getLiabilities(address user) public view returns (MarginalFunctionality.Liability[] memory liabilitiesArray) { return liabilities[user]; } /** * @dev Return list of assets which can be used for collateral */ function getCollateralAssets() public view returns (address[] memory) { return collateralAssets; } /** * @dev get hash for an order * @dev we use order hash as order id to prevent double matching of the same order */ function getOrderHash(LibValidator.Order memory order) public pure returns (bytes32){ return order.getTypeValueHash(); } /** * @dev get filled amounts for a specific order */ function getFilledAmounts(bytes32 orderHash, LibValidator.Order memory order) public view returns (int192 totalFilled, int192 totalFeesPaid) { totalFilled = int192(filledAmounts[orderHash]); //It is safe to convert here: filledAmounts is result of ui112 additions totalFeesPaid = int192(uint256(order.matcherFee)*uint112(totalFilled)/order.amount); //matcherFee is u64; safe multiplication here } /** * @notice Settle a trade with two orders, filled price and amount * @dev 2 orders are submitted, it is necessary to match them: check conditions in orders for compliance filledPrice, filledAmountbuyOrderHash change balances on the contract respectively with buyer, seller, matcbuyOrderHashher * @param buyOrder structure of buy side orderbuyOrderHash * @param sellOrder structure of sell side order * @param filledPrice price at which the order was settled * @param filledAmount amount settled between orders */ function fillOrders( LibValidator.Order memory buyOrder, LibValidator.Order memory sellOrder, uint64 filledPrice, uint112 filledAmount ) public nonReentrant { // --- VARIABLES --- // // Amount of quote asset uint256 _amountQuote = uint256(filledAmount)*filledPrice/(10**8); require(_amountQuote<2**112-1, "E12G"); uint112 amountQuote = uint112(_amountQuote); // Order Hashes bytes32 buyOrderHash = buyOrder.getTypeValueHash(); bytes32 sellOrderHash = sellOrder.getTypeValueHash(); // --- VALIDATIONS --- // // Validate signatures using eth typed sign V1 require( LibValidator.checkOrdersInfo( buyOrder, sellOrder, msg.sender, filledAmount, filledPrice, block.timestamp, _allowedMatcher ), "E3G" ); // --- UPDATES --- // //updateFilledAmount filledAmounts[buyOrderHash] += filledAmount; //it is safe to add ui112 to each other to get i192 filledAmounts[sellOrderHash] += filledAmount; require(filledAmounts[buyOrderHash] <= buyOrder.amount, "E12B"); require(filledAmounts[sellOrderHash] <= sellOrder.amount, "E12S"); // Update User's balances updateOrderBalance(buyOrder, filledAmount, amountQuote, kBuy | kCorrectMatcherFeeByOrderAmount); updateOrderBalance(sellOrder, filledAmount, amountQuote, kSell | kCorrectMatcherFeeByOrderAmount); require(checkPosition(buyOrder.senderAddress), "Incorrect margin position for buyer"); require(checkPosition(sellOrder.senderAddress), "Incorrect margin position for seller"); emit NewTrade( buyOrder.senderAddress, sellOrder.senderAddress, buyOrder.baseAsset, buyOrder.quoteAsset, filledPrice, filledAmount, amountQuote ); } /** * @dev wrapper for LibValidator methods, may be deleted. */ function validateOrder(LibValidator.Order memory order) public pure returns (bool isValid) { isValid = order.isPersonalSign ? LibValidator.validatePersonal(order) : LibValidator.validateV3(order); } /** * @notice update user balances and send matcher fee * @param flags uint8, see constants for possible flags of order */ function updateOrderBalance( LibValidator.Order memory order, uint112 filledAmount, uint112 amountQuote, uint8 flags ) internal { address user = order.senderAddress; bool isBuyer = ((flags & kBuy) != 0); int192 temp; // this variable will be used for temporary variable storage (optimization purpose) { // Stack too deep bool isCorrectFee = ((flags & kCorrectMatcherFeeByOrderAmount) != 0); if(isCorrectFee) { // matcherFee: u64, filledAmount u128 => matcherFee*filledAmount fit u256 // result matcherFee fit u64 order.matcherFee = uint64(uint256(order.matcherFee)*filledAmount/order.amount); //rewrite in memory only } } if(filledAmount > 0) { if(!isBuyer) (filledAmount, amountQuote) = (amountQuote, filledAmount); (address firstAsset, address secondAsset) = isBuyer? (order.quoteAsset, order.baseAsset): (order.baseAsset, order.quoteAsset); int192 firstBalance = assetBalances[user][firstAsset]; int192 secondBalance = assetBalances[user][secondAsset]; // 'Stack too deep' correction // WAS: // bool firstInLiabilities = firstBalance<0; // bool secondInLiabilities = secondBalance<0; // NOW: // ENDFIX temp = assetBalances[user][firstAsset] - amountQuote; assetBalances[user][firstAsset] = temp; assetBalances[user][secondAsset] += filledAmount; // 'Stack too deep' correction // WAS: // if(!firstInLiabilities && (temp<0)){ // NOW: if(!(firstBalance<0) && (temp<0)){ // ENDFIX setLiability(user, firstAsset, temp); } // 'Stack too deep' correction // WAS: // if(secondInLiabilities) { // NOW: if(secondBalance<0) { // ENDFIX MarginalFunctionality.updateLiability(user, secondAsset, liabilities, filledAmount, assetBalances[user][secondAsset]); } } // User pay for fees bool feeAssetInLiabilities = assetBalances[user][order.matcherFeeAsset]<0; temp = assetBalances[user][order.matcherFeeAsset] - order.matcherFee; assetBalances[user][order.matcherFeeAsset] = temp; if(!feeAssetInLiabilities && (temp<0)) { setLiability(user, order.matcherFeeAsset, temp); } assetBalances[order.matcherAddress][order.matcherFeeAsset] += order.matcherFee; } /** * @notice users can cancel an order * @dev write an orderHash in the contract so that such an order cannot be filled (executed) */ /* Unused for now function cancelOrder(LibValidator.Order memory order) public { require(order.validateV3(), "E2"); require(msg.sender == order.senderAddress, "Not owner"); bytes32 orderHash = order.getTypeValueHash(); require(!isOrderCancelled(orderHash), "E4"); ( int192 totalFilled, //uint totalFeesPaid ) = getFilledAmounts(orderHash); if (totalFilled > 0) orderStatus[orderHash] = Status.PARTIALLY_CANCELLED; else orderStatus[orderHash] = Status.CANCELLED; emit OrderUpdate(orderHash, msg.sender, orderStatus[orderHash]); assert( orderStatus[orderHash] == Status.PARTIALLY_CANCELLED || orderStatus[orderHash] == Status.CANCELLED ); } */ /** * @dev check user marginal position (compare assets and liabilities) * @return isPositive - boolean whether liabilities are covered by collateral or not */ function checkPosition(address user) public view returns (bool) { if(liabilities[user].length == 0) return true; return calcPosition(user).state == MarginalFunctionality.PositionState.POSITIVE; } /** * @dev internal methods which collect all variables used my MarginalFunctionality to one structure * @param user user address to query * @return UsedConstants - MarginalFunctionality.UsedConstants structure */ function getConstants(address user) internal view returns (MarginalFunctionality.UsedConstants memory) { return MarginalFunctionality.UsedConstants(user, _oracleAddress, address(this), address(_orionToken), positionOverdue, priceOverdue, stakeRisk, liquidationPremium); } /** * @dev calc user marginal position (compare assets and liabilities) * @param user user address to query * @return position - MarginalFunctionality.Position structure */ function calcPosition(address user) public view returns (MarginalFunctionality.Position memory) { MarginalFunctionality.UsedConstants memory constants = getConstants(user); return MarginalFunctionality.calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); } /** * @dev method to cover some of overdue broker liabilities and get ORN in exchange same as liquidation or margin call * @param broker - broker which will be liquidated * @param redeemedAsset - asset, liability of which will be covered * @param amount - amount of covered asset */ function partiallyLiquidate(address broker, address redeemedAsset, uint112 amount) public { MarginalFunctionality.UsedConstants memory constants = getConstants(broker); MarginalFunctionality.partiallyLiquidate(collateralAssets, liabilities, assetBalances, assetRisks, constants, redeemedAsset, amount); } /** * @dev method to add liability * @param user - user which created liability * @param asset - liability asset * @param balance - current negative balance */ function setLiability(address user, address asset, int192 balance) internal { liabilities[user].push( MarginalFunctionality.Liability({ asset: asset, timestamp: uint64(block.timestamp), outstandingAmount: uint192(-balance)}) ); } /** * @dev method to update liability forcing removing any liabilities if balance > 0 * @param assetAddress - liability asset */ function forceUpdateLiability(address assetAddress) public { address user = msg.sender; MarginalFunctionality.updateLiability(user, assetAddress, liabilities, 0, assetBalances[user][assetAddress]); } /** * @dev revert on fallback function */ fallback() external { revert("E6"); } /* Error Codes E1: Insufficient Balance, flavor S - stake E2: Invalid Signature, flavor B,S - buyer, seller E3: Invalid Order Info, flavor G - general, M - wrong matcher, M2 unauthorized matcher, As - asset mismatch, AmB/AmS - amount mismatch (buyer,seller), PrB/PrS - price mismatch(buyer,seller), D - direction mismatch, E4: Order expired, flavor B,S - buyer,seller E5: Contract not active, E6: Transfer error E7: Incorrect state prior to liquidation E8: Liquidator doesn't satisfy requirements E9: Data for liquidation handling is outdated E10: Incorrect state after liquidation E11: Amount overflow E12: Incorrect filled amount, flavor G,B,S: general(overflow), buyer order overflow, seller order overflow E14: Authorization error, sfs - seizeFromStake E15: Wrong passed params */ } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./libs/MarginalFunctionality.sol"; // Base contract which contain state variable of the first version of Exchange // deployed on mainnet. Changes of the state variables should be introduced // not in that contract but down the inheritance chain, to allow safe upgrades // More info about safe upgrades here: // https://blog.openzeppelin.com/the-state-of-smart-contract-upgrades/#upgrade-patterns contract ExchangeStorage { //order -> filledAmount mapping(bytes32 => uint192) public filledAmounts; // Get user balance by address and asset address mapping(address => mapping(address => int192)) internal assetBalances; // List of assets with negative balance for each user mapping(address => MarginalFunctionality.Liability[]) public liabilities; // List of assets which can be used as collateral and risk coefficients for them address[] internal collateralAssets; mapping(address => uint8) public assetRisks; // Risk coefficient for locked ORN uint8 public stakeRisk; // Liquidation premium uint8 public liquidationPremium; // Delays after which price and position become outdated uint64 public priceOverdue; uint64 public positionOverdue; // Base orion tokens (can be locked on stake) IERC20 _orionToken; // Address of price oracle contract address _oracleAddress; // Address from which matching of orders is allowed address _allowedMatcher; } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./Exchange.sol"; import "./utils/orionpool/periphery/interfaces/IOrionPoolV2Router02Ext.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; contract ExchangeWithOrionPool is Exchange { using SafeERC20 for IERC20; address public _orionpoolRouter; mapping (address => bool) orionpoolAllowances; modifier initialized { require(_orionpoolRouter!=address(0), "_orionpoolRouter is not set"); require(address(_orionToken)!=address(0), "_orionToken is not set"); require(_oracleAddress!=address(0), "_oracleAddress is not set"); require(_allowedMatcher!=address(0), "_allowedMatcher is not set"); _; } function _safeIncreaseAllowance(address token) internal { if(token != address(0) && !orionpoolAllowances[token]) { IERC20(token).safeIncreaseAllowance(_orionpoolRouter, 2**256-1); orionpoolAllowances[token] = true; } } /** * @dev set basic Exchange params * @param orionToken - base token address * @param priceOracleAddress - adress of PriceOracle contract * @param allowedMatcher - address which has authorization to match orders * @param orionpoolRouter - OrionPool Router address for changes through orionpool */ function setBasicParams(address orionToken, address priceOracleAddress, address allowedMatcher, address orionpoolRouter) public onlyOwner { _orionToken = IERC20(orionToken); _oracleAddress = priceOracleAddress; _allowedMatcher = allowedMatcher; _orionpoolRouter = orionpoolRouter; } // Important catch-all afunction that should only accept ethereum and don't allow do something with it // We accept ETH there only from out router. // If router sends some ETH to us - it's just swap completed, and we don't need to do smth // with ETH received - amount of ETH will be handled by ........... blah blah receive() external payable { require(msg.sender == _orionpoolRouter, "NPF"); } /** * @notice (partially) settle buy order with OrionPool as counterparty * @dev order and orionpool path are submitted, it is necessary to match them: check conditions in order for compliance filledPrice and filledAmount change tokens via OrionPool check that final price after exchange not worse than specified in order change balances on the contract respectively * @param order structure of buy side orderbuyOrderHash * @param filledAmount amount of purchaseable token * @param path array of assets addresses (each consequent asset pair is change pair) */ // Just to avoid stack too deep error; struct OrderExecutionData { uint64 filledPrice; uint112 amountQuote; uint tx_value; } function fillThroughOrionPool( LibValidator.Order memory order, uint112 filledAmount, uint64 blockchainFee, address[] calldata path ) public nonReentrant initialized { // Amount of quote asset uint256 _amountQuote = uint256(filledAmount)* order.price/(10**8); OrderExecutionData memory exec_data; if(order.buySide==1){ /* NOTE BUY ORDER ************************************************************/ (int112 amountQuoteBaseUnits, int112 filledAmountBaseUnits) = ( LibUnitConverter.decimalToBaseUnit(path[0], _amountQuote), LibUnitConverter.decimalToBaseUnit(path[path.length-1], filledAmount) ); // TODO: check // require(IERC20(order.quoteAsset).balanceOf(address(this)) >= uint(amountQuoteBaseUnits), "NEGT"); LibValidator.checkOrderSingleMatch(order, msg.sender, _allowedMatcher, filledAmount, block.timestamp, path, 1); // Change fee only after order validation if(blockchainFee < order.matcherFee) order.matcherFee = blockchainFee; _safeIncreaseAllowance(order.quoteAsset); if(order.quoteAsset == address(0)) exec_data.tx_value = uint(amountQuoteBaseUnits); try IOrionPoolV2Router02Ext(_orionpoolRouter).swapTokensForExactTokensAutoRoute{value: exec_data.tx_value}( uint(filledAmountBaseUnits), uint(amountQuoteBaseUnits), path, address(this)) // order.expiration/1000 returns(uint[] memory amounts) { exec_data.amountQuote = uint112(LibUnitConverter.baseUnitToDecimal( path[0], amounts[0] )); //require(_amountQuote<2**112-1, "E12G"); //TODO uint256 _filledPrice = exec_data.amountQuote*(10**8)/filledAmount; require(_filledPrice<= order.price, "EX"); //TODO exec_data.filledPrice = uint64(_filledPrice); // since _filledPrice<buyOrder.price it fits uint64 //uint112 amountQuote = uint112(_amountQuote); } catch(bytes memory) { filledAmount = 0; exec_data.filledPrice = order.price; } // Update User's balances updateOrderBalance(order, filledAmount, exec_data.amountQuote, kBuy); require(checkPosition(order.senderAddress), "Incorrect margin position for buyer"); }else{ /* NOTE: SELL ORDER **************************************************************************/ LibValidator.checkOrderSingleMatch(order, msg.sender, _allowedMatcher, filledAmount, block.timestamp, path, 0); // Change fee only after order validation if(blockchainFee < order.matcherFee) order.matcherFee = blockchainFee; (int112 amountQuoteBaseUnits, int112 filledAmountBaseUnits) = ( LibUnitConverter.decimalToBaseUnit(path[0], filledAmount), LibUnitConverter.decimalToBaseUnit(path[path.length-1], _amountQuote) ); _safeIncreaseAllowance(order.baseAsset); if(order.baseAsset == address(0)) exec_data.tx_value = uint(amountQuoteBaseUnits); try IOrionPoolV2Router02Ext(_orionpoolRouter).swapExactTokensForTokensAutoRoute{value: exec_data.tx_value}( uint(amountQuoteBaseUnits), uint(filledAmountBaseUnits), path, address(this)) // order.expiration/1000) returns (uint[] memory amounts) { exec_data.amountQuote = uint112(LibUnitConverter.baseUnitToDecimal( path[path.length-1], amounts[path.length-1] )); //require(_amountQuote<2**112-1, "E12G"); //TODO uint256 _filledPrice = exec_data.amountQuote*(10**8)/filledAmount; require(_filledPrice>= order.price, "EX"); //TODO exec_data.filledPrice = uint64(_filledPrice); // since _filledPrice<buyOrder.price it fits uint64 //uint112 amountQuote = uint112(_amountQuote); } catch(bytes memory) { filledAmount = 0; exec_data.filledPrice = order.price; } // Update User's balances updateOrderBalance(order, filledAmount, exec_data.amountQuote, kSell); require(checkPosition(order.senderAddress), "Incorrect margin position for seller"); } { // STack too deep workaround bytes32 orderHash = LibValidator.getTypeValueHash(order); uint192 total_amount = filledAmounts[orderHash]; // require(filledAmounts[orderHash]==0, "filledAmount already has some value"); // Old way total_amount += filledAmount; //it is safe to add ui112 to each other to get i192 require(total_amount >= filledAmount, "E12B_0"); require(total_amount <= order.amount, "E12B"); filledAmounts[orderHash] = total_amount; } emit NewTrade( order.senderAddress, address(1), //TODO //sellOrder.senderAddress, order.baseAsset, order.quoteAsset, exec_data.filledPrice, filledAmount, exec_data.amountQuote ); } /* BUY LIMIT ORN/USDT path[0] = USDT path[1] = ORN is_exact_spend = false; SELL LIMIT ORN/USDT path[0] = ORN path[1] = USDT is_exact_spend = true; */ event NewSwapOrionPool ( address user, address asset_spend, address asset_receive, int112 amount_spent, int112 amount_received ); function swapThroughOrionPool( uint112 amount_spend, uint112 amount_receive, address[] calldata path, bool is_exact_spend ) public nonReentrant initialized { (int112 amount_spend_base_units, int112 amount_receive_base_units) = ( LibUnitConverter.decimalToBaseUnit(path[0], amount_spend), LibUnitConverter.decimalToBaseUnit(path[path.length-1], amount_receive) ); // Checks require(getBalance(path[0], msg.sender) >= amount_spend, "NEGS1"); _safeIncreaseAllowance(path[0]); uint256 tx_value = path[0] == address(0) ? uint(amount_spend_base_units) : 0; uint[] memory amounts = is_exact_spend ? IOrionPoolV2Router02Ext(_orionpoolRouter).swapExactTokensForTokensAutoRoute {value: tx_value} ( uint(amount_spend_base_units), uint(amount_receive_base_units), path, address(this) ) : IOrionPoolV2Router02Ext(_orionpoolRouter).swapTokensForExactTokensAutoRoute {value: tx_value} ( uint(amount_receive_base_units), uint(amount_spend_base_units), path, address(this) ); // Anyway user gave amounts[0] and received amounts[len-1] int112 amount_actually_spent = LibUnitConverter.baseUnitToDecimal(path[0], amounts[0]); int112 amount_actually_received = LibUnitConverter.baseUnitToDecimal(path[path.length-1], amounts[path.length-1]); int192 balance_in_spent = assetBalances[msg.sender][path[0]]; require(amount_actually_spent >= 0 && balance_in_spent >= amount_actually_spent, "NEGS2_1"); balance_in_spent -= amount_actually_spent; assetBalances[msg.sender][path[0]] = balance_in_spent; require(checkPosition(msg.sender), "NEGS2_2"); address receiving_token = path[path.length - 1]; int192 balance_in_received = assetBalances[msg.sender][receiving_token]; bool is_need_update_liability = (balance_in_received < 0); balance_in_received += amount_actually_received; require(amount_actually_received >= 0 /* && balance_in_received >= amount_actually_received*/ , "NEGS2_3"); assetBalances[msg.sender][receiving_token] = balance_in_received; if(is_need_update_liability) MarginalFunctionality.updateLiability( msg.sender, receiving_token, liabilities, uint112(amount_actually_received), assetBalances[msg.sender][receiving_token] ); // TODO: remove emit NewSwapOrionPool ( msg.sender, path[0], receiving_token, amount_actually_spent, amount_actually_received ); } function increaseAllowance(address token) public { IERC20(token).safeIncreaseAllowance(_orionpoolRouter, 2**256-1); orionpoolAllowances[token] = true; } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./utils/Ownable.sol"; import "./ExchangeStorage.sol"; abstract contract OrionVault is ExchangeStorage, OwnableUpgradeSafe { enum StakePhase{ NOTSTAKED, LOCKED, RELEASING, READYTORELEASE, FROZEN } struct Stake { uint64 amount; // 100m ORN in circulation fits uint64 StakePhase phase; uint64 lastActionTimestamp; } uint64 constant releasingDuration = 3600*24; mapping(address => Stake) private stakingData; /** * @dev Returns Stake with on-fly calculated StakePhase * @dev Note StakePhase may depend on time for some phases. * @param user address */ function getStake(address user) public view returns (Stake memory stake){ stake = stakingData[user]; if(stake.phase == StakePhase.RELEASING && (block.timestamp - stake.lastActionTimestamp) > releasingDuration) { stake.phase = StakePhase.READYTORELEASE; } } /** * @dev Returns stake balance * @dev Note, this balance may be already unlocked * @param user address */ function getStakeBalance(address user) public view returns (uint256) { return getStake(user).amount; } /** * @dev Returns stake phase * @param user address */ function getStakePhase(address user) public view returns (StakePhase) { return getStake(user).phase; } /** * @dev Returns locked or frozen stake balance only * @param user address */ function getLockedStakeBalance(address user) public view returns (uint256) { Stake memory stake = getStake(user); if(stake.phase == StakePhase.LOCKED || stake.phase == StakePhase.FROZEN) return stake.amount; return 0; } /** * @dev Change stake phase to frozen, blocking release * @param user address */ function postponeStakeRelease(address user) external onlyOwner{ Stake storage stake = stakingData[user]; stake.phase = StakePhase.FROZEN; } /** * @dev Change stake phase to READYTORELEASE * @param user address */ function allowStakeRelease(address user) external onlyOwner { Stake storage stake = stakingData[user]; stake.phase = StakePhase.READYTORELEASE; } /** * @dev Request stake unlock for msg.sender * @dev If stake phase is LOCKED, that changes phase to RELEASING * @dev If stake phase is READYTORELEASE, that withdraws stake to balance * @dev Note, both unlock and withdraw is impossible if user has liabilities */ function requestReleaseStake() public { address user = _msgSender(); Stake memory current = getStake(user); require(liabilities[user].length == 0, "Can not release stake: user has liabilities"); Stake storage stake = stakingData[_msgSender()]; if(current.phase == StakePhase.READYTORELEASE) { assetBalances[user][address(_orionToken)] += stake.amount; stake.amount = 0; stake.phase = StakePhase.NOTSTAKED; } else if (current.phase == StakePhase.LOCKED) { stake.phase = StakePhase.RELEASING; stake.lastActionTimestamp = uint64(block.timestamp); } else { revert("Can not release funds from this phase"); } } /** * @dev Lock some orions from exchange balance sheet * @param amount orions in 1e-8 units to stake */ function lockStake(uint64 amount) public { address user = _msgSender(); require(assetBalances[user][address(_orionToken)]>amount, "E1S"); Stake storage stake = stakingData[user]; assetBalances[user][address(_orionToken)] -= amount; stake.amount += amount; if(stake.phase != StakePhase.FROZEN) { stake.phase = StakePhase.LOCKED; //what is frozen should stay frozen } stake.lastActionTimestamp = uint64(block.timestamp); } /** * @dev send some orion from user's stake to receiver balance * @dev This function is used during liquidations, to reimburse liquidator * with orions from stake for decreasing liabilities. * @dev Note, this function is used by MarginalFunctionality library, thus * it can not be made private, but at the same time this function * can only be called by contract itself. That way msg.sender check * is critical. * @param user - user whose stake will be decreased * @param receiver - user which get orions * @param amount - amount of withdrawn tokens */ function seizeFromStake(address user, address receiver, uint64 amount) public { require(msg.sender == address(this), "E14"); Stake storage stake = stakingData[user]; require(stake.amount >= amount, "UX"); //TODO stake.amount -= amount; assetBalances[receiver][address(_orionToken)] += amount; } } pragma solidity 0.7.4; interface OrionVaultInterface { /** * @dev Returns locked or frozen stake balance only * @param user address */ function getLockedStakeBalance(address user) external view returns (uint64); /** * @dev send some orion from user's stake to receiver balance * @dev This function is used during liquidations, to reimburse liquidator * with orions from stake for decreasing liabilities. * @param user - user whose stake will be decreased * @param receiver - user which get orions * @param amount - amount of withdrawn tokens */ function seizeFromStake(address user, address receiver, uint64 amount) external; } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface PriceOracleDataTypes { struct PriceDataOut { uint64 price; uint64 timestamp; } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./PriceOracleDataTypes.sol"; interface PriceOracleInterface is PriceOracleDataTypes { function assetPrices(address) external view returns (PriceDataOut memory); function givePrices(address[] calldata assetAddresses) external view returns (PriceDataOut[] memory); } pragma solidity 0.7.4; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; library LibUnitConverter { using SafeMath for uint; /** @notice convert asset amount from8 decimals (10^8) to its base unit */ function decimalToBaseUnit(address assetAddress, uint amount) public view returns(int112 baseValue){ uint256 result; if(assetAddress == address(0)){ result = amount.mul(1 ether).div(10**8); // 18 decimals } else { ERC20 asset = ERC20(assetAddress); uint decimals = asset.decimals(); result = amount.mul(10**decimals).div(10**8); } require(result < uint256(type(int112).max), "LibUnitConverter: Too big value"); baseValue = int112(result); } /** @notice convert asset amount from its base unit to 8 decimals (10^8) */ function baseUnitToDecimal(address assetAddress, uint amount) public view returns(int112 decimalValue){ uint256 result; if(assetAddress == address(0)){ result = amount.mul(10**8).div(1 ether); } else { ERC20 asset = ERC20(assetAddress); uint decimals = asset.decimals(); result = amount.mul(10**8).div(10**decimals); } require(result < uint256(type(int112).max), "LibUnitConverter: Too big value"); decimalValue = int112(result); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; library LibValidator { using ECDSA for bytes32; string public constant DOMAIN_NAME = "Orion Exchange"; string public constant DOMAIN_VERSION = "1"; uint256 public constant CHAIN_ID = 1; bytes32 public constant DOMAIN_SALT = 0xf2d857f4a3edcb9b78b4d503bfe733db1e3f6cdc2b7971ee739626c97e86a557; bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(string name,string version,uint256 chainId,bytes32 salt)" ) ); bytes32 public constant ORDER_TYPEHASH = keccak256( abi.encodePacked( "Order(address senderAddress,address matcherAddress,address baseAsset,address quoteAsset,address matcherFeeAsset,uint64 amount,uint64 price,uint64 matcherFee,uint64 nonce,uint64 expiration,uint8 buySide)" ) ); bytes32 public constant DOMAIN_SEPARATOR = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(DOMAIN_NAME)), keccak256(bytes(DOMAIN_VERSION)), CHAIN_ID, DOMAIN_SALT ) ); struct Order { address senderAddress; address matcherAddress; address baseAsset; address quoteAsset; address matcherFeeAsset; uint64 amount; uint64 price; uint64 matcherFee; uint64 nonce; uint64 expiration; uint8 buySide; // buy or sell bool isPersonalSign; bytes signature; } /** * @dev validate order signature */ function validateV3(Order memory order) public pure returns (bool) { bytes32 domainSeparator = DOMAIN_SEPARATOR; bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, getTypeValueHash(order) ) ); return digest.recover(order.signature) == order.senderAddress; } /** * @return hash order */ function getTypeValueHash(Order memory _order) internal pure returns (bytes32) { bytes32 orderTypeHash = ORDER_TYPEHASH; return keccak256( abi.encode( orderTypeHash, _order.senderAddress, _order.matcherAddress, _order.baseAsset, _order.quoteAsset, _order.matcherFeeAsset, _order.amount, _order.price, _order.matcherFee, _order.nonce, _order.expiration, _order.buySide ) ); } /** * @dev basic checks of matching orders against each other */ function checkOrdersInfo( Order memory buyOrder, Order memory sellOrder, address sender, uint256 filledAmount, uint256 filledPrice, uint256 currentTime, address allowedMatcher ) public pure returns (bool success) { buyOrder.isPersonalSign ? require(validatePersonal(buyOrder), "E2BP") : require(validateV3(buyOrder), "E2B"); sellOrder.isPersonalSign ? require(validatePersonal(sellOrder), "E2SP") : require(validateV3(sellOrder), "E2S"); // Same matcher address require( buyOrder.matcherAddress == sender && sellOrder.matcherAddress == sender, "E3M" ); if(allowedMatcher != address(0)) { require(buyOrder.matcherAddress == allowedMatcher, "E3M2"); } // Check matching assets require( buyOrder.baseAsset == sellOrder.baseAsset && buyOrder.quoteAsset == sellOrder.quoteAsset, "E3As" ); // Check order amounts require(filledAmount <= buyOrder.amount, "E3AmB"); require(filledAmount <= sellOrder.amount, "E3AmS"); // Check Price values require(filledPrice <= buyOrder.price, "E3"); require(filledPrice >= sellOrder.price, "E3"); // Check Expiration Time. Convert to seconds first require(buyOrder.expiration/1000 >= currentTime, "E4B"); require(sellOrder.expiration/1000 >= currentTime, "E4S"); require( buyOrder.buySide==1 && sellOrder.buySide==0, "E3D"); success = true; } function getEthSignedOrderHash(Order memory _order) public pure returns (bytes32) { return keccak256( abi.encodePacked( "order", _order.senderAddress, _order.matcherAddress, _order.baseAsset, _order.quoteAsset, _order.matcherFeeAsset, _order.amount, _order.price, _order.matcherFee, _order.nonce, _order.expiration, _order.buySide ) ).toEthSignedMessageHash(); } function validatePersonal(Order memory order) public pure returns (bool) { bytes32 digest = getEthSignedOrderHash(order); return digest.recover(order.signature) == order.senderAddress; } function checkOrderSingleMatch( Order memory buyOrder, address sender, address allowedMatcher, uint112 filledAmount, uint256 currentTime, address[] memory path, uint8 isBuySide ) public pure returns (bool success) { buyOrder.isPersonalSign ? require(validatePersonal(buyOrder), "E2BP") : require(validateV3(buyOrder), "E2B"); require(buyOrder.matcherAddress == sender && buyOrder.matcherAddress == allowedMatcher, "E3M2"); if(buyOrder.buySide==1){ require( buyOrder.baseAsset == path[path.length-1] && buyOrder.quoteAsset == path[0], "E3As" ); }else{ require( buyOrder.quoteAsset == path[path.length-1] && buyOrder.baseAsset == path[0], "E3As" ); } require(filledAmount <= buyOrder.amount, "E3AmB"); require(buyOrder.expiration/1000 >= currentTime, "E4B"); require( buyOrder.buySide==isBuySide, "E3D"); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../PriceOracleInterface.sol"; import "../OrionVaultInterface.sol"; library MarginalFunctionality { // We have the following approach: when liability is created we store // timestamp and size of liability. If the subsequent trade will deepen // this liability or won't fully cover it timestamp will not change. // However once outstandingAmount is covered we check wether balance on // that asset is positive or not. If not, liability still in the place but // time counter is dropped and timestamp set to `now`. struct Liability { address asset; uint64 timestamp; uint192 outstandingAmount; } enum PositionState { POSITIVE, NEGATIVE, // weighted position below 0 OVERDUE, // liability is not returned for too long NOPRICE, // some assets has no price or expired INCORRECT // some of the basic requirements are not met: too many liabilities, no locked stake, etc } struct Position { PositionState state; int256 weightedPosition; // sum of weighted collateral minus liabilities int256 totalPosition; // sum of unweighted (total) collateral minus liabilities int256 totalLiabilities; // total liabilities value } // Constants from Exchange contract used for calculations struct UsedConstants { address user; address _oracleAddress; address _orionVaultContractAddress; address _orionTokenAddress; uint64 positionOverdue; uint64 priceOverdue; uint8 stakeRisk; uint8 liquidationPremium; } /** * @dev method to multiply numbers with uint8 based percent numbers */ function uint8Percent(int192 _a, uint8 b) internal pure returns (int192 c) { int a = int256(_a); int d = 255; c = int192((a>65536) ? (a/d)*b : a*b/d ); } /** * @dev method to calc weighted and absolute collateral value * @notice it only count for assets in collateralAssets list, all other assets will add 0 to position. * @return outdated wether any price is outdated * @return weightedPosition in ORN * @return totalPosition in ORN */ function calcAssets(address[] storage collateralAssets, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants) internal view returns (bool outdated, int192 weightedPosition, int192 totalPosition) { uint256 collateralAssetsLength = collateralAssets.length; for(uint256 i = 0; i < collateralAssetsLength; i++) { address asset = collateralAssets[i]; if(assetBalances[constants.user][asset]<0) continue; // will be calculated in calcLiabilities (uint64 price, uint64 timestamp) = (1e8, 0xfffffff000000000); if(asset != constants._orionTokenAddress) { PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(asset);//TODO givePrices (price, timestamp) = (assetPriceData.price, assetPriceData.timestamp); } // balance: i192, price u64 => balance*price fits i256 // since generally balance <= N*maxInt112 (where N is number operations with it), // assetValue <= N*maxInt112*maxUInt64/1e8. // That is if N<= 2**17 *1e8 = 1.3e13 we can neglect overflows here int192 assetValue = int192(int256(assetBalances[constants.user][asset])*price/1e8); // Overflows logic holds here as well, except that N is the number of // operations for all assets if(assetValue>0) { weightedPosition += uint8Percent(assetValue, assetRisks[asset]); totalPosition += assetValue; // if assetValue == 0 ignore outdated price outdated = outdated || ((timestamp + constants.priceOverdue) < block.timestamp); } } return (outdated, weightedPosition, totalPosition); } /** * @dev method to calc liabilities * @return outdated wether any price is outdated * @return overdue wether any liability is overdue * @return weightedPosition weightedLiability == totalLiability in ORN * @return totalPosition totalLiability in ORN */ function calcLiabilities(mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, UsedConstants memory constants ) internal view returns (bool outdated, bool overdue, int192 weightedPosition, int192 totalPosition) { uint256 liabilitiesLength = liabilities[constants.user].length; for(uint256 i = 0; i < liabilitiesLength; i++) { Liability storage liability = liabilities[constants.user][i]; PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(liability.asset);//TODO givePrices (uint64 price, uint64 timestamp) = (assetPriceData.price, assetPriceData.timestamp); // balance: i192, price u64 => balance*price fits i256 // since generally balance <= N*maxInt112 (where N is number operations with it), // assetValue <= N*maxInt112*maxUInt64/1e8. // That is if N<= 2**17 *1e8 = 1.3e13 we can neglect overflows here int192 liabilityValue = int192( int256(assetBalances[constants.user][liability.asset]) *price/1e8 ); weightedPosition += liabilityValue; //already negative since balance is negative totalPosition += liabilityValue; overdue = overdue || ((liability.timestamp + constants.positionOverdue) < block.timestamp); outdated = outdated || ((timestamp + constants.priceOverdue) < block.timestamp); } return (outdated, overdue, weightedPosition, totalPosition); } /** * @dev method to calc Position * @return result position structure */ function calcPosition( address[] storage collateralAssets, mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants ) public view returns (Position memory result) { (bool outdatedPrice, int192 weightedPosition, int192 totalPosition) = calcAssets(collateralAssets, assetBalances, assetRisks, constants); (bool _outdatedPrice, bool overdue, int192 _weightedPosition, int192 _totalPosition) = calcLiabilities(liabilities, assetBalances, constants ); uint64 lockedAmount = OrionVaultInterface(constants._orionVaultContractAddress) .getLockedStakeBalance(constants.user); int192 weightedStake = uint8Percent(int192(lockedAmount), constants.stakeRisk); weightedPosition += weightedStake; totalPosition += lockedAmount; weightedPosition += _weightedPosition; totalPosition += _totalPosition; outdatedPrice = outdatedPrice || _outdatedPrice; bool incorrect = (liabilities[constants.user].length>0) && (lockedAmount==0); if(_totalPosition<0) { result.totalLiabilities = _totalPosition; } if(weightedPosition<0) { result.state = PositionState.NEGATIVE; } if(outdatedPrice) { result.state = PositionState.NOPRICE; } if(overdue) { result.state = PositionState.OVERDUE; } if(incorrect) { result.state = PositionState.INCORRECT; } result.weightedPosition = weightedPosition; result.totalPosition = totalPosition; } /** * @dev method removes liability */ function removeLiability(address user, address asset, mapping(address => Liability[]) storage liabilities) public { uint256 length = liabilities[user].length; for (uint256 i = 0; i < length; i++) { if (liabilities[user][i].asset == asset) { if (length>1) { liabilities[user][i] = liabilities[user][length - 1]; } liabilities[user].pop(); break; } } } /** * @dev method update liability * @notice implement logic for outstandingAmount (see Liability description) */ function updateLiability(address user, address asset, mapping(address => Liability[]) storage liabilities, uint112 depositAmount, int192 currentBalance) public { if(currentBalance>=0) { removeLiability(user,asset,liabilities); } else { uint256 i; uint256 liabilitiesLength=liabilities[user].length; for(; i<liabilitiesLength-1; i++) { if(liabilities[user][i].asset == asset) break; } Liability storage liability = liabilities[user][i]; if(depositAmount>=liability.outstandingAmount) { liability.outstandingAmount = uint192(-currentBalance); liability.timestamp = uint64(block.timestamp); } else { liability.outstandingAmount -= depositAmount; } } } /** * @dev partially liquidate, that is cover some asset liability to get ORN from meisbehaviour broker */ function partiallyLiquidate(address[] storage collateralAssets, mapping(address => Liability[]) storage liabilities, mapping(address => mapping(address => int192)) storage assetBalances, mapping(address => uint8) storage assetRisks, UsedConstants memory constants, address redeemedAsset, uint112 amount) public { //Note: constants.user - is broker who will be liquidated Position memory initialPosition = calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); require(initialPosition.state == PositionState.NEGATIVE || initialPosition.state == PositionState.OVERDUE , "E7"); address liquidator = msg.sender; require(assetBalances[liquidator][redeemedAsset]>=amount,"E8"); require(assetBalances[constants.user][redeemedAsset]<0,"E15"); assetBalances[liquidator][redeemedAsset] -= amount; assetBalances[constants.user][redeemedAsset] += amount; if(assetBalances[constants.user][redeemedAsset] >= 0) removeLiability(constants.user, redeemedAsset, liabilities); PriceOracleInterface.PriceDataOut memory assetPriceData = PriceOracleInterface(constants._oracleAddress).assetPrices(redeemedAsset); (uint64 price, uint64 timestamp) = (assetPriceData.price, assetPriceData.timestamp); require((timestamp + constants.priceOverdue) > block.timestamp, "E9"); //Price is outdated reimburseLiquidator(amount, price, liquidator, assetBalances, constants); Position memory finalPosition = calcPosition(collateralAssets, liabilities, assetBalances, assetRisks, constants); require( int(finalPosition.state)<3 && //POSITIVE,NEGATIVE or OVERDUE (finalPosition.weightedPosition>initialPosition.weightedPosition), "E10");//Incorrect state position after liquidation if(finalPosition.state == PositionState.POSITIVE) require (finalPosition.weightedPosition<10e8,"Can not liquidate to very positive state"); } /** * @dev reimburse liquidator with ORN: first from stake, than from broker balance */ function reimburseLiquidator( uint112 amount, uint64 price, address liquidator, mapping(address => mapping(address => int192)) storage assetBalances, UsedConstants memory constants) internal { int192 _orionAmount = int192(int256(amount)*price/1e8); _orionAmount += uint8Percent(_orionAmount,constants.liquidationPremium); //Liquidation premium require(_orionAmount == int64(_orionAmount), "E11"); int64 orionAmount = int64(_orionAmount); // There is only 100m Orion tokens, fits i64 int64 onBalanceOrion = int64(assetBalances[constants.user][constants._orionTokenAddress]); (int64 fromBalance, int64 fromStake) = (onBalanceOrion>orionAmount)? (orionAmount, 0) : (onBalanceOrion>0)? (onBalanceOrion, orionAmount-onBalanceOrion) : (0, orionAmount); if(fromBalance>0) { assetBalances[constants.user][constants._orionTokenAddress] -= int192(fromBalance); assetBalances[liquidator][constants._orionTokenAddress] += int192(fromBalance); } if(fromStake>0) { OrionVaultInterface(constants._orionVaultContractAddress).seizeFromStake(constants.user, liquidator, uint64(fromStake)); } } } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; import "./Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** Copied from @openzeppelin/contracts-ethereum-package to update pragma statements */ pragma solidity ^0.7.0; import "./Context.sol"; import "./Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.4; contract ReentrancyGuard { bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } modifier nonReentrant() { // Ensure mutex is unlocked require(!getStorageBool(REENTRANCY_MUTEX_POSITION), ERROR_REENTRANT); // Lock mutex before function call setStorageBool(REENTRANCY_MUTEX_POSITION,true); // Perform function call _; // Unlock mutex after function call setStorageBool(REENTRANCY_MUTEX_POSITION, false); } } pragma solidity >=0.6.2; interface IOrionPoolV2Router02Ext { function swapExactTokensForTokensAutoRoute( uint amountIn, uint amountOutMin, address[] calldata path, address to ) external payable returns (uint[] memory amounts); function swapTokensForExactTokensAutoRoute( uint amountOut, uint amountInMax, address[] calldata path, address to ) external payable returns (uint[] memory amounts); } // 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 ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } 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 SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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: 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 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; } }
set risk coefficients for collateral assets assets - list of assets risks - list of risks as uint8 (0=0, 255=1)/
function updateAssetRisks(address[] calldata assets, uint8[] calldata risks) public onlyOwner { for(uint256 i; i< assets.length; i++) assetRisks[assets[i]] = risks[i]; }
13,685,840
./partial_match/1/0xf5fEdF9A53191d86880b73d659896158aA394b07/sources/Sensoji.sol
Token Made By Liquidity Generator Contract
interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; }
9,145,255
// 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 "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // contracts/Anonymice.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./ICheeth.sol"; import "./AnonymiceLibrary.sol"; contract Anonymice is ERC721Enumerable { /* ___ _ / _ \ (_) / /_\ \_ __ ___ _ __ _ _ _ __ ___ _ ___ ___ | _ | '_ \ / _ \| '_ \| | | | '_ ` _ \| |/ __/ _ \ | | | | | | | (_) | | | | |_| | | | | | | | (_| __/ \_| |_/_| |_|\___/|_| |_|\__, |_| |_| |_|_|\___\___| __/ | |___/ */ using AnonymiceLibrary for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address cheethAddress; address _owner; constructor() ERC721("Anonymice", "MICE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [50, 150, 200, 300, 400, 500, 600, 900, 1200, 5700]; //whiskers TIERS[1] = [200, 800, 1000, 3000, 5000]; //Neck TIERS[2] = [300, 800, 900, 1000, 7000]; //Earrings TIERS[3] = [50, 200, 300, 300, 9150]; //Eyes TIERS[4] = [50, 100, 400, 450, 500, 700, 1800, 2000, 2000, 2000]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Nose TIERS[6] = [2000, 2000, 2000, 2000, 2000]; //Character TIERS[7] = [20, 70, 721, 1000, 1155, 1200, 1300, 1434, 1541, 1559]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cheeth cost of minting. */ function currentCheethCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 0; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!AnonymiceLibrary.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintMouse() public { if (totalSupply() < MINTS_PER_TIER) return mintInternal(); //Burn this much cheeth ICheeth(cheethAddress).burnFrom(msg.sender, currentCheethCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i + 1); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = AnonymiceLibrary.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( AnonymiceLibrary.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( AnonymiceLibrary.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", AnonymiceLibrary.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> ', svgString, "<style>rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = AnonymiceLibrary.parseInt( AnonymiceLibrary.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", AnonymiceLibrary.encode( bytes( string( abi.encodePacked( '{"name": "Anonymice #', AnonymiceLibrary.toString(_tokenId), '", "description": "Anonymice is a collection of 10,000 unique mice. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API. Just the Ethereum blockchain.", "image": "data:image/svg+xml;base64,', AnonymiceLibrary.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", AnonymiceLibrary.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the cheeth ERC20 address * @param _cheethAddress The cheeth address */ function setCheethAddress(address _cheethAddress) public onlyOwner { cheethAddress = _cheethAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library AnonymiceLibrary { 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; } /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function parseInt(string memory _a) internal pure returns (uint8 _parsedInt) { bytes memory bresult = bytes(_a); uint8 mint = 0; for (uint8 i = 0; i < bresult.length; i++) { if ( (uint8(uint8(bresult[i])) >= 48) && (uint8(uint8(bresult[i])) <= 57) ) { mint *= 10; mint += uint8(bresult[i]) - 48; } } return mint; } function substring( string memory str, uint256 startIndex, uint256 endIndex ) internal pure returns (string memory) { bytes memory strBytes = bytes(str); bytes memory result = new bytes(endIndex - startIndex); for (uint256 i = startIndex; i < endIndex; i++) { result[i - startIndex] = strBytes[i]; } return string(result); } 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; } } // contracts/ICheeth.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ICheeth is IERC20 { function burnFrom(address account, uint256 amount) external; }
Mint internal, this is to avoid code duplication./
function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!AnonymiceLibrary.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); }
5,731,672
pragma solidity 0.4.26; import "./ControllerGovernanceEngine.sol"; import "./IControllerDividends.sol"; contract ControllerDividends is ControllerGovernanceEngine, IControllerDividends, KnownInterfaces { //////////////////////// // Public Methods //////////////////////// function ordinaryPayoutResolution( bytes32 resolutionId, IERC223Token /*paymentToken*/, uint256 /*amount*/, uint256 /*recycleAfter*/, string resolutionDocumentUrl ) public { payoutResolutionPrivate(resolutionId, Gov.Action.OrdinaryPayout, resolutionDocumentUrl); } function extraOrdinaryPayoutResolution( bytes32 resolutionId, IERC223Token /*paymentToken*/, uint256 /*amount*/, uint256 /*recycleAfter*/, string resolutionDocumentUrl ) public { payoutResolutionPrivate(resolutionId, Gov.Action.ExtraordinaryPayout, resolutionDocumentUrl); } //////////////////////// // Internal Methods //////////////////////// function receiveDividend(address wallet, uint256 amount, bytes memory data) internal returns (bool) { // check if data contains one of known selectors bytes4 sig; assembly { // skip length prefix of bytes sig := mload(add(data, 32)) } if (sig != this.ordinaryPayoutResolution.selector && sig != this.extraOrdinaryPayoutResolution.selector) { // we cannot process this payout return false; } // wallet must be company require(wallet == _g.COMPANY_LEGAL_REPRESENTATIVE, "NF_DIVIDEND_ONLY_COMPANY"); // take resolution, token and amount from data IERC223Token paymentToken; bytes32 resolutionId; uint256 promisedAmount; uint256 recycleAfter; assembly { // add 4 to all pointers to skip selector // skip length prefix of bytes + selector = 36 resolutionId := mload(add(data, 36)) // skip 32 + 4 + 32 = 68 // load memory area that is unpacked address paymentToken := mload(add(data, 68)) promisedAmount := mload(add(data, 100)) recycleAfter := mload(add(data, 132)) } // msg.sender must match require(paymentToken == msg.sender && amount == promisedAmount, "NF_DIVIDEND_PAYMENT_MISMATCH"); // data must contain original call data of resolution so promise matches completePayout(resolutionId, paymentToken, amount, recycleAfter, keccak256(data)); return true; } //////////////////////// // Private Methods //////////////////////// function completePayout(bytes32 resolutionId, IERC223Token paymentToken, uint256 amount, uint256 recycleAfter, bytes32 promise) private withAtomicContinuedExecution(resolutionId, promise, 0) { // fee disbursal expect token address and recycle after packed bytes memory serializedAddress = abi.encodePacked(address(_t._token), recycleAfter); IFeeDisbursal disbursal = IFeeDisbursal(_g.UNIVERSE.feeDisbursal()); if (amount > 0) { // disburse via ERC223, where we encode token used to provide pro-rata in `data` parameter assert(paymentToken.transfer(disbursal, amount, serializedAddress)); } } function payoutResolutionPrivate( bytes32 resolutionId, Gov.Action action, // IERC223Token /*paymentToken*/, string resolutionDocumentUrl ) private onlyOperational withNonAtomicExecution(resolutionId, payoutValidator) withGovernance( resolutionId, action, resolutionDocumentUrl ) {} function payoutValidator(Gov.ResolutionExecution storage /*e*/) private constant returns (string memory code) { if (_t._token == address(0)) { return "NF_NO_PRORATA_TOKEN"; } // unpack calldata to extract address payload IERC223Token paymentToken; uint256 amount; assembly { // skip 4 bytes selector and 32 bytes resolution id // _rId := calldataload(4) paymentToken := calldataload(36) amount := calldataload(68) } require(amount > 0); if (!_g.UNIVERSE.isInterfaceCollectionInstance(KNOWN_INTERFACE_PAYMENT_TOKEN, paymentToken)) { return "NF_NOT_PAYMENT_TOKEN"; } } }
Private Methods fee disbursal expect token address and recycle after packed disburse via ERC223, where we encode token used to provide pro-rata in `data` parameter
function completePayout(bytes32 resolutionId, IERC223Token paymentToken, uint256 amount, uint256 recycleAfter, bytes32 promise) private withAtomicContinuedExecution(resolutionId, promise, 0) { bytes memory serializedAddress = abi.encodePacked(address(_t._token), recycleAfter); IFeeDisbursal disbursal = IFeeDisbursal(_g.UNIVERSE.feeDisbursal()); if (amount > 0) { assert(paymentToken.transfer(disbursal, amount, serializedAddress)); } }
6,460,324
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || 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&#39;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; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ 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); function mint(address from, address to, uint tokens) public; event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract RADION is ERC20Interface,Ownable { using SafeMath for uint256; string public name; string public symbol; uint256 public decimals; uint256 public _totalSupply; mapping(address => uint256) tokenBalances; address musicContract; address advertisementContract; address sale; address wallet; // Owner of account approves the transfer of an amount to another account mapping (address => mapping (address => uint256)) allowed; // whitelisted addresses are those that have registered on the website mapping(address=>bool) whiteListedAddresses; /** * @dev Contructor that gives msg.sender all of existing tokens. */ constructor(address _wallet) public { owner = msg.sender; wallet = _wallet; name = "RADION"; symbol = "RADIO"; decimals = 18; _totalSupply = 55000000 * 10 ** uint(decimals); tokenBalances[wallet] = _totalSupply; //Since we divided the token into 10^18 parts } // Get the token balance for account `tokenOwner` function balanceOf(address tokenOwner) public constant returns (uint balance) { return tokenBalances[tokenOwner]; } // Transfer the balance from owner&#39;s account to another account function transfer(address to, uint tokens) public returns (bool success) { require(to != address(0)); require(tokens <= tokenBalances[msg.sender]); tokenBalances[msg.sender] = tokenBalances[msg.sender].sub(tokens); tokenBalances[to] = tokenBalances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= tokenBalances[_from]); require(_value <= allowed[_from][msg.sender]); tokenBalances[_from] = tokenBalances[_from].sub(_value); tokenBalances[_to] = tokenBalances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - tokenBalances[address(0)]; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } //only to be used by the ICO function mint(address sender, address receiver, uint256 tokenAmount) public { require(msg.sender == musicContract || msg.sender == advertisementContract); require(tokenBalances[sender] >= tokenAmount); // checks if it has enough to sell tokenBalances[receiver] = tokenBalances[receiver].add(tokenAmount); // adds the amount to buyer&#39;s balance tokenBalances[sender] = tokenBalances[sender].sub(tokenAmount); // subtracts amount from seller&#39;s balance emit Transfer(sender, receiver, tokenAmount); } function setAddresses(address music, address advertisement,address _sale) public onlyOwner { musicContract = music; advertisementContract = advertisement; sale = _sale; } function () public payable { revert(); } function buy(address beneficiary, uint ethAmountSent, uint rate) public onlyOwner { require(beneficiary != 0x0 && whiteListedAddresses[beneficiary] == true); require(ethAmountSent>0); uint weiAmount = ethAmountSent; uint tokens = weiAmount.mul(rate); require(tokenBalances[wallet] >= tokens); // checks if it has enough to sell tokenBalances[beneficiary] = tokenBalances[beneficiary].add(tokens); // adds the amount to buyer&#39;s balance tokenBalances[wallet] = tokenBalances[wallet].sub(tokens); // subtracts amount from seller&#39;s balance emit Transfer(wallet, beneficiary, tokens); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } function addAddressToWhiteList(address whitelistaddress) public onlyOwner { whiteListedAddresses[whitelistaddress] = true; } function checkIfAddressIsWhitelisted(address whitelistaddress) public onlyOwner constant returns (bool) { if (whiteListedAddresses[whitelistaddress] == true) return true; return false; } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _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 <= tokenBalances[_from]); require(_value <= allowed[_from][msg.sender]); tokenBalances[_from] = tokenBalances[_from].sub(_value); tokenBalances[_to] = tokenBalances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
10,542,960
./partial_match/7700/0xdc0aa5ae2867F5FD41Ba6FDfea072998291Ee742/sources/src/CNote.sol
User redeems cTokens in exchange for the underlying asset Assumes interest has already been accrued up to the current block redeemer The address of the account which is redeeming the tokens redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)/ If redeemTokensIn > 0: / Verify market's block number equals current block number / Fail gracefully if protocol has insufficient cash /
function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn ) internal override { require( redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero" ); uint256 redeemTokens; uint256 redeemAmount; if (redeemTokensIn > 0) { redeemTokens = redeemTokensIn; redeemAmount = mul_ScalarTruncate(exchangeRate, redeemTokensIn); redeemTokens = div_(redeemAmountIn, exchangeRate); redeemAmount = redeemAmountIn; address(this), redeemer, redeemTokens ); if (allowed != 0) { revert RedeemComptrollerRejection(allowed); } if (accrualBlockNumber != getBlockNumber()) { revert RedeemFreshnessCheck(); } if (getCashPrior() < redeemAmount) { revert RedeemTransferOutNotPossible(); } accountTokens[redeemer] = accountTokens[redeemer] - redeemTokens; emit Redeem(redeemer, redeemAmount, redeemTokens); address(this), redeemer, redeemAmount, redeemTokens ); }
3,505,541
./full_match/5/0x082A7daac615Fbbfd0CF39FB3e366255723C7fd5/sources/contracts/INFI/PowerfulERC20.sol
IERC1363 Interface Interface for a Payable Token contract as defined in/
interface IERC1363 is IERC20, IERC165 { function transferAndCall(address recipient, uint256 amount) external returns (bool); function transferAndCall( address recipient, uint256 amount, bytes calldata data ) external returns (bool); function transferFromAndCall( address sender, address recipient, uint256 amount ) external returns (bool); function transferFromAndCall( address sender, address recipient, uint256 amount, bytes calldata data ) external returns (bool); function approveAndCall(address spender, uint256 amount) external returns (bool); function approveAndCall( address spender, uint256 amount, bytes calldata data ) external returns (bool); } }
1,867,516
./full_match/4/0x68bC9Fd0A002617c17EA6183372C6CdBfCE3Fa7a/sources/RoninPresale.sol
Delete purchaser from whitelist
function deleteFromWhitelist(address _purchaser) public onlyOwner { whitelist[_purchaser] = false; }
12,400,750
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { ERC721 } from "./ERC721/ERC721.sol"; import { ERC721M } from "./ERC721/ERC721M.sol"; import { ERC721Tradable } from "./ERC721/extensions/ERC721Tradable.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; contract Mingoes is ERC721M, ERC721Tradable, Ownable { uint256 public constant PRICE = 0.04 ether; uint256 public constant MAX_SUPPLY = 10000; uint256 public constant MAX_RESERVE = 300; uint256 public constant MAX_PUBLIC = 9700; // MAX_SUPPLY - MAX_RESERVE uint256 public constant MAX_FREE = 200; uint256 public constant MAX_TX = 20; uint256 public reservesMinted; string public baseURI; bool public isSaleActive; mapping (address => bool) public hasClaimed; /* -------------------------------------------------------------------------- */ /* CONSTRUCTOR */ /* -------------------------------------------------------------------------- */ constructor( address _openSeaProxyRegistry, address _looksRareTransferManager, string memory _baseURI ) payable ERC721M("Mingoes", "MINGOES") ERC721Tradable(_openSeaProxyRegistry, _looksRareTransferManager) { baseURI = _baseURI; } /* -------------------------------------------------------------------------- */ /* USER */ /* -------------------------------------------------------------------------- */ /// @notice Mints an amount of tokens and transfers them to the caller during the public sale. /// @param amount The amount of tokens to mint. function publicMint(uint256 amount) external payable { require(isSaleActive, "Sale is not active"); require(msg.sender == tx.origin, "No contracts allowed"); uint256 _totalSupply = totalSupply(); if (_totalSupply < MAX_FREE) { require(!hasClaimed[msg.sender], "Already claimed"); hasClaimed[msg.sender] = true; _mint(msg.sender, 1); return; } require(msg.value == PRICE * amount, "Wrong ether amount"); require(amount <= MAX_TX, "Amount exceeds tx limit"); require(_totalSupply + amount <= MAX_PUBLIC, "Max public supply reached"); _mint(msg.sender, amount); } /* -------------------------------------------------------------------------- */ /* OWNER */ /* -------------------------------------------------------------------------- */ /// @notice Enables or disables minting through {publicMint}. /// @dev Requirements: /// - Caller must be the owner. function setIsSaleActive(bool _isSaleActive) external onlyOwner { isSaleActive = _isSaleActive; } /// @notice Mints tokens to multiple addresses. /// @dev Requirements: /// - Caller must be the owner. /// @param recipients The addresses to mint the tokens to. /// @param amounts The amounts of tokens to mint. function reserveMint(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner { unchecked { uint256 sum; uint256 length = recipients.length; for (uint256 i; i < length; i++) { address to = recipients[i]; require(to != address(0), "Invalid recipient"); uint256 amount = amounts[i]; _mint(to, amount); sum += amount; } uint256 totalReserves = reservesMinted + sum; require(totalSupply() <= MAX_SUPPLY, "Max supply reached"); require(totalReserves <= MAX_RESERVE, "Amount exceeds reserve limit"); reservesMinted = totalReserves; } } /// @notice Sets the base Uniform Resource Identifier (URI) for token metadata. /// @dev Requirements: /// - Caller must be the owner. /// @param _baseURI The base URI. function setBaseURI(string calldata _baseURI) external onlyOwner { baseURI = _baseURI; } /// @notice Withdraws all contract balance to the caller. /// @dev Requirements: /// - Caller must be the owner. function withdrawETH() external onlyOwner { _transferETH(msg.sender, address(this).balance); } /// @dev Requirements: /// - Caller must be the owner. /// @inheritdoc ERC721Tradable function setMarketplaceApprovalForAll(bool approved) public override onlyOwner { marketPlaceApprovalForAll = approved; } /* -------------------------------------------------------------------------- */ /* SOLIDITY OVERRIDES */ /* -------------------------------------------------------------------------- */ /// @inheritdoc ERC721 function tokenURI(uint256 id) public view override returns (string memory) { require(_exists(id), "NONEXISTENT_TOKEN"); string memory _baseURI = baseURI; return bytes(_baseURI).length == 0 ? "" : string(abi.encodePacked(_baseURI, toString(id))); } /// @inheritdoc ERC721Tradable function isApprovedForAll(address owner, address operator) public view override(ERC721, ERC721Tradable) returns (bool) { return ERC721Tradable.isApprovedForAll(owner, operator); } /* -------------------------------------------------------------------------- */ /* UTILS */ /* -------------------------------------------------------------------------- */ function _transferETH(address to, uint256 value) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = to.call{ value: value }(""); require(success, "ETH transfer failed"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { ERC721TokenReceiver } from "./ERC721TokenReceiver.sol"; abstract contract ERC721 { /* -------------------------------------------------------------------------- */ /* EVENTS */ /* -------------------------------------------------------------------------- */ /// @dev Emitted when `id` token is transferred from `from` to `to`. event Transfer(address indexed from, address indexed to, uint256 indexed id); /// @dev Emitted when `owner` enables `approved` to manage the `id` token. event Approval(address indexed owner, address indexed spender, uint256 indexed id); /// @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); /* -------------------------------------------------------------------------- */ /* METADATA STORAGE */ /* -------------------------------------------------------------------------- */ /// @dev The collection name. string private _name; /// @dev The collection symbol. string private _symbol; /* -------------------------------------------------------------------------- */ /* ERC721 STORAGE */ /* -------------------------------------------------------------------------- */ /// @dev ID => spender mapping(uint256 => address) internal _tokenApprovals; /// @dev owner => operator => approved mapping(address => mapping(address => bool)) internal _operatorApprovals; /* -------------------------------------------------------------------------- */ /* CONSTRUCTOR */ /* -------------------------------------------------------------------------- */ /// @param name_ The collection name. /// @param symbol_ The collection symbol. constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /* -------------------------------------------------------------------------- */ /* ERC165 LOGIC */ /* -------------------------------------------------------------------------- */ /// @notice Returns true if this contract implements an interface from its ID. /// @dev See the corresponding /// [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) /// to learn more about how these IDs are created. /// @return The implementation status. function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f || // ERC165 Interface ID for ERC721Metadata interfaceId == 0x780e9d63; // ERC165 Interface ID for ERC721Enumerable } /* -------------------------------------------------------------------------- */ /* METADATA LOGIC */ /* -------------------------------------------------------------------------- */ /// @notice Returns the collection name. /// @return The collection name. function name() public view virtual returns (string memory) { return _name; } /// @notice Returns the collection symbol. /// @return The collection symbol. function symbol() public view virtual returns (string memory) { return _symbol; } /// @notice Returns the Uniform Resource Identifier (URI) for `id` token. /// @param id The token ID. /// @return The URI. function tokenURI(uint256 id) public view virtual returns (string memory); /* -------------------------------------------------------------------------- */ /* ENUMERABLE LOGIC */ /* -------------------------------------------------------------------------- */ /// @notice Returns the total amount of tokens stored by the contract. /// @return The token supply. function totalSupply() public view virtual returns (uint256); /// @notice Returns a token ID owned by `owner` at a given `index` of its token list. /// @dev Use along with {balanceOf} to enumerate all of `owner`'s tokens. /// @param owner The address to query. /// @param index The index to query. /// @return The token ID. function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256); /// @notice Returns a token ID at a given `index` of all the tokens stored by the contract. /// @dev Use along with {totalSupply} to enumerate all tokens. /// @param index The index to query. /// @return The token ID. function tokenByIndex(uint256 index) public view virtual returns (uint256); /* -------------------------------------------------------------------------- */ /* ERC721 LOGIC */ /* -------------------------------------------------------------------------- */ /// @notice Returns the account approved for a token ID. /// @dev Requirements: /// - `id` must exist. /// @param id Token ID to query. /// @return The account approved for `id` token. function getApproved(uint256 id) public virtual returns (address) { require(_exists(id), "NONEXISTENT_TOKEN"); return _tokenApprovals[id]; } /// @notice Returns if the `operator` is allowed to manage all of the assets of `owner`. /// @param owner The address of the owner. /// @param operator The address of the operator. /// @return True if `operator` was approved by `owner`. function isApprovedForAll(address owner, address operator) public view virtual returns (bool) { return _operatorApprovals[owner][operator]; } /// @notice Gives permission to `to` to transfer `id` token to another account. /// @dev 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. /// - `id` must exist. /// Emits an {Approval} event. /// @param spender The address of the spender to approve to. /// @param id The token ID to approve. function approve(address spender, uint256 id) public virtual { address owner = ownerOf(id); require(isApprovedForAll(owner, msg.sender) || msg.sender == owner, "NOT_AUTHORIZED"); _tokenApprovals[id] = spender; emit Approval(owner, spender, id); } /// @notice Approve or remove `operator` as an operator for the caller. /// @dev Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. /// Emits an {ApprovalForAll} event. /// @param operator The address of the operator to approve. /// @param approved The status to set. function setApprovalForAll(address operator, bool approved) public virtual { _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /// @notice Transfers `id` token from `from` to `to`. /// WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. /// @dev Requirements: /// - `to` cannot be the zero address. /// - `id` 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. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param id The token ID to transfer. function transferFrom( address from, address to, uint256 id ) public virtual { _transfer(from, to, id); } /// @notice Safely transfers `id` token from `from` to `to`. /// @dev Requirements: /// - `to` cannot be the zero address. /// - `id` 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 {ERC721TokenReceiver-onERC721Received}, which is called upon a safe transfer. /// Emits a {Transfer} event. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param id The token ID to transfer. function safeTransferFrom( address from, address to, uint256 id ) public virtual { _transfer(from, to, id); require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT"); } /// @notice Safely transfers `id` token from `from` to `to`. /// @dev Requirements: /// - `to` cannot be the zero address. /// - `id` 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 {ERC721TokenReceiver-onERC721Received}, which is called upon a safe transfer. /// Emits a {Transfer} event. /// Additionally passes `data` in the callback. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param id The token ID to transfer. /// @param data The calldata to pass in the {ERC721TokenReceiver-onERC721Received} callback. function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public virtual { _transfer(from, to, id); require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(msg.sender, from, id, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT"); } /// @notice Returns the number of tokens in an account. /// @param owner The address to query. /// @return The balance. function balanceOf(address owner) public view virtual returns (uint256); /// @notice Returns the owner of a token ID. /// @dev Requirements: /// - `id` must exist. /// @param id The token ID. function ownerOf(uint256 id) public view virtual returns (address); /* -------------------------------------------------------------------------- */ /* INTERNAL LOGIC */ /* -------------------------------------------------------------------------- */ /// @dev Returns whether a token ID exists. /// Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. /// Tokens start existing when they are minted. /// @param id Token ID to query. function _exists(uint256 id) internal view virtual returns (bool); /// @dev Transfers `id` from `from` to `to`. /// Requirements: /// - `to` cannot be the zero address. /// - `id` token must be owned by `from`. /// Emits a {Transfer} event. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param id The token ID to transfer. function _transfer( address from, address to, uint256 id ) internal virtual; /// @dev Mints `amount` tokens to `to`. /// Requirements: /// - there must be `amount` tokens remaining unminted in the total collection. /// - `to` cannot be the zero address. /// Emits `amount` {Transfer} events. /// @param to The address to mint to. /// @param amount The amount of tokens to mint. function _mint(address to, uint256 amount) internal virtual; /// @dev Safely mints `amount` of tokens and transfers them to `to`. /// If `to` is a contract it must implement {ERC721TokenReceiver.onERC721Received} /// that returns {ERC721TokenReceiver.onERC721Received.selector}. /// @param to The address to mint to. /// @param amount The amount of tokens to mint. function _safeMint(address to, uint256 amount) internal virtual { _mint(to, amount); require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(address(0), to, totalSupply() - amount + 1, "") == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT"); } /// @dev Safely mints `amount` of tokens and transfers them to `to`. /// Requirements: /// - `id` must not exist. /// - If `to` refers to a smart contract, it must implement {ERC721TokenReceiver.onERC721Received}, which is called upon a safe transfer. /// Additionally passes `data` in the callback. /// @param to The address to mint to. /// @param amount The amount of tokens to mint. /// @param data The calldata to pass in the {ERC721TokenReceiver.onERC721Received} callback. function _safeMint( address to, uint256 amount, bytes memory data ) internal virtual { _mint(to, amount); require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(address(0), to, totalSupply() - amount + 1, data) == ERC721TokenReceiver.onERC721Received.selector, "UNSAFE_RECIPIENT"); } /* -------------------------------------------------------------------------- */ /* UTILS */ /* -------------------------------------------------------------------------- */ /// @notice Converts a `uint256` to its ASCII `string` decimal representation. /// @dev https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol function toString(uint256 value) internal pure virtual 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); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import { ERC721 } from "./ERC721.sol"; abstract contract ERC721M is ERC721 { /* -------------------------------------------------------------------------- */ /* ERC721M STORAGE */ /* -------------------------------------------------------------------------- */ /// @dev The index is the token ID counter and points to its owner. address[] internal _owners; /* -------------------------------------------------------------------------- */ /* CONSTRUCTOR */ /* -------------------------------------------------------------------------- */ constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) { // Initializes the index to 1. _owners.push(); } /* -------------------------------------------------------------------------- */ /* ENUMERABLE LOGIC */ /* -------------------------------------------------------------------------- */ /// @inheritdoc ERC721 function totalSupply() public view override returns (uint256) { // Overflow is impossible as _owners.length is initialized to 1. unchecked { return _owners.length - 1; } } /// @dev O(totalSupply), it is discouraged to call this function from other contracts /// as it can become very expensive, especially with higher total collection sizes. /// @inheritdoc ERC721 function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < balanceOf(owner), "INVALID_INDEX"); // Both of the counters cannot overflow because the loop breaks before that. unchecked { uint256 count; uint256 _currentIndex = _owners.length; // == totalSupply() + 1 == _owners.length - 1 + 1 for (uint256 i; i < _currentIndex; i++) { if (owner == ownerOf(i)) { if (count == index) return i; else count++; } } } revert("NOT_FOUND"); } /// @inheritdoc ERC721 function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(_exists(index), "INVALID_INDEX"); return index; } /* -------------------------------------------------------------------------- */ /* ERC721 LOGIC */ /* -------------------------------------------------------------------------- */ /// @dev O(totalSupply), it is discouraged to call this function from other contracts /// as it can become very expensive, especially with higher total collection sizes. /// @inheritdoc ERC721 function balanceOf(address owner) public view virtual override returns (uint256 balance) { require(owner != address(0), "INVALID_OWNER"); unchecked { // Start at 1 since token 0 does not exist uint256 _currentIndex = _owners.length; // == totalSupply() + 1 == _owners.length - 1 + 1 for (uint256 i = 1; i < _currentIndex; i++) { if (owner == ownerOf(i)) { balance++; } } } } /// @dev O(MAX_TX), gradually moves to O(1) as more tokens get transferred and /// the owners are explicitly set. /// @inheritdoc ERC721 function ownerOf(uint256 id) public view virtual override returns (address owner) { require(_exists(id), "NONEXISTENT_TOKEN"); for (uint256 i = id; ; i++) { owner = _owners[i]; if (owner != address(0)) { return owner; } } } /* -------------------------------------------------------------------------- */ /* INTERNAL LOGIC */ /* -------------------------------------------------------------------------- */ /// @inheritdoc ERC721 function _mint(address to, uint256 amount) internal virtual override { require(to != address(0), "INVALID_RECIPIENT"); require(amount != 0, "INVALID_AMOUNT"); unchecked { uint256 _currentIndex = _owners.length; // == totalSupply() + 1 == _owners.length - 1 + 1 for (uint256 i; i < amount - 1; i++) { // storing address(0) while also incrementing the index _owners.push(); emit Transfer(address(0), to, _currentIndex + i); } // storing the actual owner _owners.push(to); emit Transfer(address(0), to, _currentIndex + (amount - 1)); } } /// @inheritdoc ERC721 function _exists(uint256 id) internal view virtual override returns (bool) { return id != 0 && id < _owners.length; } /// @inheritdoc ERC721 function _transfer( address from, address to, uint256 id ) internal virtual override { require(ownerOf(id) == from, "WRONG_FROM"); require(to != address(0), "INVALID_RECIPIENT"); require(msg.sender == from || getApproved(id) == msg.sender || isApprovedForAll(from, msg.sender), "NOT_AUTHORIZED"); delete _tokenApprovals[id]; _owners[id] = to; unchecked { uint256 prevId = id - 1; if (_owners[prevId] == address(0)) { _owners[prevId] = from; } } emit Transfer(from, to, id); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { ERC721 } from "../ERC721.sol"; /// @notice An interface for the OpenSea Proxy Registry. interface IProxyRegistry { function proxies(address) external view returns (address); } abstract contract ERC721Tradable is ERC721 { /* -------------------------------------------------------------------------- */ /* IMMUTABLE STORAGE */ /* -------------------------------------------------------------------------- */ /// @notice The OpenSea Proxy Registry address. address public immutable openSeaProxyRegistry; /// @notice The LooksRare Transfer Manager (ERC721) address. address public immutable looksRareTransferManager; /* -------------------------------------------------------------------------- */ /* MUTABLE STORAGE */ /* -------------------------------------------------------------------------- */ /// @notice Returns true if the stored marketplace addresses are whitelisted in {isApprovedForAll}. /// @dev Enabled by default. Can be turned off with {setMarketplaceApprovalForAll}. bool public marketPlaceApprovalForAll = true; /* -------------------------------------------------------------------------- */ /* CONSTRUCTOR */ /* -------------------------------------------------------------------------- */ /// OpenSea proxy registry addresses: /// - ETHEREUM MAINNET: 0xa5409ec958C83C3f309868babACA7c86DCB077c1 /// - ETHEREUM RINKEBY: 0xF57B2c51dED3A29e6891aba85459d600256Cf317 /// LooksRare Transfer Manager addresses (https://docs.looksrare.org/developers/deployed-contract-addresses): /// - ETHEREUM MAINNET: 0xf42aa99F011A1fA7CDA90E5E98b277E306BcA83e /// - ETHEREUM RINKEBY: 0x3f65A762F15D01809cDC6B43d8849fF24949c86a /// @param _openSeaProxyRegistry The OpenSea proxy registry address. constructor(address _openSeaProxyRegistry, address _looksRareTransferManager) { require(_openSeaProxyRegistry != address(0) && _looksRareTransferManager != address(0), "INVALID_ADDRESS"); openSeaProxyRegistry = _openSeaProxyRegistry; looksRareTransferManager = _looksRareTransferManager; } /* -------------------------------------------------------------------------- */ /* ERC721ATradable LOGIC */ /* -------------------------------------------------------------------------- */ /// @notice Enables or disables the marketplace whitelist in {isApprovedForAll}. /// @dev Must be implemented in inheriting contracts. /// Recommended to use in combination with an access control contract (e.g. OpenZeppelin's Ownable). function setMarketplaceApprovalForAll(bool approved) public virtual; /// @return True if `operator` is a whitelisted marketplace contract or if it was approved by `owner` with {ERC721A.setApprovalForAll}. /// @inheritdoc ERC721 function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { if (marketPlaceApprovalForAll && (operator == IProxyRegistry(openSeaProxyRegistry).proxies(owner) || operator == looksRareTransferManager)) return true; return super.isApprovedForAll(owner, operator); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice A generic interface for a contract which properly accepts ERC721 tokens. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC721.sol) interface ERC721TokenReceiver { function onERC721Received( address operator, address from, uint256 id, bytes calldata data ) external returns (bytes4); } // 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; } }
Requirements: - Caller must be the owner. @inheritdoc ERC721Tradable
function setMarketplaceApprovalForAll(bool approved) public override onlyOwner { marketPlaceApprovalForAll = approved; }
10,176,504
pragma solidity 0.6.7; pragma experimental ABIEncoderV2; import "./../openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./../openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./../openzeppelin/contracts/token/ERC721/IERC721.sol"; import "./../openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./../openzeppelin/contracts/math/SafeMath.sol"; import "./../openzeppelin/contracts/access/Ownable.sol"; import "./../openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./Crowns.sol"; import "./NftParamsInterface.sol"; import "./SwapSigner.sol"; /// @title Nft Swap is a part of Seascape marketplace platform. /// It allows users to obtain desired nfts in exchange for their offered nfts, /// a fee and an optional bounty /// @author Nejc Schneider contract NftSwap is Crowns, Ownable, ReentrancyGuard, IERC721Receiver { using SafeERC20 for IERC20; using SafeMath for uint256; SwapSigner private swapSigner; uint256 public lastOfferId; /// @dev keep count of offers (aka offerIds) bool public tradeEnabled = true; /// @dev enable/disable create and accept offer uint256 public fee; /// @dev fee for creating an offer /// @notice individual offer related data struct OfferObject{ uint256 offerId; // offer ID uint8 offeredTokensAmount; // total offered tokens uint8 requestedTokensAmount; // total requested tokens uint256 bounty; // reward for the buyer address bountyAddress; // currency address for paying bounties address payable seller; // seller's address uint256 fee; // fee amount at the time offer was created mapping(uint256 => OfferedToken) offeredTokens; // offered tokens data mapping(uint256 => RequestedToken) requestedTokens; // requested tokensdata } /// @notice individual offered token related data struct OfferedToken{ uint256 tokenId; // offered token id address tokenAddress; // offered token address } /// @notice individual requested token related data struct RequestedToken{ address tokenAddress; // requested token address bytes tokenParams; // requested token Params uint8 v; bytes32 r; bytes32 s; } /// @dev store offer objects. /// @param offerId => OfferObject mapping(uint256 => OfferObject) offerObjects; /// @dev supported ERC721 and ERC20 contracts mapping(address => bool) public supportedBountyAddresses; /// @dev parse params contract addresses (1 per individual nftSeries) /// @param nftAddress => nftParams contract address mapping(address => address) public supportedNftAddresses; event CreateOffer( uint256 indexed offerId, address indexed seller, uint256 bounty, address indexed bountyAddress, uint256 fee, uint256 offeredTokensAmount, uint256 requestedTokensAmount, OfferedToken [5] offeredTokens, RequestedToken [5] requestedTokens ); event AcceptOffer( uint256 indexed offerId, address indexed buyer, uint256 bounty, address indexed bountyAddress, uint256 fee, uint256 requestedTokensAmount, uint256 [5] requestedTokenIds, uint256 offeredTokensAmount, uint256 [5] offeredTokenIds ); event CancelOffer( uint256 indexed offerId, address indexed seller ); event NftReceived(address operator, address from, uint256 tokenId, bytes data); event Received(address, uint); /// @param _feeRate - fee amount /// @param _crownsAddress staking currency address constructor(uint256 _feeRate, address _crownsAddress, address _signerAddress) public { /// @dev set crowns is defined in Crowns.sol require(_crownsAddress != address(0x0), "invalid cws address"); setCrowns(_crownsAddress); fee = _feeRate; swapSigner = SwapSigner(_signerAddress); } //-------------------------------------------------- // External methods //-------------------------------------------------- fallback() external payable { emit Received(msg.sender, msg.value); } /// @notice enable/disable createOffer() and acceptOffer() functionality /// @param _tradeEnabled set tradeEnabled to true/false function enableTrade(bool _tradeEnabled) external onlyOwner { tradeEnabled = _tradeEnabled; } /// @notice enable additional nft series /// @param _nftAddress ERC721 contract address // @param _nftParamsAddress contract address function enableSupportedNftAddress( address _nftAddress, address _nftParamsAddress ) external onlyOwner { require(_nftAddress != address(0x0), "invalid nft address"); require(_nftParamsAddress != address(0x0), "invalid NftParams address"); require(supportedNftAddresses[_nftAddress] == address(0x0), "nft address already enabled"); supportedNftAddresses[_nftAddress] = _nftParamsAddress; } /// @notice disable nft series /// @param _nftAddress ERC721 contract address function disableSupportedNftAddress(address _nftAddress) external onlyOwner { require(_nftAddress != address(0x0), "invalid address"); require(supportedNftAddresses[_nftAddress] != address(0), "nft address already disabled"); supportedNftAddresses[_nftAddress] = address(0x0); } /// @notice enable additional bounty currency /// @param _bountyAddress ERC20 contract address function addSupportedBountyAddress(address _bountyAddress) external onlyOwner { require(!supportedBountyAddresses[_bountyAddress], "bounty already supported"); supportedBountyAddresses[_bountyAddress] = true; } /// @notice disable supported bounty currency /// @param _bountyAddress ERC20 contract address function removeSupportedBountyAddress(address _bountyAddress) external onlyOwner { require(supportedBountyAddresses[_bountyAddress], "bounty already removed"); supportedBountyAddresses[_bountyAddress] = false; } /// @notice update fee value. Change will only apply to new offers. /// @param _feeRate set fee to this value. function setFee(uint256 _feeRate) external onlyOwner { fee = _feeRate; } /// @notice returns amount of offers /// @return total amount of offer objects function getLastOfferId() external view returns(uint) { return lastOfferId; } /// @dev returns all properties of offer object at _offerId element /// @param _offerId unique offer ID /// @return OfferObject at given index function getOffer(uint _offerId) external view returns(uint256, uint8, uint8, uint256, address, address, uint256) { return ( offerObjects[_offerId].offerId, offerObjects[_offerId].offeredTokensAmount, offerObjects[_offerId].requestedTokensAmount, offerObjects[_offerId].bounty, offerObjects[_offerId].bountyAddress, offerObjects[_offerId].seller, offerObjects[_offerId].fee ); } //-------------------------------------------------- // Public methods //-------------------------------------------------- /// @notice by creating a new offer, msg.sender will transfer offered tokens, /// fee and an optional bounty to the contract /// @param _offeredTokens array of five OfferedToken structs /// @param _requestedTokens array of five RequestedToken structs /// @param _bounty additional cws to offer to buyer /// @return lastOfferId total amount of offers function createOffer( uint8 _offeredTokensAmount, OfferedToken [5] memory _offeredTokens, uint8 _requestedTokensAmount, RequestedToken [5] memory _requestedTokens, uint256 _bounty, address _bountyAddress ) public payable returns(uint256) { /// require statements require(tradeEnabled, "trade is disabled"); require(_offeredTokensAmount > 0, "should offer at least one nft"); require(_offeredTokensAmount <= 5, "cant offer more than 5 tokens"); require(_requestedTokensAmount > 0, "should require at least one nft"); require(_requestedTokensAmount <= 5, "cant request more than 5 tokens"); // bounty & fee related requirements if (_bounty > 0) { if (address(crowns) == _bountyAddress) { require(crowns.balanceOf(msg.sender) >= fee + _bounty, "not enough CWS for fee & bounty"); } else { require(supportedBountyAddresses[_bountyAddress], "bounty address not supported"); if (_bountyAddress == address(0x0)) { require (msg.value >= _bounty, "insufficient transfer amount"); uint256 returnBack = msg.value.sub(_bounty); if (returnBack > 0) msg.sender.transfer(returnBack); } else { IERC20 currency = IERC20(_bountyAddress); require(currency.balanceOf(msg.sender) >= _bounty, "not enough money to pay bounty"); } } } else { require(crowns.balanceOf(msg.sender) >= fee, "not enough CWS for fee"); } /// input token verification // verify offered nft oddresses and ids for (uint index = 0; index < _offeredTokensAmount; index++) { // the following checks should only apply if slot at index is filled. require(_offeredTokens[index].tokenId > 0, "nft id must be greater than 0"); require(supportedNftAddresses[_offeredTokens[index].tokenAddress] != address(0), "offered nft address unsupported"); IERC721 nft = IERC721(_offeredTokens[index].tokenAddress); require(nft.ownerOf(_offeredTokens[index].tokenId) == msg.sender, "sender not owner of nft"); } // verify requested nft oddresses for (uint _index = 0; _index < _requestedTokensAmount; _index++) { address nftParamsAddress = supportedNftAddresses[_requestedTokens[_index].tokenAddress]; require(nftParamsAddress != address(0), "requested nft address unsupported"); // verify nft parameters // external but trusted contract maintained by Seascape NftParamsInterface requestedToken = NftParamsInterface (nftParamsAddress); require(requestedToken.paramsAreValid(lastOfferId, _requestedTokens[_index].tokenParams, _requestedTokens[_index].v, _requestedTokens[_index].r, _requestedTokens[_index].s), "invalid nft Params"); } /// make transactions // send offered nfts to smart contract for (uint index = 0; index < _offeredTokensAmount; index++) { // send nfts to contract IERC721(_offeredTokens[index].tokenAddress) .safeTransferFrom(msg.sender, address(this), _offeredTokens[index].tokenId); } // send fee and _bounty to contract if (_bounty > 0) { if (_bountyAddress == address(crowns)) { IERC20(crowns).safeTransferFrom(msg.sender, address(this), fee + _bounty); } else { if (_bountyAddress == address(0)) { address(this).transfer(_bounty); } else { IERC20(_bountyAddress).safeTransferFrom(msg.sender, address(this), _bounty); } IERC20(crowns).safeTransferFrom(msg.sender, address(this), fee); } } else { IERC20(crowns).safeTransferFrom(msg.sender, address(this), fee); } /// update states lastOfferId++; offerObjects[lastOfferId].offerId = lastOfferId; offerObjects[lastOfferId].offeredTokensAmount = _offeredTokensAmount; offerObjects[lastOfferId].requestedTokensAmount = _requestedTokensAmount; for(uint256 i = 0; i < _offeredTokensAmount; i++){ offerObjects[lastOfferId].offeredTokens[i] = _offeredTokens[i]; } for(uint256 i = 0; i < _requestedTokensAmount; i++){ offerObjects[lastOfferId].requestedTokens[i] = _requestedTokens[i]; } offerObjects[lastOfferId].bounty = _bounty; offerObjects[lastOfferId].bountyAddress = _bountyAddress; offerObjects[lastOfferId].seller = msg.sender; offerObjects[lastOfferId].fee = fee; /// emit events emit CreateOffer( lastOfferId, msg.sender, _bounty, _bountyAddress, fee, _offeredTokensAmount, _requestedTokensAmount, _offeredTokens, _requestedTokens ); return lastOfferId; } /// @notice by accepting offer, buyer will transfer requested tokens to the seller, /// in exchange for offered tokens and an optional bounty. Fee is spend. function acceptOffer( uint256 _offerId, uint256 [5] memory _requestedTokenIds, address [5] memory _requestedTokenAddresses, uint8 [5] memory _v, bytes32 [5] memory _r, bytes32 [5] memory _s ) public nonReentrant payable { OfferObject storage obj = offerObjects[_offerId]; require(tradeEnabled, "trade is disabled"); require(msg.sender != obj.seller, "cant buy self-made offer"); /// @dev verify requested tokens for(uint256 i = 0; i < obj.requestedTokensAmount; i++){ require(_requestedTokenIds[i] > 0, "nft id must be greater than 0"); require(_requestedTokenAddresses[i] == obj.requestedTokens[i].tokenAddress, "wrong requested token address"); IERC721 nft = IERC721(obj.requestedTokens[i].tokenAddress); require(nft.ownerOf(_requestedTokenIds[i]) == msg.sender, "sender not owner of nft"); /// digital signature part bytes32 _messageNoPrefix = keccak256(abi.encodePacked( _offerId, _requestedTokenIds[i], _requestedTokenAddresses[i], msg.sender )); bytes32 _message = keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", _messageNoPrefix)); address _recover = ecrecover(_message, _v[i], _r[i], _s[i]); require(_recover == swapSigner.getSigner(), "Verification failed"); } /// make transactions // send requestedTokens from buyer to seller for (uint index = 0; index < obj.requestedTokensAmount; index++) { IERC721(_requestedTokenAddresses[index]) .safeTransferFrom(msg.sender, obj.seller, _requestedTokenIds[index]); } // send offeredTokens from SC to buyer for (uint index = 0; index < obj.offeredTokensAmount; index++) { IERC721(obj.offeredTokens[index].tokenAddress) .safeTransferFrom(address(this), msg.sender, obj.offeredTokens[index].tokenId); } // spend obj.fee and send obj.bounty from SC to buyer crowns.spend(obj.fee); if(obj.bounty > 0) { if(obj.bountyAddress == address(0)) msg.sender.transfer(obj.bounty); else IERC20(obj.bountyAddress).safeTransfer(msg.sender, obj.bounty); } /// emit events emit AcceptOffer( obj.offerId, msg.sender, obj.bounty, obj.bountyAddress, obj.fee, obj.requestedTokensAmount, _requestedTokenIds, obj.offeredTokensAmount, [obj.offeredTokens[0].tokenId, obj.offeredTokens[1].tokenId, obj.offeredTokens[2].tokenId, obj.offeredTokens[3].tokenId, obj.offeredTokens[4].tokenId] ); /// update states delete offerObjects[_offerId]; } /// @notice offered tokens, fee, and an optional bounty is returned to seller /// @param _offerId offer unique ID function cancelOffer(uint _offerId) public { OfferObject storage obj = offerObjects[_offerId]; require(obj.seller == msg.sender, "sender is not creator of offer"); /// make transactions // send the offeredTokens from SC to seller for (uint index=0; index < obj.offeredTokensAmount; index++) { IERC721(obj.offeredTokens[index].tokenAddress) .safeTransferFrom(address(this), obj.seller, obj.offeredTokens[index].tokenId); } // send crowns and bounty from SC to seller if (obj.bounty > 0) { if (obj.bountyAddress == address(crowns)) { crowns.transfer(msg.sender, obj.fee + obj.bounty); } else { if (obj.bountyAddress == address(0)) { msg.sender.transfer(obj.bounty); } else { IERC20(obj.bountyAddress).safeTransfer(msg.sender, obj.bounty); } crowns.transfer(msg.sender, obj.fee); } } else { crowns.transfer(msg.sender, obj.fee); } /// emit events emit CancelOffer( obj.offerId, obj.seller ); /// update states delete offerObjects[_offerId]; } /// @dev encrypt token data function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) public override returns (bytes4) { //only receive the _nft staff if (address(this) != operator) { //invalid from nft return 0; } //success emit NftReceived(operator, from, tokenId, data); return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @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/library/ReentrancyGuard.sol pragma solidity ^0.6.7; 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; } function initReentrancyStatus() internal { _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the 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.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity 0.6.7; import "./../openzeppelin/contracts/access/Ownable.sol"; /// @title SwapSigner holds address for signature verification. /// It is used by NftSwap and SwapParams contracts. /// @author Nejc Schneider contract SwapSigner is Ownable { address public signer; // @dev verify v, r, s signature constructor() public { signer = msg.sender; } /// @notice change address to verify signature against /// @param _signer new signer address function setSigner(address _signer) external onlyOwner { require(_signer != address(0), "invalid signer address"); signer = _signer; } /// @notice returns verifier of signatures /// @return signer address function getSigner() external view returns(address) { return signer; } } pragma solidity 0.6.7; /// @dev Interface of the nftSwapParams interface NftParamsInterface { /// @dev Returns true if signature is valid function paramsAreValid(uint256 _offerId, bytes calldata _encodedParams, uint8 v, bytes32 r, bytes32 s) external view returns (bool); } pragma solidity 0.6.7; import "./../crowns/erc-20/contracts/CrownsToken/CrownsToken.sol"; /// @dev Nft Rush and Leaderboard contracts both are with Crowns. /// So, making Crowns available for both Contracts by moving it to another contract. /// /// @author Medet Ahmetson contract Crowns { CrownsToken public crowns; function setCrowns(address _crowns) internal { require(_crowns != address(0), "Crowns can't be zero address"); crowns = CrownsToken(_crowns); } } // contracts/Crowns.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.7; import "./../../../../openzeppelin/contracts/access/Ownable.sol"; import "./../../../../openzeppelin/contracts/GSN/Context.sol"; import "./../../../../openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./../../../../openzeppelin/contracts/math/SafeMath.sol"; import "./../../../../openzeppelin/contracts/utils/Address.sol"; /// @title Official token of Blocklords and the Seascape ecosystem. /// @author Medet Ahmetson /// @notice Crowns (CWS) is an ERC-20 token with a Rebase feature. /// Rebasing is a distribution of spent tokens among all current token holders. /// In order to appear in balance, rebased tokens need to be claimed by users by triggering transaction with the ERC-20 contract. /// @dev Implementation of the {IERC20} interface. contract CrownsToken is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; struct Account { uint256 balance; uint256 lastRebase; } mapping (address => Account) private _accounts; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private constant _minSpend = 10 ** 6; uint256 private constant _decimalFactor = 10 ** 18; uint256 private constant _million = 1000000; /// @notice Total amount of tokens that have yet to be transferred to token holders as part of a rebase. /// @dev Used Variable tracking unclaimed rebase token amounts. uint256 public unclaimedRebase = 0; /// @notice Amount of tokens spent by users that have not been rebased yet. /// @dev Calling the rebase function will move the amount to {totalRebase} uint256 public unconfirmedRebase = 0; /// @notice Total amount of tokens that were rebased overall. /// @dev Total aggregate rebase amount that is always increasing. uint256 public totalRebase = 0; /** * @dev Sets the {name} and {symbol} of token. * Initializes {decimals} with a default value of 18. * Mints all tokens. * Transfers ownership to another account. So, the token creator will not be counted as an owner. */ constructor () public { _name = "Crowns"; _symbol = "CWS"; _decimals = 18; // Grant the minter roles to a specified account address inGameAirdropper = 0xFa4D7D1AC9b7a7454D09B8eAdc35aA70599329EA; address rechargeDexManager = 0x53bd91aEF5e84A61F9B87781A024ee648733f973; address teamManager = 0xB5de2b5186E1Edc947B73019F3102EF53c2Ac691; address investManager = 0x1D3Db9BCA5aa2CE931cE13B7B51f8E14F5895368; address communityManager = 0x0811e2DFb6482507461ca2Ab583844313f2549B5; address newOwner = msg.sender; // 3 million tokens uint256 inGameAirdrop = 3 * _million * _decimalFactor; uint256 rechargeDex = inGameAirdrop; // 1 million tokens uint256 teamAllocation = 1 * _million * _decimalFactor; uint256 investment = teamAllocation; // 750,000 tokens uint256 communityBounty = 750000 * _decimalFactor; // 1,25 million tokens uint256 inGameReserve = 1250000 * _decimalFactor; // reserve for the next 5 years. _mint(inGameAirdropper, inGameAirdrop); _mint(rechargeDexManager, rechargeDex); _mint(teamManager, teamAllocation); _mint(investManager, investment); _mint(communityManager, communityBounty); _mint(newOwner, inGameReserve); transferOwnership(newOwner); } /** * @notice Return amount of tokens that {account} gets during rebase * @dev Used both internally and externally to calculate the rebase amount * @param account is an address of token holder to calculate for * @return amount of tokens that player could get */ function rebaseOwing (address account) public view returns(uint256) { Account memory _account = _accounts[account]; uint256 newRebase = totalRebase.sub(_account.lastRebase); uint256 proportion = _account.balance.mul(newRebase); // The rebase is not a part of total supply, since it was moved out of balances uint256 supply = _totalSupply.sub(newRebase); // rebase owed proportional to current balance of the account. // The decimal factor is used to avoid floating issue. uint256 rebase = proportion.mul(_decimalFactor).div(supply).div(_decimalFactor); return rebase; } /** * @dev Called before any edit of {account} balance. * Modifier moves the belonging rebase amount to its balance. * @param account is an address of Token holder. */ modifier updateAccount(address account) { uint256 owing = rebaseOwing(account); _accounts[account].lastRebase = totalRebase; if (owing > 0) { _accounts[account].balance = _accounts[account].balance.add(owing); unclaimedRebase = unclaimedRebase.sub(owing); emit Transfer( address(0), account, owing ); } _; } /** * @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`). * * 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 Returns the amount of tokens in existence. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) public view override returns (uint256) { return _getBalance(account); } /** * @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) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @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) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @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) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @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) 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 updateAccount(sender) updateAccount(recipient) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Can not send 0 token"); require(_getBalance(sender) >= amount, "ERC20: Not enough token to send"); _beforeTokenTransfer(sender, recipient, amount); _accounts[sender].balance = _accounts[sender].balance.sub(amount); _accounts[recipient].balance = _accounts[recipient].balance.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); _accounts[account].balance = _accounts[account].balance.add(amount); emit Transfer(address(0), account, amount); } /** * @dev Moves `amount` tokens from `account` to {unconfirmedRebase} without reducing the * total supply. Will be rebased among token holders. * * 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 updateAccount(account) virtual { require(account != address(0), "ERC20: burn from the zero address"); require(_getBalance(account) >= amount, "ERC20: Not enough token to burn"); _beforeTokenTransfer(account, address(0), amount); _accounts[account].balance = _accounts[account].balance.sub(amount); unconfirmedRebase = unconfirmedRebase.add(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } /** * @notice Spend some token from caller's balance in the game. * @dev Moves `amount` of token from caller to `unconfirmedRebase`. * @param amount Amount of token used to spend */ function spend(uint256 amount) public returns(bool) { require(amount > _minSpend, "Crowns: trying to spend less than expected"); require(_getBalance(msg.sender) >= amount, "Crowns: Not enough balance"); _burn(msg.sender, amount); return true; } function spendFrom(address sender, uint256 amount) public returns(bool) { require(amount > _minSpend, "Crowns: trying to spend less than expected"); require(_getBalance(sender) >= amount, "Crowns: not enough balance"); _burn(sender, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @notice Return the rebase amount, when `account` balance was updated. */ function getLastRebase(address account) public view returns (uint256) { return _accounts[account].lastRebase; } /** * @dev Returns actual balance of account as a sum of owned divends and current balance. * @param account Address of Token holder. * @return Token amount */ function _getBalance(address account) private view returns (uint256) { uint256 balance = _accounts[account].balance; if (balance == 0) { return 0; } uint256 owing = rebaseOwing(account); return balance.add(owing); } /** * @dev Emitted when `spent` tokens are moved `unconfirmedRebase` to `totalRebase`. */ event Rebase( uint256 spent, uint256 totalRebase ); /** * @notice Rebasing is a unique feature of Crowns (CWS) token. It redistributes tokens spenth within game among all token holders. * @dev Moves tokens from {unconfirmedRebase} to {totalRebase}. * Any account balance related functions will use {totalRebase} to calculate the dividend shares for each account. * * Emits a {Rebase} event. */ function rebase() public onlyOwner() returns (bool) { totalRebase = totalRebase.add(unconfirmedRebase); unclaimedRebase = unclaimedRebase.add(unconfirmedRebase); unconfirmedRebase = 0; emit Rebase ( unconfirmedRebase, totalRebase ); return true; } }
Return amount of tokens that {account} gets during rebase Used both internally and externally to calculate the rebase amount account is an address of token holder to calculate for return amount of tokens that player could get/ The rebase is not a part of total supply, since it was moved out of balances rebase owed proportional to current balance of the account. The decimal factor is used to avoid floating issue.
function rebaseOwing (address account) public view returns(uint256) { Account memory _account = _accounts[account]; uint256 newRebase = totalRebase.sub(_account.lastRebase); uint256 proportion = _account.balance.mul(newRebase); uint256 supply = _totalSupply.sub(newRebase); uint256 rebase = proportion.mul(_decimalFactor).div(supply).div(_decimalFactor); return rebase; }
9,930,594
pragma solidity ^0.8.0; import "./interfaces/IRoyalties.sol"; import "./tokens/ERC721URIStorage.sol"; import "./utils/OwnableUpgradeable.sol"; import "./utils/Address.sol"; import "./utils/MerkleProof.sol"; contract uwudropShared is OwnableUpgradeable, ERC721Simple { using Address for address payable; string public baseURI; uint256 private _royaltyInBasisPoints = 300; uint256 public collectionIndex; uint256 public uwulabsFee; mapping(uint256 => bool) public collectionFinalized; mapping(uint256 => bytes32) public collectionDataRoot; mapping(uint256 => address) public collectionOwner; // maybe put in merkle tree for simplicity. mapping(uint256 => bytes32) public collectionManagers; mapping(uint256 => address) public derivativeSourceNFT; mapping(address => address) public derivativeSourceReceiver; mapping(address => uint256) public derivativeFee; /** * @dev Stores an optional alternate address to receive creator revenue and royalty payments. * The target address may be a contract which could split or escrow payments. */ address payable private _creatorPaymentAddress; event Purchase(uint256 collectionId, uint256 id); event CollectionUpdate(uint256 collectionId, uint256 newMaxSupply, bytes32 newNFTDataRoot, string customURI); event CollectionManagerUpdate(uint256 collectionId, bytes32 newCollectionManagerRoot); event Finalized(uint256 collectionId); function __uwudropShared_init(string memory _name, string memory _symbol, string memory _baseURI) external { __Ownable_init(); __ERC721Simple_init(_name, _symbol); setBaseURI(_baseURI); uwulabsFee = 0.01 gwei; } function createCollection(bytes32 dataRoot, address _derivativeSourceNFT) external { uint256 _collectionIndex = collectionIndex + 1; collectionIndex = _collectionIndex; collectionOwner[_collectionIndex] = msg.sender; collectionDataRoot[_collectionIndex] = dataRoot; derivativeSourceNFT[_collectionIndex] = _derivativeSourceNFT; } function updateCollectionData(uint256 collectionId, string memory customURI, uint256 newMaxSupply, bytes32 newNFTDataTreeRoot) external onlyOwner { require(!collectionFinalized[collectionId], "Finalized"); collectionDataRoot[collectionId] = newNFTDataTreeRoot; baseURI = customURI; emit CollectionUpdate(collectionId, newMaxSupply, newNFTDataTreeRoot, customURI); } // function managerUpdateCollectionData(uint256 collectionId, string memory customURI, uint256 newMaxSupply, bytes32 newNFTDataTreeRoot) external onlyOwner { // require(!collectionFinalized[collectionId], "Finalized"); // require(!collectionFinalized[collectionId], "Finalized"); // collectionDataRoot[collectionId] = newNFTDataTreeRoot; // baseURI = customURI; // emit CollectionUpdate(newMaxSupply, newNFTDataTreeRoot, customURI); // } function updateCollectionManagers(uint256 collectionId, bytes32 collectionManagerRoot) external { require(msg.sender == collectionOwner[collectionId], "Not collection owner"); collectionManagers[collectionId] = collectionManagerRoot; } function finalize(uint256 collectionId) external { require(msg.sender == collectionOwner[collectionId], "Not collection owner"); collectionFinalized[collectionId] = true; emit Finalized(collectionId); } function nftMint(uint256 collectionId, uint256 id, uint256 price, address sourceArtist, bool privateSale, bytes32[] memory merkleProof) external payable { uint256 _nftId = collectionId*1e6 | id; require(id < 1e6, "Above max"); require(_exists(_nftId), "Already purchased"); require(msg.value == price, "Not enough ETH"); bytes32 _dataRoot = collectionDataRoot[collectionId]; require(_dataRoot != bytes32(0), "Data Root not initialized"); { address receiver = address(0); if (privateSale) { receiver = msg.sender; } bytes32 node = keccak256(abi.encodePacked(collectionId, id, price, msg.value, receiver)); require(MerkleProof.verify(merkleProof, _dataRoot, node), 'MerkleDistributor: Invalid proof.'); } // uwulabs fee: 1%. uint256 _uwulabsFee = uwulabsFee; payable(owner()).sendValue((_uwulabsFee * msg.value)/1 gwei); // derivative source fee: variable. address _derivativeSourceNFT = derivativeSourceNFT[collectionId]; uint256 derivFee; if (_derivativeSourceNFT != address(0)) { derivFee = derivativeFee[_derivativeSourceNFT]; if (derivFee > 0) { payable(derivativeSourceReceiver[_derivativeSourceNFT]).sendValue((derivFee * msg.value)/1 gwei); } } // Rest goes to artist. payable(sourceArtist).sendValue(((1 gwei - derivFee - _uwulabsFee)*msg.value)/1 gwei); _mint(sourceArtist, msg.sender, _nftId); // Add more to this. emit Purchase(collectionId, id); } function setDerivativeSourceFee(address _derivativeSourceNFT, uint256 _derivFee, address _derivFeeReceiver) public { // require(); derivativeSourceReceiver[_derivativeSourceNFT] = _derivFeeReceiver; derivativeFee[_derivativeSourceNFT] = _derivFee; } function disperseETH() internal { uint256 fullAmount = address(this).balance; payable(msg.sender).sendValue(fullAmount*990/1000); payable(0x354A70969F0b4a4C994403051A81C2ca45db3615).sendValue(address(this).balance); } function setTokenCreatorPaymentAddress(address payable tokenCreatorPaymentAddress) external onlyOwner { _creatorPaymentAddress = tokenCreatorPaymentAddress; } function setRoyaltyInBasisPoints(uint256 royaltyInBasisPoints) external onlyOwner { _royaltyInBasisPoints = royaltyInBasisPoints; } function setBaseURI(string memory newURI) public onlyOwner { baseURI = newURI; } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { if ( interfaceId == type(IGetRoyalties).interfaceId || interfaceId == type(ITokenCreator).interfaceId || interfaceId == type(ITokenCreatorPaymentAddress).interfaceId || interfaceId == type(IGetFees).interfaceId ) { return true; } return super.supportsInterface(interfaceId); } /** * @notice Returns an array of recipient addresses to which royalties for secondary sales should be sent. * The expected royalty amount is communicated with `getFeeBps`. */ function getFeeRecipients(uint256 /*id*/) external view returns (address payable[] memory recipients) { recipients = new address payable[](1); recipients[0] = _creatorPaymentAddress; } /** * @notice Returns an array of royalties to be sent for secondary sales in basis points. * The expected recipients is communicated with `getFeeRecipients`. */ function getFeeBps( uint256 /* id */ ) external view returns (uint256[] memory feesInBasisPoints) { feesInBasisPoints = new uint256[](1); feesInBasisPoints[0] = _royaltyInBasisPoints; } /** * @notice Returns an array of royalties to be sent for secondary sales. **/ function getRoyalties(uint256 /*tokenId*/) external view returns (address payable[] memory recipients, uint256[] memory feesInBasisPoints) { recipients = new address payable[](1); recipients[0] = _creatorPaymentAddress; feesInBasisPoints = new uint256[](1); feesInBasisPoints[0] = _royaltyInBasisPoints; } /** * @notice Returns the creator for an NFT, which is always the collection owner. */ function tokenCreator( uint256 /* tokenId */ ) external view returns (address payable) { return payable(owner()); } /** * @notice Returns the desired payment address to be used for any transfers to the creator. * @dev The payment address may be assigned for each individual NFT, if not defined the collection owner is returned. */ function getTokenCreatorPaymentAddress(uint256 /* tokenId */) public view returns (address payable) { return _creatorPaymentAddress; } }
Returns an array of recipient addresses to which royalties for secondary sales should be sent. The expected royalty amount is communicated with `getFeeBps`./
function getFeeRecipients(uint256 /*id*/) external view returns (address payable[] memory recipients) { recipients = new address payable[](1); recipients[0] = _creatorPaymentAddress; }
7,294,016
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IERC721Facet.sol"; import "../interfaces/IERC721Consumable.sol"; import "../libraries/LibOwnership.sol"; import "../libraries/LibERC721.sol"; import "../shared/RentPayout.sol"; contract ERC721Facet is IERC721Facet, IERC721Consumable, RentPayout { using Strings for uint256; /// @notice Initialises the ERC721's name, symbol and base URI. /// @param _name The target name /// @param _symbol The target symbol /// @param _baseURI The target base URI function initERC721( string memory _name, string memory _symbol, string memory _baseURI ) external { LibERC721.ERC721Storage storage erc721 = LibERC721.erc721Storage(); require(!erc721.initialized, "ERC721 Storage already initialized"); erc721.initialized = true; erc721.name = _name; erc721.symbol = _symbol; erc721.baseURI = _baseURI; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view returns (uint256) { return LibERC721.balanceOf(owner); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view returns (address) { return LibERC721.ownerOf(tokenId); } /** * @dev See {IERC721Metadata-name}. */ function name() public view returns (string memory) { return LibERC721.erc721Storage().name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view returns (string memory) { return LibERC721.erc721Storage().symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view returns (string memory) { require( LibERC721.exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory base = ERC721Facet.baseURI(); return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString())) : ""; } /** * @dev Returns the base URI. */ function baseURI() public view returns (string memory) { return LibERC721.erc721Storage().baseURI; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view returns (uint256) { return LibERC721.erc721Storage().allTokens.length; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return LibERC721.erc721Storage().ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < totalSupply(), "ERC721Enumerable: global index out of bounds" ); return LibERC721.erc721Storage().allTokens[index]; } /** * @dev Sets the base URI. * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721Facet-tokenURI}. * * Requirements: * * - The caller must be the owner of the contract. */ function setBaseURI(string calldata _baseURI) public { LibOwnership.enforceIsContractOwner(); LibERC721.erc721Storage().baseURI = _baseURI; emit SetBaseURI(_baseURI); } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public { address owner = ERC721Facet.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); LibERC721.approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view returns (address) { return LibERC721.getApproved(tokenId); } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) external { require(operator != msg.sender, "ERC721: approve to caller"); LibERC721.erc721Storage().operatorApprovals[msg.sender][ operator ] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return LibERC721.isApprovedForAll(owner, operator); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public payout(tokenId) { //solhint-disable-next-line max-line-length require( LibERC721.isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved" ); LibERC721.transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public payout(tokenId) { require( LibERC721.isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved" ); LibERC721.safeTransfer(from, to, tokenId, _data); } /** * @dev See {IERC721Consumable-changeConsumer} */ function changeConsumer(address consumer, uint256 tokenId) public { require( LibERC721.isApprovedOrOwner(msg.sender, tokenId), "ERC721Consumer: change consumer caller is not owner nor approved" ); LibERC721.changeConsumer(ownerOf(tokenId), consumer, tokenId); } /** * @dev See {IERC721Consumable-consumerOf} */ function consumerOf(uint256 tokenId) public view returns (address) { return LibERC721.consumerOf(tokenId); } }
See {IERC721Enumerable-tokenOfOwnerByIndex}./
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); return LibERC721.erc721Storage().ownedTokens[owner][index]; }
15,781,084
./full_match/421611/0x0D75D46640ED2A50CbC0B59122C029edFddaB651/sources/github/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC721/ERC721min.sol
See {IERC721-ownerOf}./
function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(tokenId == 1, "ERC721: owner query for nonexistent token"); return _owner; }
13,221,598
./full_match/5/0x61b3E0fcEF001A8bcBd216c72bd78902ef8EA325/sources/project_/contracts/MetawinCollectibleRewardsSale.sol
Global toggle for the additional requirements filter: when switched off, the modifier {onlyIfHasRequirements} included in the {buy} function has no effect. Check {RequirementsCheck} contract for more info./
function toggleRequirementsFilters() external onlyOwner{ _toggleRequirementsCheck(); }
1,920,199
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol) pragma solidity ^0.8.0; import "../diamond/LibAppStorage.sol"; import "../interfaces/IERC1155.sol"; import "../interfaces/IPower.sol"; import "hardhat/console.sol"; interface ITokenAttributeSetter { function setAttribute( uint256 _tokenId, string memory key, uint256 value ) external; } /** * @dev Implements an NFT staking pool */ contract AttributeMutationPoolFacet is Modifiers, IPower { event AttributeMutationPoolValuesSet(string attributeKey, uint256 updateValuePerPeriod, uint256 blocksPerPeriod, uint256 totalValueThreshold); event TokenDeposited(address indexed staker, uint256 indexed tokenId); event TokenWithdrawn(address indexed staker, uint256 indexed tokenId, uint256 totalAccrued); event TokenValueThresholdReached(address indexed staker, uint256 indexed tokenId, uint256 totalAccrued); /// @notice set the attribute mutation pool settings function setAttributeMutationSettings(string memory attributeKey, uint256 updateValuePerPeriod, uint256 blocksPerPeriod, uint256 totalValueThreshold) public onlyOwner { require(bytes(attributeKey).length > 0, "attribute key cannot be empty"); require(updateValuePerPeriod > 0, "attribute value per block must be greater than 0"); s.attributeMutationPoolStorage._attributeKey = attributeKey; s.attributeMutationPoolStorage._attributeValuePerPeriod = updateValuePerPeriod; s.attributeMutationPoolStorage._attributeBlocksPerPeriod = blocksPerPeriod; s.attributeMutationPoolStorage._totalValueThreshold = totalValueThreshold; emit AttributeMutationPoolValuesSet(attributeKey, updateValuePerPeriod, blocksPerPeriod, totalValueThreshold); } /// @notice deposit the token into the pool function stake(uint256 tokenId) public { // require that this be a valid token with the correct attribute set to at least 1 uint256 currentAccruedValue = s.tokenAttributeStorage.attributes[tokenId][s.attributeMutationPoolStorage._attributeKey]; require(currentAccruedValue > 0, "token must have accrued value"); console.log("token id", tokenId); // require that this token not be already deposited uint256 tdHeight = s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId]; require(tdHeight == 0, "token has already been deposited"); console.log("token height", tdHeight); console.log("token", s.tokenMinterStorage.token); // require that the user have a quantity of the tokenId they specify require(IERC1155(s.tokenMinterStorage.token).balanceOf(msg.sender, tokenId) >= 1, "insufficient funds"); console.log("passed balance check"); // record the deposit in the variables to track it s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId] = block.number; IERC1155(s.tokenMinterStorage.token).safeTransferFrom(msg.sender, address(this), tokenId, 1, ""); console.log("transferred token"); console.log(s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId]); // emit a token deposited event emit TokenDeposited(msg.sender, tokenId); } /// @notice withdraw the accrued value for a token function unstake(uint256 tokenId) public { console.log(s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId]); // require( // s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId] > 0 && s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId] <= block.number, "token has not been deposited"); require(IERC1155(s.tokenMinterStorage.token).balanceOf(address(this), tokenId) >= 1, "insufficient funds"); uint256 currentAccruedValue = getAccruedValue(tokenId); s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId] = 0; // set the attribute to the value, or the total value if value > total value ITokenAttributeSetter(address(this)).setAttribute( tokenId, s.attributeMutationPoolStorage._attributeKey, currentAccruedValue > s.attributeMutationPoolStorage._totalValueThreshold ? s.attributeMutationPoolStorage._totalValueThreshold : currentAccruedValue ); emit PowerUpdated(tokenId, currentAccruedValue); // send the token back to the user IERC1155(s.tokenMinterStorage.token).safeTransferFrom(address(this), msg.sender, tokenId, 1, ""); // emit a token withdrawn event emit TokenWithdrawn(msg.sender, tokenId, currentAccruedValue); // emit a token value threshold reached event if threshold reached if(currentAccruedValue >= s.attributeMutationPoolStorage._totalValueThreshold) { emit TokenValueThresholdReached(msg.sender, tokenId, currentAccruedValue); } } /// @notice get the accrued value for a token function getAccruedValue(uint256 tokenId) public view returns (uint256 _currentAccruedValue) { uint256 depositBlockHeight = s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId]; require(depositBlockHeight > 0 && depositBlockHeight <= block.number, "token has not been deposited"); uint256 blocksDeposited = block.number - depositBlockHeight; uint256 accruedValue = blocksDeposited * s.attributeMutationPoolStorage._attributeValuePerPeriod / s.attributeMutationPoolStorage._attributeBlocksPerPeriod; _currentAccruedValue = accruedValue + s.tokenAttributeStorage.attributes[tokenId][s.attributeMutationPoolStorage._attributeKey]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/UInt256Set.sol"; import "../utils/AddressSet.sol"; import "../interfaces/IMarketplace.sol"; import "../interfaces/ITokenMinter.sol"; import "../interfaces/ITokenSale.sol"; import "../interfaces/IAirdropTokenSale.sol"; import "../interfaces/IERC721A.sol"; import {LibDiamond} from "./LibDiamond.sol"; // struct for erc1155 storage struct ERC1155Storage { mapping(uint256 => mapping(address => uint256)) _balances; mapping(address => mapping(address => bool)) _operatorApprovals; mapping(address => mapping(uint256 => uint256)) _minterApprovals; // mono-uri from erc1155 string _uri; string _uriBase; string _symbol; string _name; address _approvalProxy; } // struct for erc721a storage struct ERC721AStorage { // The tokenId of the next token to be minted. uint256 _currentIndex; // The number of tokens burned. uint256 _burnCounter; // Token name string _name; // Token symbol string _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => IERC721A.TokenOwnership) _ownerships; // Mapping owner address to address data mapping(address => IERC721A.AddressData) _addressData; // Mapping from token ID to approved address mapping(uint256 => address) _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) _operatorApprovals; } // erc2981 storage struct struct ERC2981Storage { // royalty receivers by token hash mapping(uint256 => address) royaltyReceiversByHash; // royalties for each token hash - expressed as permilliage of total supply mapping(uint256 => uint256) royaltyFeesByHash; } // attribute mutatiom pool storage struct AttributeMutationPoolStorage { string _attributeKey; uint256 _attributeValuePerPeriod; uint256 _attributeBlocksPerPeriod; uint256 _totalValueThreshold; mapping (address => mapping (uint256 => uint256)) _tokenDepositHeight; } // token attribute storage struct TokenAttributeStorage { mapping(uint256 => mapping(string => uint256)) attributes; } // merkle utils storage struct MerkleUtilsStorage { mapping(uint256 => uint256) tokenHashToIds; } // NFT marketplace storage struct MarketplaceStorage { uint256 itemsSold; uint256 itemIds; mapping(uint256 => IMarketplace.MarketItem) idToMarketItem; mapping(uint256 => bool) idToListed; } // token minter storage struct TokenMinterStorage { address token; uint256 _tokenCounter; mapping(uint256 => address) _tokenMinters; } // fractionalized token storage struct FractionalizedTokenData { string symbol; string name; address tokenAddress; uint256 tokenId; address fractionalizedToken; uint256 totalFractions; } // fractionalizer storage struct FractionalizerStorage { address fTokenTemplate; mapping(address => FractionalizedTokenData) fractionalizedTokens; } // token sale storage struct TokenSaleStorage { mapping(address => ITokenSale.TokenSaleEntry) tokenSaleEntries; } struct AirdropTokenSaleStorage { uint256 tsnonce; mapping(uint256 => uint256) nonces; // token sale settings mapping(uint256 => IAirdropTokenSale.TokenSaleSettings) _tokenSales; // is token sale open mapping(uint256 => bool) tokenSaleOpen; // total purchased tokens per drop - 0 for public tokensale mapping(uint256 => mapping(address => uint256)) purchased; // total purchased tokens per drop - 0 for public tokensale mapping(uint256 => uint256) totalPurchased; } struct MerkleAirdropStorage { mapping (uint256 => IAirdrop.AirdropSettings) _settings; uint256 numSettings; mapping (uint256 => mapping(uint256 => uint256)) _redeemedData; mapping (uint256 => mapping(address => uint256)) _redeemedDataQuantities; mapping (uint256 => mapping(address => uint256)) _totalDataQuantities; } struct MarketUtilsStorage { mapping(uint256 => bool) validTokens; } struct AppStorage { // gem pools data MarketplaceStorage marketplaceStorage; // gem pools data TokenMinterStorage tokenMinterStorage; // the erc1155 token ERC1155Storage erc1155Storage; // fractionalizer storage FractionalizerStorage fractionalizerStorage; // market utils storage MarketUtilsStorage marketUtilsStorage; // token sale storage TokenSaleStorage tokenSaleStorage; // merkle airdrop storage MerkleAirdropStorage merkleAirdropStorage; // erc721a storage ERC721AStorage erc721AStorage; // erc2981 storage ERC2981Storage erc2981Storage; // attribute mutation pool storage AttributeMutationPoolStorage attributeMutationPoolStorage; // token attribute storage TokenAttributeStorage tokenAttributeStorage; // airdrop token sale storage AirdropTokenSaleStorage airdropTokenSaleStorage; } library LibAppStorage { function diamondStorage() internal pure returns (AppStorage storage ds) { assembly { ds.slot := 0 } } } contract Modifiers { AppStorage internal s; modifier onlyOwner() { require(LibDiamond.contractOwner() == msg.sender || address(this) == msg.sender, "ERC1155: only the contract owner can call this function"); _; } } // 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 { /** * @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; interface IPower { event PowerUpdated (uint256 tokenId, uint256 power); } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /** * @notice Key sets with enumeration and delete. Uses mappings for random * and existence checks and dynamic arrays for enumeration. Key uniqueness is enforced. * @dev Sets are unordered. Delete operations reorder keys. All operations have a * fixed gas cost at any scale, O(1). * author: Rob Hitchens */ library UInt256Set { struct Set { mapping(uint256 => uint256) keyPointers; uint256[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, uint256 key) public { require( !exists(self, key), "UInt256Set: key already exists in the set." ); self.keyList.push(key); self.keyPointers[key] = self.keyList.length - 1; } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, uint256 key) public { // TODO: I commented this out do get a test to pass - need to figure out what is up here // require( // exists(self, key), // "UInt256Set: key does not exist in the set." // ); if (!exists(self, key)) return; uint256 last = count(self) - 1; uint256 rowToReplace = self.keyPointers[key]; if (rowToReplace != last) { uint256 keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; delete self.keyList[self.keyList.length - 1]; } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) public view returns (uint256) { return (self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, uint256 key) public view returns (bool) { if (self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint256 index) public view returns (uint256) { return self.keyList[index]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /** * @notice Key sets with enumeration and delete. Uses mappings for random * and existence checks and dynamic arrays for enumeration. Key uniqueness is enforced. * @dev Sets are unordered. Delete operations reorder keys. All operations have a * fixed gas cost at any scale, O(1). * author: Rob Hitchens */ library AddressSet { struct Set { mapping(address => uint256) keyPointers; address[] keyList; } /** * @notice insert a key. * @dev duplicate keys are not permitted. * @param self storage pointer to a Set. * @param key value to insert. */ function insert(Set storage self, address key) public { require( !exists(self, key), "AddressSet: key already exists in the set." ); self.keyList.push(key); self.keyPointers[key] = self.keyList.length - 1; } /** * @notice remove a key. * @dev key to remove must exist. * @param self storage pointer to a Set. * @param key value to remove. */ function remove(Set storage self, address key) public { // TODO: I commented this out do get a test to pass - need to figure out what is up here require( exists(self, key), "AddressSet: key does not exist in the set." ); if (!exists(self, key)) return; uint256 last = count(self) - 1; uint256 rowToReplace = self.keyPointers[key]; if (rowToReplace != last) { address keyToMove = self.keyList[last]; self.keyPointers[keyToMove] = rowToReplace; self.keyList[rowToReplace] = keyToMove; } delete self.keyPointers[key]; self.keyList.pop(); } /** * @notice count the keys. * @param self storage pointer to a Set. */ function count(Set storage self) public view returns (uint256) { return (self.keyList.length); } /** * @notice check if a key is in the Set. * @param self storage pointer to a Set. * @param key value to check. * @return bool true: Set member, false: not a Set member. */ function exists(Set storage self, address key) public view returns (bool) { if (self.keyList.length == 0) return false; return self.keyList[self.keyPointers[key]] == key; } /** * @notice fetch a key by row (enumerate). * @param self storage pointer to a Set. * @param index row to enumerate. Must be < count() - 1. */ function keyAtIndex(Set storage self, uint256 index) public view returns (address) { return self.keyList[index]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; interface IMarketplace { event Bids(uint256 indexed itemId, address bidder, uint256 amount); event Sales(uint256 indexed itemId, address indexed owner, uint256 amount, uint256 quantity, uint256 indexed tokenId); event Closes(uint256 indexed itemId); event Listings( uint256 indexed itemId, address indexed nftContract, uint256 indexed tokenId, address seller, address receiver, address owner, uint256 price, bool sold ); struct MarketItem { uint256 itemId; address nftContract; uint256 tokenId; address seller; address owner; uint256 price; uint256 quantity; bool sold; address receiver; } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./IERC1155Burn.sol"; /** * @notice This intreface provides a way for users to register addresses as permissioned minters, mint * burn, unregister, and reload the permissioned minter account. */ interface ITokenMinter { /// @notice a registration record for a permissioned minter. struct Minter { // the account address of the permissioned minter. address account; // the amount of tokens minted by the permissioned minter. uint256 minted; // the amount of tokens minted by the permissioned minter. uint256 burned; // the amount of payment spent by the permissioned minter. uint256 spent; // an approval map for this minter. sets a count of tokens the approved can mint. // mapping(address => uint256) approved; // TODO implement this. } /// @notice event emitted when minter is registered event MinterRegistered( address indexed registrant, uint256 depositPaid ); /// @notice emoitted when minter is unregistered event MinterUnregistered( address indexed registrant, uint256 depositReturned ); /// @notice emitted when minter address is reloaded event MinterReloaded( address indexed registrant, uint256 amountDeposited ); /// @notice get the registration record for a permissioned minter. /// @param _minter the address /// @return _minterObj the address function minter(address _minter) external returns (Minter memory _minterObj); /// @notice mint a token associated with a collection with an amount /// @param receiver the mint receiver /// @param collectionId the collection id /// @param amount the amount to mint function mint(address receiver, uint256 collectionId, uint256 id, uint256 amount) external; /// @notice mint a token associated with a collection with an amount /// @param target the mint receiver /// @param id the collection id /// @param amount the amount to mint function burn(address target, uint256 id, uint256 amount) external; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; /// /// @notice A token seller is a contract that can sell tokens to a token buyer. /// The token buyer can buy tokens from the seller by paying a certain amount /// of base currency to receive a certain amount of erc1155 tokens. the number /// of tokens that can be bought is limited by the seller - the seller can /// specify the maximum number of tokens that can be bought per transaction /// and the maximum number of tokens that can be bought in total for a given /// address. The seller can also specify the price of erc1155 tokens and how /// that price increases per successful transaction. interface ITokenSale { struct TokenSaleEntry { address payable receiver; address sourceToken; uint256 sourceTokenId; address token; uint256 quantity; uint256 price; uint256 quantitySold; } event TokenSaleSet(address indexed token, uint256 indexed tokenId, uint256 price, uint256 quantity); event TokenSold(address indexed buyer, address indexed tokenAddress, uint256 indexed tokenId, uint256 salePrice); event TokensSet(address indexed tokenAddress, ITokenSale.TokenSaleEntry tokens); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./ITokenPrice.sol"; import "./IAirdrop.sol"; /// @notice A token seller is a contract that can sell tokens to a token buyer. /// The token buyer can buy tokens from the seller by paying a certain amount /// of base currency to receive a certain amount of erc1155 tokens. the number /// of tokens that can be bought is limited by the seller - the seller can /// specify the maximum number of tokens that can be bought per transaction /// and the maximum number of tokens that can be bought in total for a given /// address. The seller can also specify the price of erc1155 tokens and how /// that price increases per successful transaction. interface IAirdropTokenSale { enum PaymentType { ETH, TOKEN } /// @notice the settings for the token sale, struct TokenSaleSettings { // addresses address contractAddress; // the contract doing the selling address token; // the token being sold uint256 tokenHash; // the token hash being sold. set to 0 to autocreate hash uint256 collectionHash; // the collection hash being sold. set to 0 to autocreate hash // owner and payee address owner; // the owner of the contract address payee; // the payee of the contract string symbol; // the symbol of the token string name; // the name of the token string description; // the description of the token // open state bool openState; // open or closed uint256 startTime; // block number when the sale starts uint256 endTime; // block number when the sale ends // quantities uint256 maxQuantity; // max number of tokens that can be sold uint256 maxQuantityPerSale; // max number of tokens that can be sold per sale uint256 minQuantityPerSale; // min number of tokens that can be sold per sale uint256 maxQuantityPerAccount; // max number of tokens that can be sold per account // inital price of the token sale ITokenPrice.TokenPriceData initialPrice; PaymentType paymentType; // the type of payment that is being used address tokenAddress; // the address of the payment token, if payment type is TOKEN } /// @notice emitted when a token is opened event TokenSaleOpen (uint256 tokenSaleId, TokenSaleSettings tokenSale ); /// @notice emitted when a token is opened event TokenSaleClosed (uint256 tokenSaleId, TokenSaleSettings tokenSale ); /// @notice emitted when a token is opened event TokenPurchased (uint256 tokenSaleId, address indexed purchaser, uint256 tokenId, uint256 quantity ); // token settings were updated event TokenSaleSettingsUpdated (uint256 tokenSaleId, TokenSaleSettings tokenSale ); /// @notice Get the token sale settings /// @return settings the token sale settings function getTokenSaleSettings(uint256 tokenSaleId) external view returns (TokenSaleSettings memory settings); /// @notice Updates the token sale settings /// @param settings - the token sake settings function updateTokenSaleSettings(uint256 iTokenSaleId, TokenSaleSettings memory settings) external; function initTokenSale( TokenSaleSettings memory tokenSaleInit, IAirdrop.AirdropSettings[] calldata settingsList ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721A { // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import { IDiamondCut } from "../interfaces/IDiamondCut.sol"; /// @notice Defines the data structures that are used to store the data for a diamond library LibDiamond { // the diamond storage position bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); /// @notice Stores the function selectors located within the Diamond struct DiamondStorage { // maps function selectors to the facets that execute the functions. // and maps the selectors to their position in the selectorSlots array. // func selector => address facet, selector position mapping(bytes4 => bytes32) facets; // array of slots of function selectors. // each slot holds 8 function selectors. mapping(uint256 => bytes32) selectorSlots; // The number of function selectors in selectorSlots uint16 selectorCount; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } /// @notice Returns the storage position of the diamond function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } // event is generated when the diamond ownership is transferred event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice set the diamond contract owner /// @param _newOwner the new owner of the diamond function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } /// @notice returns the diamond contract owner /// @return contractOwner_ the diamond contract owner function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } /// @notice enforce contract ownership by requiring the caller to be the contract owner function enforceIsContractOwner() internal view { require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner"); } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); bytes32 constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff)); bytes32 constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224)); // Internal function version of diamondCut // This code is almost the same as the external diamondCut, // except it is using 'Facet[] memory _diamondCut' instead of // 'Facet[] calldata _diamondCut'. // The code is duplicated to prevent copying calldata to memory which // causes an error for a two dimensional array. function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { DiamondStorage storage ds = diamondStorage(); uint256 originalSelectorCount = ds.selectorCount; uint256 selectorCount = originalSelectorCount; bytes32 selectorSlot; // Check if last selector slot is not full // "selectorCount & 7" is a gas efficient modulo by eight "selectorCount % 8" if (selectorCount & 7 > 0) { // get last selectorSlot // "selectorSlot >> 3" is a gas efficient division by 8 "selectorSlot / 8" selectorSlot = ds.selectorSlots[selectorCount >> 3]; } // loop through diamond cut for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { (selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors( selectorCount, selectorSlot, _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].action, _diamondCut[facetIndex].functionSelectors ); } if (selectorCount != originalSelectorCount) { ds.selectorCount = uint16(selectorCount); } // If last selector slot is not full // "selectorCount & 7" is a gas efficient modulo by eight "selectorCount % 8" if (selectorCount & 7 > 0) { // "selectorSlot >> 3" is a gas efficient division by 8 "selectorSlot / 8" ds.selectorSlots[selectorCount >> 3] = selectorSlot; } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } /// @notice add or replace facet selectors function addReplaceRemoveFacetSelectors( uint256 _selectorCount, bytes32 _selectorSlot, address _newFacetAddress, IDiamondCut.FacetCutAction _action, bytes4[] memory _selectors ) internal returns (uint256, bytes32) { DiamondStorage storage ds = diamondStorage(); require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); if (_action == IDiamondCut.FacetCutAction.Add) { enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; require(address(bytes20(oldFacet)) == address(0), "LibDiamondCut: Can't add function that already exists"); // add facet for selector ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount); // "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8" uint256 selectorInSlotPosition = (_selectorCount & 7) << 5; // clear selector position in slot and add selector _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) | (bytes32(selector) >> selectorInSlotPosition); // if slot is full then write it to storage if (selectorInSlotPosition == 224) { // "_selectorSlot >> 3" is a gas efficient division by 8 "_selectorSlot / 8" ds.selectorSlots[_selectorCount >> 3] = _selectorSlot; _selectorSlot = 0; } _selectorCount++; } } else if (_action == IDiamondCut.FacetCutAction.Replace) { enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code"); for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; address oldFacetAddress = address(bytes20(oldFacet)); // only useful if immutable functions exist require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function"); require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function"); require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist"); // replace old facet address ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress); } } else if (_action == IDiamondCut.FacetCutAction.Remove) { require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)"); // "_selectorCount >> 3" is a gas efficient division by 8 "_selectorCount / 8" uint256 selectorSlotCount = _selectorCount >> 3; // "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8" uint256 selectorInSlotIndex = _selectorCount & 7; for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) { if (_selectorSlot == 0) { // get last selectorSlot selectorSlotCount--; _selectorSlot = ds.selectorSlots[selectorSlotCount]; selectorInSlotIndex = 7; } else { selectorInSlotIndex--; } bytes4 lastSelector; uint256 oldSelectorsSlotCount; uint256 oldSelectorInSlotPosition; // adding a block here prevents stack too deep error { bytes4 selector = _selectors[selectorIndex]; bytes32 oldFacet = ds.facets[selector]; require(address(bytes20(oldFacet)) != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); // only useful if immutable functions exist require(address(bytes20(oldFacet)) != address(this), "LibDiamondCut: Can't remove immutable function"); // replace selector with last selector in ds.facets // gets the last selector lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex << 5)); if (lastSelector != selector) { // update last selector slot position info ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]); } delete ds.facets[selector]; uint256 oldSelectorCount = uint16(uint256(oldFacet)); // "oldSelectorCount >> 3" is a gas efficient division by 8 "oldSelectorCount / 8" oldSelectorsSlotCount = oldSelectorCount >> 3; // "oldSelectorCount & 7" is a gas efficient modulo by eight "oldSelectorCount % 8" oldSelectorInSlotPosition = (oldSelectorCount & 7) << 5; } if (oldSelectorsSlotCount != selectorSlotCount) { bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount]; // clears the selector we are deleting and puts the last selector in its place. oldSelectorSlot = (oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); // update storage with the modified slot ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot; } else { // clears the selector we are deleting and puts the last selector in its place. _selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) | (bytes32(lastSelector) >> oldSelectorInSlotPosition); } if (selectorInSlotIndex == 0) { delete ds.selectorSlots[selectorSlotCount]; _selectorSlot = 0; } } _selectorCount = selectorSlotCount * 8 + selectorInSlotIndex; } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } return (_selectorCount, _selectorSlot); } /// @notice initialise the DiamondCut contract function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// implemented by erc1155 tokens to allow burning interface IERC1155Burn { /// @notice event emitted when tokens are burned event Burned( address target, uint256 tokenHash, uint256 amount ); /// @notice burn tokens of specified amount from the specified address /// @param target the burn target /// @param tokenHash the token hash to burn /// @param amount the amount to burn function burn( address target, uint256 tokenHash, uint256 amount ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @notice common struct definitions for tokens interface ITokenPrice { /// @notice DIctates how the price of the token is increased post every sale enum PriceModifier { None, Fixed, Exponential, InverseLog } /// @notice a token price and how it changes struct TokenPriceData { // the price of the token uint256 price; // how the price is modified PriceModifier priceModifier; // only used if priceModifier is EXPONENTIAL or INVERSELOG or FIXED uint256 priceModifierFactor; // max price for the token uint256 maxPrice; } /// @notice get the increased price of the token function getIncreasedPrice() external view returns (uint256); /// @notice get the increased price of the token function getTokenPrice() external view returns (TokenPriceData memory); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "./IToken.sol"; import "./ITokenPrice.sol"; import "./IAirdropTokenSale.sol"; interface IMerkleAirdrop { function airdropRedeemed( uint256 drop, address recipient, uint256 amount ) external; function initMerkleAirdrops(IAirdrop.AirdropSettings[] calldata settingsList) external; function airdrop(uint256 drop) external view returns (IAirdrop.AirdropSettings memory settings); function airdropRedeemed(uint256 drop, address recipient) external view returns (bool isRedeemed); } /// @notice an airdrop airdrops tokens interface IAirdrop { // emitted when airdrop is redeemed /// @notice the settings for the token sale, struct AirdropSettings { // sell from the whitelist only bool whitelistOnly; // this whitelist id - by convention is the whitelist hash uint256 whitelistId; // the root hash of the merkle tree bytes32 whitelistHash; // quantities uint256 maxQuantity; // max number of tokens that can be sold uint256 maxQuantityPerSale; // max number of tokens that can be sold per sale uint256 minQuantityPerSale; // min number of tokens that can be sold per sale uint256 maxQuantityPerAccount; // max number of tokens that can be sold per account // quantity of item sold uint256 quantitySold; // start timne and end time for token sale uint256 startTime; // block number when the sale starts uint256 endTime; // block number when the sale ends // inital price of the token sale ITokenPrice.TokenPriceData initialPrice; // token hash uint256 tokenHash; IAirdropTokenSale.PaymentType paymentType; // the type of payment that is being used address tokenAddress; // the address of the payment token, if payment type is TOKEN // the address of the payment token, if payment type is ETH address payee; } // emitted when airdrop is launched event AirdropLaunched(uint256 indexed airdropId, AirdropSettings airdrop); // emitted when airdrop is redeemed event AirdropRedeemed(uint256 indexed airdropId, address indexed beneficiary, uint256 indexed tokenHash, bytes32[] proof, uint256 amount); /// @notice airdrops check to see if proof is redeemed /// @param drop the id of the airdrop /// @param recipient the merkle proof /// @return isRedeemed the amount of tokens redeemed function airdropRedeemed(uint256 drop, address recipient) external view returns (bool isRedeemed); /// @notice redeem tokens for airdrop /// @param drop the airdrop id /// @param leaf the index of the token in the airdrop /// @param recipient the beneficiary of the tokens /// @param amount tje amount of tokens to redeem /// @param merkleProof the merkle proof of the token function redeemAirdrop(uint256 drop, uint256 leaf, address recipient, uint256 amount, uint256 total, bytes32[] memory merkleProof) external payable; /// @notice Get the token sale settings /// @return settings the token sale settings function airdrop(uint256 drop) external view returns (AirdropSettings memory settings); } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @notice common struct definitions for tokens interface IToken { struct Token { uint256 id; uint256 balance; bool burn; } /// @notice a set of tokens. struct TokenSet { mapping(uint256 => uint256) keyPointers; uint256[] keyList; Token[] valueList; } /// @notice the definition for a token. struct TokenDefinition { // the host multitoken address token; // the id of the token definition. if static mint then also token hash uint256 id; // the category name uint256 collectionId; // the name of the token string name; // the symbol of the token string symbol; // the description of the token string description; // the decimals of the token. 0 for NFT uint8 decimals; // the total supply of the token uint256 totalSupply; // whether to generate the id or not for new tokens. if false then we use id field of the definition to mint tokens bool generateId; // probability of the item being awarded uint256 probability; // the index of the probability in its array uint256 probabilityIndex; // the index of the probability in its array uint256 probabilityRoll; } struct TokenRecord { uint256 id; address owner; address minter; uint256 _type; uint256 balance; } /// @notice the token source type. Either a static source or a collection. enum TokenSourceType { Static, Collection } /// @notice the token source. Specifies the source of the token - either a static source or a collection. struct TokenSource { // the token source type TokenSourceType _type; // the source id if a static collection uint256 staticSourceId; // the collection source address if collection address collectionSourceAddress; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; import "../utils/introspection/IERC165.sol"; // 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); }
deposit the token into the pool require that this be a valid token with the correct attribute set to at least 1 require that this token not be already deposited require that the user have a quantity of the tokenId they specify record the deposit in the variables to track it emit a token deposited event
function stake(uint256 tokenId) public { uint256 currentAccruedValue = s.tokenAttributeStorage.attributes[tokenId][s.attributeMutationPoolStorage._attributeKey]; require(currentAccruedValue > 0, "token must have accrued value"); console.log("token id", tokenId); uint256 tdHeight = s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId]; require(tdHeight == 0, "token has already been deposited"); console.log("token height", tdHeight); console.log("token", s.tokenMinterStorage.token); require(IERC1155(s.tokenMinterStorage.token).balanceOf(msg.sender, tokenId) >= 1, "insufficient funds"); console.log("passed balance check"); s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId] = block.number; IERC1155(s.tokenMinterStorage.token).safeTransferFrom(msg.sender, address(this), tokenId, 1, ""); console.log("transferred token"); console.log(s.attributeMutationPoolStorage._tokenDepositHeight[msg.sender][tokenId]); emit TokenDeposited(msg.sender, tokenId); }
581,893
./full_match/11155111/0x8D82Ef8521bCa834AD7BD112cE656d471c8d3699/sources/contracts/ProjectPosting.sol
IPF Algorithm for fair payout
function distributePayout(address payable[] memory freelancers, uint256[] memory rmseScores, uint256 totalPayout) public payable returns (uint256[] memory) { uint256[] memory weights = new uint256[](freelancers.length); uint256 totalWeight = 0; for (uint256 i = 0; i < freelancers.length; i++) { totalWeight += weights[i]; } uint256[] memory payouts = new uint256[](freelancers.length); uint256 totalPayoutTop3 = 0; for (uint256 i = 0; i < 3; i++) { payouts[i] = totalPayout * weights[i] / totalWeight; totalPayoutTop3 += payouts[i]; } uint256 averagePayoutTop3 = totalPayoutTop3 / 3; for (uint256 i = 0; i < 3; i++) { weights[i] = payouts[i] * 3 / averagePayoutTop3; } uint256 maxIterations = 100; uint256 epsilon = 1; uint256 iteration = 0; while (epsilon > 0 && iteration < maxIterations) { iteration++; totalWeight = 0; for (uint256 i = 0; i < freelancers.length; i++) { totalWeight += weights[i]; } epsilon = 0; for (uint256 i = 0; i < freelancers.length; i++) { uint256 newWeight = totalPayout * weights[i] / totalWeight; epsilon += absDiff(newWeight, weights[i]); weights[i] = newWeight; } } for (uint256 i = 0; i < 3; i++) { payouts[i] = totalPayout * weights[i] / totalWeight; } for (uint256 i = 0; i < freelancers.length; i++) { payouts[i] = totalPayout * weights[i] / totalWeight; freelancers[i].transfer(payouts[i]); } return payouts; }
3,799,952
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "./Imports.sol"; /* BLOBLOBLOBLOBLOBBLOBLOBLOBLOBLOBBLOBLOBLOBLOBLOBBLOBLOBL BLOBLOBLOBLOBLOBLOBB#=*+++++*=#BLOBLOBLOBLOBLOBLOBLOBLOB [email protected]*++::::::::::-----*@BLOBLOBLOBLOBLOBLOBB BLOBLOBLOBLOB#++++::::::::::---------=BLOBLOBLOBLOBLOBLO BLOBLOBLOBLO=+++++:::::::::-----------:@BLOBLOBLOBLOBLOB BLOBLOBLOBB=++++++:::::::::-------------#BLOBLOBLOBLOBLO [email protected]+++++++::::::::[email protected] BLOBLOBLOB*+++++++::[email protected]*------:@[email protected]:BLOBLOBLOBLOBL BLOBLOBLOB++++++++::#@WWW=*W+-----:@WW*@=-=BLOBLOBLOBLOB [email protected]++++++++:*#@WWW= #[email protected]*+W:+BLOBLOBLOBLOB BLOBLOBLO#++++++++:*#@@WW= *#------#WW= @[email protected] BLOBLOBLO#++++++++:*#@@WW= *@------=WW# ==-=BLOBLOBLOBLO BLOBLOBLO#+++++++++*#@@WW= +W------*[email protected] @-*BLOBLOBLOBLO BLOBLOBLO#+++++++++*#@@WW= +W------*[email protected] @-*BLOBLOBLOBLO BLOBLOBLO#++++++++++#@@WW= +W:-----*WWW+ W-+BLOBLOBLOBLO BLOBLOBLO#++++++++++#@@WW= +W:[email protected]+ W:+BLOBLOBLOBLO BLOBLOBLO#++++++++++#@@WW# +W+::---:@WW+ W++BLOBLOBLOBLO BLOBLOBLO#++++++++++#@@WW# +W+::::-:@WW* W++BLOBLOBLOBLO BLOBLOBLO#[email protected]@[email protected] *W:::::::#WW#+W++BLOBLOBLOBLO BLOBLOBLO#++++++++++*@@WWW*@@:::::::[email protected]:*BLOBLOBLOBLO BLOBLOBLO#+++++++++++#@WWWWW=:::::::+WWWW*:=BLOBLOBLOBLO BLOBLOBLO#++++++++++++*#@@=+::::::::::**:::#BLOBLOBLOBLO [email protected]++++++++++++++::;::::::::::;:::::@BLOBLOBLOBLO [email protected]+++++++++++++++::*@[email protected]*::::::BLOBLOBLOBLOB BLOBLOBLOB+++++++++++++++:::::::::::::::::*BLOBLOBLOBLOB BLOBLOBLOB++++++++++++++++::::::::::::::::=BLOBLOBLOBLOB BLOBLOBLOB*+++++++++++++++++::::::::::::::@BLOBLOBLOBLOB BLOBLOBLOB*++++++++++++++++++::::::::::::+BLOBLOBLOBLOBL BLOBLOBLOB=++++++++++++++++++++::::::::::=BLOBLOBLOBLOBL BLOBLOBLOB#++++++++++++++++++++++::::::::@BLOBLOBLOBLOBL [email protected]#2022 */ contract Blobs is BlobChecker, IERC1155Receiver, WithIPFSMetaData, WithFreezableMetadata, WithMarketOffers { address constant private BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; constructor (string memory cid) ERC721("Blob Mob", "BLOB") WithIPFSMetaData(cid) WithMarketOffers(payable(BLOB_LAB), 1000) {} /// @notice Create a new blob /// @param tokenIDs The list of tokenIDs to mint /// @param owners The list of owners that the tokenIDs should be airdropped to /// @param cid The new IPFS collection content identifyer function mint ( uint256[] memory tokenIDs, address[] memory owners, string memory cid ) external onlyOwner { require(_freeBlobs(tokenIDs), "Blob ID not allowed"); for (uint256 index = 0; index < tokenIDs.length; index++) { _mint(owners[index], tokenIDs[index]); } _setCID(cid); } /// @notice Burns the received Blob to mint a new one. function setCID (string memory cid) external onlyOwner unfrozen { _setCID(cid); } /// @notice Burns the received Blob to mint a new one. function onERC1155Received( address, address from, uint256 id, uint256, bytes calldata ) public override returns (bytes4) { require(_isBlob(id), "Not a Blob"); _migrateBlob(id, from); return IERC1155Receiver.onERC1155Received.selector; } /// @notice Burns received Blobs to mint new ones. function onERC1155BatchReceived( address, address from, uint256[] calldata ids, uint256[] calldata, bytes calldata ) external override returns (bytes4) { // First check whether all given IDs are actual Blobs... for (uint256 index = 0; index < ids.length; index++) { require(_isBlob(ids[index]), "Not a Blob"); } // Then migrate them one by one. for (uint256 index = 0; index < ids.length; index++) { _migrateBlob(ids[index], from); } return IERC1155Receiver.onERC1155BatchReceived.selector; } /// @notice Get the tokenURI for a specific token function tokenURI(uint256 tokenId) public view override(WithIPFSMetaData, ERC721) returns (string memory) { return WithIPFSMetaData.tokenURI(tokenId); } /// @notice We support the `HasSecondarySalesFees` interface function supportsInterface(bytes4 interfaceId) public view override(WithMarketOffers, ERC721, IERC165) returns (bool) { return WithMarketOffers.supportsInterface(interfaceId); } function _migrateBlob(uint256 id, address owner) private { uint256 tokenId = _getBlobTokenId(id); storefront.safeTransferFrom(address(this), BURN_ADDRESS, id, 1, ""); _safeMint(owner, tokenId); } function _baseURI() internal view override(WithIPFSMetaData, ERC721) returns (string memory) { return WithIPFSMetaData._baseURI(); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override(WithMarketOffers, ERC721) { return WithMarketOffers._beforeTokenTransfer(from, to, tokenId); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "@1001-digital/erc721-extensions/contracts/WithFreezableMetadata.sol"; import "@1001-digital/erc721-extensions/contracts/WithIPFSMetaData.sol"; import "@1001-digital/erc721-extensions/contracts/WithMarketOffers.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "./BlobChecker.sol"; // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /// @author 1001.digital /// @title A small helper to handle freezing of metadata contract WithFreezableMetadata is Ownable { // Whether metadata is frozen bool public frozen; /// @dev Freeze the metadata function freeze() external onlyOwner { frozen = true; } /// @dev Whether metadata is unfrozen modifier unfrozen() { require(! frozen, "Metadata already frozen"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @author 1001.digital /// @title Handle NFT Metadata stored on IPFS abstract contract WithIPFSMetaData is ERC721 { using Strings for uint256; /// @dev Emitted when the content identifyer changes event MetadataURIChanged(string indexed baseURI); /// @dev The content identifier of the folder containing all JSON files. string public cid; /// Instantiate the contract /// @param _cid the content identifier for the token metadata. /// @dev be careful & make sure your metadata is correct - you can't change this constructor (string memory _cid) { _setCID(_cid); } /// Get the tokenURI for a tokenID /// @param tokenId the token id for which to get the matadata URL /// @dev links to the metadata json file on IPFS. /// @return the URL to the token metadata file function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); // We don't check whether the _baseURI is set like in the OpenZeppelin implementation // as we're deploying the contract with the CID. return string(abi.encodePacked( _baseURI(), "/", tokenId.toString(), "/metadata.json" )); } /// Configure the baseURI for the tokenURI method. /// @dev override the standard OpenZeppelin implementation /// @return the IPFS base uri function _baseURI() internal view virtual override returns (string memory) { return string(abi.encodePacked("ipfs://", cid)); } /// Set the content identifier for this collection. /// @param _cid the new content identifier /// @dev update the content identifier for this nft. function _setCID(string memory _cid) internal virtual { cid = _cid; emit MetadataURIChanged(_baseURI()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@1001-digital/erc721-extensions/contracts/WithFees.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; /// @author 1001.digital /// @title Implement a basic integrated marketplace with fees abstract contract WithMarketOffers is ERC721, WithFees { event OfferCreated(uint256 indexed tokenId, uint256 indexed value, address indexed to); event OfferWithdrawn(uint256 indexed tokenId); event Sale(uint256 indexed tokenId, address indexed from, address indexed to, uint256 value); struct Offer { uint256 price; address payable specificBuyer; } /// @dev All active offers mapping (uint256 => Offer) private _offers; /// Instantiate the contract /// @param _feeRecipient the fee recipient for secondary sales /// @param _bps the basis points measure for the fees constructor (address payable _feeRecipient, uint256 _bps) WithFees(_feeRecipient, _bps) {} /// @dev All active offers function offerFor(uint256 tokenId) external view returns(Offer memory) { require(_offers[tokenId].price > 0, "No active offer for this item"); return _offers[tokenId]; } function _makeOffer(uint256 tokenId, uint256 price, address to) internal { require(_isApprovedOrOwner(_msgSender(), tokenId), "Caller is neither owner nor approved"); require(price > 0, "Price should be higher than 0"); require(price > _offers[tokenId].price, "Price should be higher than existing offer"); _offers[tokenId] = Offer(price, payable(to)); emit OfferCreated(tokenId, price, to); } /// @dev Make a new offer function makeOffer(uint256 tokenId, uint256 price) external { _makeOffer(tokenId, price, address(0)); } /// @dev Make a new offer to a specific person function makeOfferTo(uint256 tokenId, uint256 price, address to) external { _makeOffer(tokenId, price, to); } /// @dev Revoke an active offer function _cancelOffer(uint256 tokenId) private { delete _offers[tokenId]; emit OfferWithdrawn(tokenId); } /// @dev Allow approved operators to cancel an offer function cancelOffer(uint256 tokenId) external { require(_isApprovedOrOwner(_msgSender(), tokenId), "Caller is neither owner nor approved"); _cancelOffer(tokenId); } /// @dev Buy an item that is for offer function buy(uint256 tokenId) external payable isForSale(tokenId) { Offer memory offer = _offers[tokenId]; address payable seller = payable(ownerOf(tokenId)); // If it is a private sale, make sure the buyer is the private sale recipient. if (offer.specificBuyer != address(0)) { require(offer.specificBuyer == msg.sender, "Can't buy a privately offered item"); } require(msg.value >= offer.price, "Price not met"); // Seller gets msg value - fees set as BPS. seller.transfer(msg.value - (offer.price * bps / 10000)); // We transfer the token. _safeTransfer(seller, msg.sender, tokenId, ""); emit Sale(tokenId, seller, msg.sender, offer.price); } /// @dev Check whether the token is for sale modifier isForSale(uint256 tokenId) { require(_offers[tokenId].price > 0, "Item not for sale"); _; } /// We support the `HasSecondarySalesFees` interface function supportsInterface(bytes4 interfaceId) public view virtual override(WithFees, ERC721) returns (bool) { return WithFees.supportsInterface(interfaceId); } function _beforeTokenTransfer(address, address, uint256 tokenId) internal virtual override(ERC721) { if (_offers[tokenId].price > 0) { _cancelOffer(tokenId); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _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(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // 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: Unlicense pragma solidity ^0.8.4; import "./OpenSeaStorefrontInterface.sol"; contract BlobChecker { address constant private OPENSEA_STOREFRONT = 0x495f947276749Ce646f68AC8c248420045cb7b5e; address constant public BLOB_LAB = 0x9ac320589Def76E17C02a6436a1e8244d66998B7; OpenSeaStorefrontInterface internal storefront = OpenSeaStorefrontInterface(OPENSEA_STOREFRONT); function _freeBlobs (uint256[] memory ids) internal pure returns (bool) { for (uint256 index = 0; index < ids.length; index++) { if (! _isFreeBlob(ids[index])) return false; } return true; } function _isFreeBlob (uint256 id) internal pure returns (bool) { // Unclaimed Blobs if ( id >= 918 && id <= 984 && id != 983 // The zombie Blob is already alive :kek: ) { return true; } // Unclaimed golden Blobs if (id >= 993 && id <= 998) { return true; } return false; } // ReceivesOpenSeaBlobs function _isBlob (uint256 id) internal view returns (bool) { // Make sure it's a Blob created on the OpenSea storefront if (storefront.balanceOf(address(this), id) < 1) { return false; } // Make sure it's a Blob created by BlobLab if (id >> 96 != uint256(uint160(BLOB_LAB))) { return false; } return (id & 0xffffffffff) == 1; } function _getBlobTokenId (uint256 id) internal pure returns (uint256) { // Get only the token ID (without the token creator) uint256 _id = (id & 0xffffffffffffff0000000000) >> 40; // Special cases if (_id == 935) return 983; if (_id == 686) return 985; if (_id == 683) return 986; if (_id == 687) return 987; if (_id == 942) return 988; if (_id == 917) return 989; if (_id == 944) return 990; if (_id == 903) return 991; if (_id == 926) return 992; if (_id == 688) return 999; // Offsets (due to manual mint gaps) if (_id < 110) return _id - 9; if (_id < 190) return _id - 14; if (_id < 191) return _id - 20; if (_id < 216) return _id - 15; if (_id < 228) return _id - 17; if (_id < 335) return _id - 18; if (_id < 461) return _id - 19; if (_id < 575) return _id - 20; if (_id < 683) return _id - 21; if (_id < 686) return _id - 22; if (_id < 692) return _id - 25; if (_id < 800) return _id - 26; if (_id < 903) return _id - 27; if (_id < 917) return _id - 28; if (_id < 926) return _id - 29; if (_id < 935) return _id - 30; if (_id < 942) return _id - 31; if (_id < 944) return _id - 32; if (_id < 951) return _id - 33; revert("Token not found"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./standards/HasSecondarySaleFees.sol"; /// @author 1001.digital /// @title Implements the various fee standards that are floating around. /// @dev We need a proper standard for this. abstract contract WithFees is ERC721, HasSecondarySaleFees, Ownable { // The address to pay fees to address payable internal beneficiary; // The fee basis points uint256 internal bps; /// Instanciate the contract /// @param _beneficiary the address to send fees to /// @param _bps the basis points measure for the fees constructor (address payable _beneficiary, uint256 _bps) { beneficiary = _beneficiary; bps = _bps; } /// Implement the `HasSecondarySalesFees` Contract /// @dev implements the standard pushed by Rarible /// @return list of fee recipients, in our case always one function getFeeRecipients(uint256) public view override returns (address payable[] memory) { address payable[] memory recipients = new address payable[](1); recipients[0] = beneficiary; return recipients; } /// Implement the `HasSecondarySalesFees` Contract /// @dev implements the standard pushed by Rarible /// @return list of fee basis points, in our case always one function getFeeBps(uint256) public view override returns (uint256[] memory) { uint256[] memory bpsArray = new uint256[](1); bpsArray[0] = bps; return bpsArray; } /// Make sure the contract reports that it supportsthe `HasSecondarySalesFees` Interface /// @param interfaceId the interface to check /// @dev extends the ERC721 method /// @return whether the given interface is supported function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC165) returns (bool) { return interfaceId == type(HasSecondarySaleFees).interfaceId || ERC721.supportsInterface(interfaceId); } /// Exposes a way to update the secondary sale beneficiary /// @param _beneficiary the new beneficiary function setBeneficiary(address _beneficiary) public onlyOwner { beneficiary = payable(_beneficiary); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; abstract contract HasSecondarySaleFees is ERC165 { function getFeeRecipients(uint256 id) public view virtual returns (address payable[] memory); function getFeeBps(uint256 id) public view virtual returns (uint256[] memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; interface OpenSeaStorefrontInterface { function balanceOf(address _owner, uint256 _id) external view returns (uint256); function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) external; }
Burns the received Blob to mint a new one.
function setCID (string memory cid) external onlyOwner unfrozen { _setCID(cid); }
297,595
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract PillowSavings { struct SavingsPlan { uint savingsGoal; uint savingsBalance; } //new comment address payable pillowInc = payable(0x4B38016118FDE970e2371740F849840aEc745c7B); constructor() {} mapping(address => SavingsPlan) savingsAccounts; function createSavingsPlan(address _usersAddress, uint _savingsGoal) private { savingsAccounts[_usersAddress].savingsGoal = _savingsGoal; } function savingsBalance(address _usersAddress) view private returns(uint) { return savingsAccounts[_usersAddress].savingsBalance; } function transferDeposit(address _usersAddress, uint _amount) private { savingsAccounts[_usersAddress].savingsBalance += _amount; } function withdraw(address _usersAddress) private returns (uint) { //read savingsGoal from PillowSavings.sol, compare with savingsBalance amount, if the savingsBalance is less than the savingsGoal then charge a fee of 5%. if (savingsAccounts[_usersAddress].savingsGoal > savingsAccounts[_usersAddress].savingsBalance) { pillowInc.transfer(savingsAccounts[_usersAddress].savingsBalance * 5/100); savingsAccounts[_usersAddress].savingsBalance -= savingsAccounts[_usersAddress].savingsBalance * 5/100; } uint withdrawalAmount = savingsAccounts[_usersAddress].savingsBalance; savingsAccounts[_usersAddress].savingsBalance = 0; return withdrawalAmount; } }
read savingsGoal from PillowSavings.sol, compare with savingsBalance amount, if the savingsBalance is less than the savingsGoal then charge a fee of 5%.
function withdraw(address _usersAddress) private returns (uint) { if (savingsAccounts[_usersAddress].savingsGoal > savingsAccounts[_usersAddress].savingsBalance) { pillowInc.transfer(savingsAccounts[_usersAddress].savingsBalance * 5/100); savingsAccounts[_usersAddress].savingsBalance -= savingsAccounts[_usersAddress].savingsBalance * 5/100; } uint withdrawalAmount = savingsAccounts[_usersAddress].savingsBalance; savingsAccounts[_usersAddress].savingsBalance = 0; return withdrawalAmount; }
12,755,602
./full_match/1/0xF7eCC016FafF1D8c9265d9a1Aad33f0ed8787c94/sources/browser/DeloreanWeth.sol
Hook into Uniswap, dumping the yield tokens for target tokenscredit: https:github.com/flamincome/contracts/blob/bfbee3877aa7524408363516ceb2aab0d4527352/implementations/strategy/StrategyBaselineCarbonUniswapBTC.solL57 if the token we're swapping FROM is not WETH if the token we're swapping TO is not WETH
function _hookUniswap(address _operator, address _yield, address _dapp, address _target) internal { address weth = IUniswapV2Router02(uniswapRouterV2).WETH(); if(_yield != weth) { uint256 yieldBalance = IERC20(_yield).balanceOf(address(this)); IERC20(_yield).safeApprove(uniswapRouterV2, 0); IERC20(_yield).safeApprove(uniswapRouterV2, yieldBalance); address[] memory path1 = new address[](2); path1[0] = _yield; path1[1] = weth; IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokensSupportingFeeOnTransferTokens( yieldBalance, 0, path1, address(this), block.timestamp ); } if(_target != weth) { uint256 wethAmount = IERC20(weth).balanceOf(address(this)); IERC20(weth).safeApprove(uniswapRouterV2, 0); IERC20(weth).safeApprove(uniswapRouterV2, wethAmount); address[] memory path2 = new address[](2); path2[0] = weth; path2[1] = _target; IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokensSupportingFeeOnTransferTokens( wethAmount, 0, path2, address(this), block.timestamp ); if(_dapp != address(0x0)) _hookDapp(_target, _dapp, IERC20(_target).balanceOf(address(this)), _operator); } }
16,401,132
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; contract MockERC20 { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ /*////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ mapping(address => uint256) public nonces; /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ /*////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function mint(address to, uint256 amount) external { _mint(to, amount); } function burn(address from, uint256 amount) external { _burn(from, amount); } function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ /*////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } }
//////////////////
function mint(address to, uint256 amount) external { _mint(to, amount); }
1,050,814
./partial_match/1/0xFB15127f6464fcBB82b05Dc4b772283236C65167/sources/LexSecurityToken.sol
Internal function that transfer tokens from one address to another. Update pointsCorrection to keep funds unchanged. from The address to transfer from. to The address to transfer to. value The amount to be transferred./
function _transfer(address from, address to, uint256 value) internal { super._transfer(from, to, value); int256 _magCorrection = pointsPerShare.mul(value).toInt256Safe(); pointsCorrection[from] = pointsCorrection[from].add(_magCorrection); pointsCorrection[to] = pointsCorrection[to].sub(_magCorrection); }
3,647,134
pragma solidity ^0.8.0; /* */ /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } /* * @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 payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev 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 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } /** * @dev 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; } /** * @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); } /** * @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); } /** * @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); } function _approve(address to, uint256 tokenId) private { _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 {} } /** * @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); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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))) ); } } /** * @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)); } } /** * @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); } } /** * @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 ); } /** @title ERC-1155 Multi Token Standard @dev See https://eips.ethereum.org/EIPS/eip-1155 Note: The ERC-165 identifier for this interface is 0xd9b67a26. */ interface IERC1155 { /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_id` argument MUST be the token type being transferred. The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferSingle( address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value ); /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender). The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_ids` argument MUST be the list of tokens being transferred. The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferBatch( address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values ); /** @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absence of an event assumes disabled). */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** @dev MUST emit when the URI is updated for a token ID. URIs are defined in RFC 3986. The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". */ event URI(string _value, uint256 indexed _id); /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data ) external; /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _ids IDs of each token type (order and length must match _values array) @param _values Transfer amounts per token type (order and length must match _ids array) @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom( address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, 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 the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param _operator Address to add to the set of authorized operators @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** @notice Queries the approval status of an operator for a given owner. @param _owner The owner of the tokens @param _operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /** Note: The ERC-165 identifier for this interface is 0x4e2312e0. */ interface ERC1155TokenReceiver { /** @notice Handle the receipt of a single ERC1155 token type. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer. This function MUST revert if it rejects the transfer. Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @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)"))` */ function onERC1155Received( address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data ) external returns (bytes4); /** @notice Handle the receipt of multiple ERC1155 token types. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). This function MUST revert if it rejects the transfer(s). Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @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)"))` */ function onERC1155BatchReceived( address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data ) external returns (bytes4); } contract WrappedNonFungibleToken is ERC721, Ownable, ERC1155TokenReceiver { bytes32 internal _tokenIdArrayMerkleRoot; uint256 internal nextTokenId = 1; bool internal isContractFinalized = false; address public _wrappableContract; mapping(uint256 => uint256) public legacyTokenIdRegister; mapping(uint256 => uint256) public legacyTokenIdReverseRegister; constructor( string memory name, string memory symbol, address wrappableContract, bytes32 tokenIdArrayMerkleRoot ) ERC721(name, symbol) { _tokenIdArrayMerkleRoot = tokenIdArrayMerkleRoot; _wrappableContract = wrappableContract; } function updateRoot(bytes32 tokenIdArrayMerkleRoot_) external onlyOwner { if(!isContractFinalized) { _tokenIdArrayMerkleRoot = tokenIdArrayMerkleRoot_; } } function setContractFinalized() external onlyOwner { isContractFinalized = true; } /** * @dev Wraps NFTs */ function wrapWithProof(uint256 legacyTokenId, bytes32[] memory merkleProof) public returns (bool) { //require that the tokenId is in the tokenIdArray that was merkle hashed require( MerkleProof.verify( merkleProof, _tokenIdArrayMerkleRoot, keccak256(abi.encode(legacyTokenId)) ), "proof failure" ); IERC1155(_wrappableContract).safeTransferFrom( msg.sender, address(this), legacyTokenId, 1, "" ); //if this legacy token had never been wrapped, assign it to the register with a new id if (legacyTokenIdRegister[legacyTokenId] == 0) { legacyTokenIdRegister[legacyTokenId] = nextTokenId; legacyTokenIdReverseRegister[nextTokenId] = legacyTokenId; nextTokenId += 1; } _mint(msg.sender, legacyTokenIdRegister[legacyTokenId]); return true; } /** * @dev Wraps NFTs */ function wrapManyWithProof( uint256[] memory legacyTokenIds, bytes32[][] memory merkleProofs ) public returns (bool) { //require that the tokenId is in the tokenIdArray that was merkle hashed uint256 arrayLength = merkleProofs.length; for (uint256 i = 0; i < arrayLength; i++) { require( MerkleProof.verify( merkleProofs[i], _tokenIdArrayMerkleRoot, keccak256(abi.encode(legacyTokenIds[i])) ), "proof failure" ); } for (uint256 i = 0; i < arrayLength; i++) { uint256 legacyTokenId = legacyTokenIds[i]; IERC1155(_wrappableContract).safeTransferFrom( msg.sender, address(this), legacyTokenIds[i], 1, "" ); //if this legacy token had never been wrapped, assign it to the register with a new id if (legacyTokenIdRegister[legacyTokenId] == 0) { legacyTokenIdRegister[legacyTokenId] = nextTokenId; legacyTokenIdReverseRegister[nextTokenId] = legacyTokenId; nextTokenId += 1; } _mint(msg.sender, legacyTokenIdRegister[legacyTokenId]); } return true; } function unwrap(uint256 tokenId) public returns (bool) { require(ownerOf(tokenId) == msg.sender); //burn the wrapped token _burn(tokenId); //unlock and send back the legacy token IERC1155(_wrappableContract).safeTransferFrom( address(this), msg.sender, legacyTokenIdReverseRegister[tokenId], 1, "" ); return true; } /** * @notice Sets the Option contract metadata URI. * example: _baseURI ="https://api.niftyoptions.org/metadata/" * * Requirements: * - {_msgSender} must be the owner */ function setBaseURI(string calldata _uri) external onlyOwner { _setBaseURI(_uri); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); //mirror the old contract uri data return string( abi.encodePacked( baseURI(), uint2str(legacyTokenIdReverseRegister[tokenId]), "?format=json" ) ); } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function onERC1155Received( address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data ) external override 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 returns (bytes4) { return bytes4( keccak256( "onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)" ) ); } }
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 ====/ 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. solhint-disable-next-line no-inline-assembly
function _beforeTokenTransfer( address from, address to, uint256 tokenId } } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; }
11,933,775
// "SPDX-License-Identifier: MIT" pragma solidity ^0.6.6; // ---------------------------------------------------------------------------- // 'CovidCoin' token contract // // Deployed to : 0x4e2D8c9412548acEf6e4Fe696133c63df67b5Ad8 // Symbol : CVD // Name : CovidCoin // Total supply: 100000000000000000000000000 // Decimals : 15 // // (c) by A. Valentine, modified by CVD Team // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply() virtual public view returns (uint); function balanceOf(address tokenOwner) virtual public view returns (uint balance); function allowance(address tokenOwner, address spender) virtual public view returns (uint remaining); function transfer(address to, uint tokens) virtual public returns (bool success); function approve(address spender, uint tokens) virtual public returns (bool success); function transferFrom(address from, address to, uint tokens) virtual public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- abstract contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) virtual public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract CovidCoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; // New uint public _totalBurned; uint public _totalMinted; uint public BurnPercentage; uint public MintOfBurnedPercentage; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "CVD"; name = "CovidCoin"; decimals = 15; _totalSupply = 100000000000000000000000000; _totalBurned = 0; _totalMinted = 0; BurnPercentage = 2; MintOfBurnedPercentage = 50; balances[0x4e2D8c9412548acEf6e4Fe696133c63df67b5Ad8] = _totalSupply; emit Transfer(address(0), 0x4e2D8c9412548acEf6e4Fe696133c63df67b5Ad8, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public override returns (bool success) { uint256 tokensMinted = safeDiv(tokens, 100); uint256 tokensBurned = safeMul(tokensMinted, BurnPercentage); balances[msg.sender] = safeSub(balances[msg.sender], (tokens + tokensBurned)); balances[to] = safeAdd(balances[to], tokens); balances[0x4e2D8c9412548acEf6e4Fe696133c63df67b5Ad8] = safeAdd(balances[0x4e2D8c9412548acEf6e4Fe696133c63df67b5Ad8], tokensMinted); emit Transfer(msg.sender, to, tokens); emit Transfer(msg.sender, address(0), tokensBurned); emit Transfer(address(0), 0x4e2D8c9412548acEf6e4Fe696133c63df67b5Ad8, tokensMinted); _totalSupply = safeSub(_totalSupply, tokensMinted); _totalBurned = safeAdd(_totalBurned, tokensBurned); _totalMinted = safeAdd(_totalMinted, tokensMinted); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from account to account // // - Seller account must have sufficient balance to transfer // - Buyer must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public override returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ // function () external payable { // revert(); // } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
------------------------------------------------------------------------ Transfer the balance from token owner's account to to account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transfer(address to, uint tokens) public override returns (bool success) { uint256 tokensMinted = safeDiv(tokens, 100); uint256 tokensBurned = safeMul(tokensMinted, BurnPercentage); balances[msg.sender] = safeSub(balances[msg.sender], (tokens + tokensBurned)); balances[to] = safeAdd(balances[to], tokens); balances[0x4e2D8c9412548acEf6e4Fe696133c63df67b5Ad8] = safeAdd(balances[0x4e2D8c9412548acEf6e4Fe696133c63df67b5Ad8], tokensMinted); emit Transfer(msg.sender, to, tokens); emit Transfer(msg.sender, address(0), tokensBurned); emit Transfer(address(0), 0x4e2D8c9412548acEf6e4Fe696133c63df67b5Ad8, tokensMinted); _totalSupply = safeSub(_totalSupply, tokensMinted); _totalBurned = safeAdd(_totalBurned, tokensBurned); _totalMinted = safeAdd(_totalMinted, tokensMinted); return true; }
1,106,379
//SPDX-License-Identifier: UNLICENSED // Solidity files have to start with this pragma. // It will be used by the Solidity compiler to validate its version. pragma solidity ^0.8.0; // We import this library to be able to use console.log import "hardhat/console.sol"; contract Transactions { address private owner; uint256 transactionCounts; mapping (address => uint) balanceOf; event Transfer(address indexed sender, address indexed receiver, uint256 amount, uint256 timestamp); struct TransferStruct { address sender; address receiver; uint256 amount; uint256 timestamp; uint256 projectId; string nodeId; } TransferStruct[] transactions; mapping(uint => mapping(string => TransferStruct[])) public nested; constructor() { owner = msg.sender; balanceOf[tx.origin] = msg.sender.balance; } function getOwner() public view returns (address) { return owner; } function sendMoney(address payable receiver, uint256 amount, uint256 _projectId, string memory _nodeId) public returns(bool success) { if (balanceOf[owner] < amount) return false; balanceOf[owner] -= amount; balanceOf[receiver] += amount; transactionCounts += 1; transactions.push( TransferStruct( owner, receiver, amount, block.timestamp, _projectId, _nodeId ) ); //maybe load nestedx -> get the array TransferStruct[] storage pool = nested[_projectId][_nodeId] ; pool.push( TransferStruct( owner, receiver, amount, block.timestamp, _projectId, _nodeId ) ); nested[_projectId][_nodeId] = pool; emit Transfer(msg.sender, receiver, amount, block.timestamp); return true; } function getBalance(address addr) public view returns(uint) { return balanceOf[addr]; } function getAllTransactions() public view returns(TransferStruct[] memory) { return transactions; } function getPoolTransactions(uint256 _projectId, string memory _nodeId) public view returns(TransferStruct[] memory) { return nested[_projectId][_nodeId]; } // function getAddressTransactions(address _add) public view returns(TransferStruct[] memory) { // return nested[_add]; // } function getTransactionsCount() public view returns(uint256) { return transactionCounts; } } // This is the main building block for smart contracts. contract Token is Transactions { // Nested mapping (mapping from address to another mapping) uint256 number; mapping(uint256 => string) public mapFlow; function addFlow( string memory _data ) external { // do some require checks, probably a cooldown and balances uint256 id = number++; mapFlow[id] = _data; // emit ProposalExecute(id); } function updateFlow( uint256 _id, string memory _data ) external { // do some require checks, probably a cooldown and balances mapFlow[_id] = _data; // emit ProposalExecute(id); } function getFlows(uint256 _id ) external view returns(string memory){ // do some require checks, probably a cooldown and balances return mapFlow[_id]; // emit ProposalExecute(id); } function getTransactionsCountX() public view returns(uint256) { return Transactions.transactionCounts; } }
maybe load nestedx -> get the array
function sendMoney(address payable receiver, uint256 amount, uint256 _projectId, string memory _nodeId) public returns(bool success) { if (balanceOf[owner] < amount) return false; balanceOf[owner] -= amount; balanceOf[receiver] += amount; transactionCounts += 1; transactions.push( TransferStruct( owner, receiver, amount, block.timestamp, _projectId, _nodeId ) ); TransferStruct[] storage pool = nested[_projectId][_nodeId] ; pool.push( TransferStruct( owner, receiver, amount, block.timestamp, _projectId, _nodeId ) ); nested[_projectId][_nodeId] = pool; emit Transfer(msg.sender, receiver, amount, block.timestamp); return true; }
6,348,215
./full_match/5/0x079BC05ebF765c3678Bec03A598561f0414f6227/sources/project:/contracts/PropertyNFT.sol
Updates the sellFees attribute for a multiple tokenIds. tokenIds - Array of NFT token IDs. _sellFees - the new value for sellFees to be set. Only callable by an operator./
function updateBulkSellFees(uint256[] memory tokenIds, uint _sellFees) external onlyOperator { for (uint i = 0; i < tokenIds.length; i++) { require(_exists(tokenIds[i]), "NFT does not exist"); properties[tokenIds[i]].sellFees = _sellFees; } }
1,864,628
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } library addressSet { struct _addressSet { address[] members; mapping(address => uint) memberIndices; } function insert(_addressSet storage self, address other) public { if (!contains(self, other)) { assert(length(self) < 2**256-1); self.members.push(other); self.memberIndices[other] = length(self); } } function remove(_addressSet storage self, address other) public { if (contains(self, other)) { uint replaceIndex = self.memberIndices[other]; address lastMember = self.members[length(self)-1]; // overwrite other with the last member and remove last member self.members[replaceIndex-1] = lastMember; self.members.length--; // reflect this change in the indices self.memberIndices[lastMember] = replaceIndex; delete self.memberIndices[other]; } } function contains(_addressSet storage self, address other) public view returns (bool) { return self.memberIndices[other] > 0; } function length(_addressSet storage self) public view returns (uint) { return self.members.length; } } interface ERC20 { function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); } interface SnowflakeResolver { function callOnSignUp() external returns (bool); function onSignUp(string hydroId, uint allowance) external returns (bool); function callOnRemoval() external returns (bool); function onRemoval(string hydroId) external returns(bool); } interface ClientRaindrop { function getUserByAddress(address _address) external view returns (string userName); function isSigned( address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s ) external pure returns (bool); } interface ViaContract { function snowflakeCall(address resolver, string hydroIdFrom, string hydroIdTo, uint amount, bytes _bytes) external; function snowflakeCall(address resolver, string hydroIdFrom, address to, uint amount, bytes _bytes) external; } contract Snowflake is Ownable { using SafeMath for uint; using addressSet for addressSet._addressSet; // hydro token wrapper variable mapping (string => uint) internal deposits; // signature variables uint signatureTimeout; mapping (bytes32 => bool) signatureLog; // lookup mappings -- accessible only by wrapper functions mapping (string => Identity) internal directory; mapping (address => string) internal addressDirectory; mapping (bytes32 => string) internal initiatedAddressClaims; // admin/contract variables address public clientRaindropAddress; address public hydroTokenAddress; addressSet._addressSet resolverWhitelist; constructor() public { setSignatureTimeout(7200); } // identity structures struct Identity { address owner; addressSet._addressSet addresses; addressSet._addressSet resolvers; mapping(address => uint) resolverAllowances; } // checks whether the given address is owned by a token (does not throw) function hasToken(address _address) public view returns (bool) { return bytes(addressDirectory[_address]).length != 0; } // enforces that a particular address has a token modifier _hasToken(address _address, bool check) { require(hasToken(_address) == check, "The transaction sender does not have a Snowflake."); _; } // gets the HydroID for an address (throws if address doesn't have a HydroID or doesn't have a snowflake) function getHydroId(address _address) public view returns (string hydroId) { require(hasToken(_address), "The address does not have a hydroId"); return addressDirectory[_address]; } // allows whitelisting of resolvers function whitelistResolver(address resolver) public { resolverWhitelist.insert(resolver); emit ResolverWhitelisted(resolver); } function isWhitelisted(address resolver) public view returns(bool) { return resolverWhitelist.contains(resolver); } function getWhitelistedResolvers() public view returns(address[]) { return resolverWhitelist.members; } // set the signature timeout function setSignatureTimeout(uint newTimeout) public { require(newTimeout >= 1800, "Timeout must be at least 30 minutes."); require(newTimeout <= 604800, "Timeout must be less than a week."); signatureTimeout = newTimeout; } // set the raindrop and hydro token addresses function setAddresses(address clientRaindrop, address hydroToken) public onlyOwner { clientRaindropAddress = clientRaindrop; hydroTokenAddress = hydroToken; } // token minting function mintIdentityToken() public _hasToken(msg.sender, false) { _mintIdentityToken(msg.sender); } function mintIdentityTokenDelegated(address _address, uint8 v, bytes32 r, bytes32 s) public _hasToken(_address, false) { ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress); require( clientRaindrop.isSigned( _address, keccak256(abi.encodePacked("Create Snowflake", _address)), v, r, s ), "Permission denied." ); _mintIdentityToken(_address); } function _mintIdentityToken(address _address) internal { ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress); string memory hydroId = clientRaindrop.getUserByAddress(_address); Identity storage identity = directory[hydroId]; identity.owner = _address; identity.addresses.insert(_address); addressDirectory[_address] = hydroId; emit SnowflakeMinted(hydroId); } // wrappers that enable modifying resolvers function addResolvers(address[] resolvers, uint[] withdrawAllowances) public _hasToken(msg.sender, true) { _addResolvers(addressDirectory[msg.sender], resolvers, withdrawAllowances); } function addResolversDelegated( string hydroId, address[] resolvers, uint[] withdrawAllowances, uint8 v, bytes32 r, bytes32 s, uint timestamp ) public { require(directory[hydroId].owner != address(0), "Must initiate claim for a HydroID with a Snowflake"); // solium-disable-next-line security/no-block-members require(timestamp.add(signatureTimeout) > block.timestamp, "Message was signed too long ago."); ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress); require( clientRaindrop.isSigned( directory[hydroId].owner, keccak256(abi.encodePacked("Add Resolvers", resolvers, withdrawAllowances, timestamp)), v, r, s ), "Permission denied." ); _addResolvers(hydroId, resolvers, withdrawAllowances); } function _addResolvers( string hydroId, address[] resolvers, uint[] withdrawAllowances ) internal { require(resolvers.length == withdrawAllowances.length, "Malformed inputs."); Identity storage identity = directory[hydroId]; for (uint i; i < resolvers.length; i++) { require(resolverWhitelist.contains(resolvers[i]), "The given resolver is not on the whitelist."); require(!identity.resolvers.contains(resolvers[i]), "Snowflake has already set this resolver."); SnowflakeResolver snowflakeResolver = SnowflakeResolver(resolvers[i]); identity.resolvers.insert(resolvers[i]); identity.resolverAllowances[resolvers[i]] = withdrawAllowances[i]; if (snowflakeResolver.callOnSignUp()) { require( snowflakeResolver.onSignUp(hydroId, withdrawAllowances[i]), "Sign up failure." ); } emit ResolverAdded(hydroId, resolvers[i], withdrawAllowances[i]); } } function changeResolverAllowances(address[] resolvers, uint[] withdrawAllowances) public _hasToken(msg.sender, true) { _changeResolverAllowances(addressDirectory[msg.sender], resolvers, withdrawAllowances); } function changeResolverAllowancesDelegated( string hydroId, address[] resolvers, uint[] withdrawAllowances, uint8 v, bytes32 r, bytes32 s, uint timestamp ) public { require(directory[hydroId].owner != address(0), "Must initiate claim for a HydroID with a Snowflake"); bytes32 _hash = keccak256( abi.encodePacked("Change Resolver Allowances", resolvers, withdrawAllowances, timestamp) ); require(signatureLog[_hash] == false, "Signature was already submitted"); signatureLog[_hash] = true; ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress); require(clientRaindrop.isSigned(directory[hydroId].owner, _hash, v, r, s), "Permission denied."); _changeResolverAllowances(hydroId, resolvers, withdrawAllowances); } function _changeResolverAllowances(string hydroId, address[] resolvers, uint[] withdrawAllowances) internal { require(resolvers.length == withdrawAllowances.length, "Malformed inputs."); Identity storage identity = directory[hydroId]; for (uint i; i < resolvers.length; i++) { require(identity.resolvers.contains(resolvers[i]), "Snowflake has not set this resolver."); identity.resolverAllowances[resolvers[i]] = withdrawAllowances[i]; emit ResolverAllowanceChanged(hydroId, resolvers[i], withdrawAllowances[i]); } } function removeResolvers(address[] resolvers, bool force) public _hasToken(msg.sender, true) { Identity storage identity = directory[addressDirectory[msg.sender]]; for (uint i; i < resolvers.length; i++) { require(identity.resolvers.contains(resolvers[i]), "Snowflake has not set this resolver."); identity.resolvers.remove(resolvers[i]); delete identity.resolverAllowances[resolvers[i]]; if (!force) { SnowflakeResolver snowflakeResolver = SnowflakeResolver(resolvers[i]); if (snowflakeResolver.callOnRemoval()) { require( snowflakeResolver.onRemoval(addressDirectory[msg.sender]), "Removal failure." ); } } emit ResolverRemoved(addressDirectory[msg.sender], resolvers[i]); } } // functions to read token values (does not throw) function getDetails(string hydroId) public view returns ( address owner, address[] resolvers, address[] ownedAddresses, uint256 balance ) { Identity storage identity = directory[hydroId]; return ( identity.owner, identity.resolvers.members, identity.addresses.members, deposits[hydroId] ); } // check resolver membership (does not throw) function hasResolver(string hydroId, address resolver) public view returns (bool) { Identity storage identity = directory[hydroId]; return identity.resolvers.contains(resolver); } // check address ownership (does not throw) function ownsAddress(string hydroId, address _address) public view returns (bool) { Identity storage identity = directory[hydroId]; return identity.addresses.contains(_address); } // check resolver allowances (does not throw) function getResolverAllowance(string hydroId, address resolver) public view returns (uint withdrawAllowance) { Identity storage identity = directory[hydroId]; return identity.resolverAllowances[resolver]; } // allow contract to receive HYDRO tokens function receiveApproval(address sender, uint amount, address _tokenAddress, bytes _bytes) public { require(msg.sender == _tokenAddress, "Malformed inputs."); require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract."); address recipient; if (_bytes.length == 20) { assembly { // solium-disable-line security/no-inline-assembly recipient := div(mload(add(add(_bytes, 0x20), 0)), 0x1000000000000000000000000) } } else { recipient = sender; } require(hasToken(recipient), "Invalid token recipient"); ERC20 hydro = ERC20(_tokenAddress); require(hydro.transferFrom(sender, address(this), amount), "Unable to transfer token ownership."); deposits[addressDirectory[recipient]] = deposits[addressDirectory[recipient]].add(amount); emit SnowflakeDeposit(addressDirectory[recipient], sender, amount); } function snowflakeBalance(string hydroId) public view returns (uint) { return deposits[hydroId]; } // transfer snowflake balance from one snowflake holder to another function transferSnowflakeBalance(string hydroIdTo, uint amount) public _hasToken(msg.sender, true) { _transfer(addressDirectory[msg.sender], hydroIdTo, amount); } // withdraw Snowflake balance to an external address function withdrawSnowflakeBalance(address to, uint amount) public _hasToken(msg.sender, true) { _withdraw(addressDirectory[msg.sender], to, amount); } // allows resolvers to transfer allowance amounts to other snowflakes (throws if unsuccessful) function transferSnowflakeBalanceFrom(string hydroIdFrom, string hydroIdTo, uint amount) public { handleAllowance(hydroIdFrom, amount); _transfer(hydroIdFrom, hydroIdTo, amount); } // allows resolvers to withdraw allowance amounts to external addresses (throws if unsuccessful) function withdrawSnowflakeBalanceFrom(string hydroIdFrom, address to, uint amount) public { handleAllowance(hydroIdFrom, amount); _withdraw(hydroIdFrom, to, amount); } // allows resolvers to send withdrawal amounts to arbitrary smart contracts 'to' hydroIds (throws if unsuccessful) function withdrawSnowflakeBalanceFromVia( string hydroIdFrom, address via, string hydroIdTo, uint amount, bytes _bytes ) public { handleAllowance(hydroIdFrom, amount); _withdraw(hydroIdFrom, via, amount); ViaContract viaContract = ViaContract(via); viaContract.snowflakeCall(msg.sender, hydroIdFrom, hydroIdTo, amount, _bytes); } // allows resolvers to send withdrawal amounts 'to' addresses via arbitrary smart contracts function withdrawSnowflakeBalanceFromVia( string hydroIdFrom, address via, address to, uint amount, bytes _bytes ) public { handleAllowance(hydroIdFrom, amount); _withdraw(hydroIdFrom, via, amount); ViaContract viaContract = ViaContract(via); viaContract.snowflakeCall(msg.sender, hydroIdFrom, to, amount, _bytes); } function _transfer(string hydroIdFrom, string hydroIdTo, uint amount) internal returns (bool) { require(directory[hydroIdTo].owner != address(0), "Must transfer to an HydroID with a Snowflake"); require(deposits[hydroIdFrom] >= amount, "Cannot withdraw more than the current deposit balance."); deposits[hydroIdFrom] = deposits[hydroIdFrom].sub(amount); deposits[hydroIdTo] = deposits[hydroIdTo].add(amount); emit SnowflakeTransfer(hydroIdFrom, hydroIdTo, amount); } function _withdraw(string hydroIdFrom, address to, uint amount) internal { require(to != address(this), "Cannot transfer to the Snowflake smart contract itself."); require(deposits[hydroIdFrom] >= amount, "Cannot withdraw more than the current deposit balance."); deposits[hydroIdFrom] = deposits[hydroIdFrom].sub(amount); ERC20 hydro = ERC20(hydroTokenAddress); require(hydro.transfer(to, amount), "Transfer was unsuccessful"); emit SnowflakeWithdraw(to, amount); } function handleAllowance(string hydroIdFrom, uint amount) internal { Identity storage identity = directory[hydroIdFrom]; require(identity.owner != address(0), "Must withdraw from a HydroID with a Snowflake"); // check that resolver-related details are correct require(identity.resolvers.contains(msg.sender), "Resolver has not been set by from tokenholder."); if (identity.resolverAllowances[msg.sender] < amount) { emit InsufficientAllowance(hydroIdFrom, msg.sender, identity.resolverAllowances[msg.sender], amount); require(false, "Insufficient Allowance"); } identity.resolverAllowances[msg.sender] = identity.resolverAllowances[msg.sender].sub(amount); } // address ownership functions // to claim an address, users need to send a transaction from their snowflake address containing a sealed claim // sealedClaims are: keccak256(abi.encodePacked(<address>, <secret>, <hydroId>)), // where <address> is the address you'd like to claim, and <secret> is a SECRET bytes32 value. function initiateClaimDelegated(string hydroId, bytes32 sealedClaim, uint8 v, bytes32 r, bytes32 s) public { require(directory[hydroId].owner != address(0), "Must initiate claim for a HydroID with a Snowflake"); ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress); require( clientRaindrop.isSigned( directory[hydroId].owner, keccak256(abi.encodePacked("Initiate Claim", sealedClaim)), v, r, s ), "Permission denied." ); _initiateClaim(hydroId, sealedClaim); } function initiateClaim(bytes32 sealedClaim) public _hasToken(msg.sender, true) { _initiateClaim(addressDirectory[msg.sender], sealedClaim); } function _initiateClaim(string hydroId, bytes32 sealedClaim) internal { require(bytes(initiatedAddressClaims[sealedClaim]).length == 0, "This sealed claim has been submitted."); initiatedAddressClaims[sealedClaim] = hydroId; } function finalizeClaim(bytes32 secret, string hydroId) public { bytes32 possibleSealedClaim = keccak256(abi.encodePacked(msg.sender, secret, hydroId)); require( bytes(initiatedAddressClaims[possibleSealedClaim]).length != 0, "This sealed claim hasn't been submitted." ); // ensure that the claim wasn't stolen by another HydroID during initialization require( keccak256(abi.encodePacked(initiatedAddressClaims[possibleSealedClaim])) == keccak256(abi.encodePacked(hydroId)), "Invalid signature." ); directory[hydroId].addresses.insert(msg.sender); addressDirectory[msg.sender] = hydroId; emit AddressClaimed(msg.sender, hydroId); } function unclaim(address[] addresses) public _hasToken(msg.sender, true) { for (uint i; i < addresses.length; i++) { require(addresses[i] != directory[addressDirectory[msg.sender]].owner, "Cannot unclaim owner address."); directory[addressDirectory[msg.sender]].addresses.remove(addresses[i]); delete addressDirectory[addresses[i]]; emit AddressUnclaimed(addresses[i], addressDirectory[msg.sender]); } } // events event SnowflakeMinted(string hydroId); event ResolverWhitelisted(address indexed resolver); event ResolverAdded(string hydroId, address resolver, uint withdrawAllowance); event ResolverAllowanceChanged(string hydroId, address resolver, uint withdrawAllowance); event ResolverRemoved(string hydroId, address resolver); event SnowflakeDeposit(string hydroId, address from, uint amount); event SnowflakeTransfer(string hydroIdFrom, string hydroIdTo, uint amount); event SnowflakeWithdraw(address to, uint amount); event InsufficientAllowance( string hydroId, address indexed resolver, uint currentAllowance, uint requestedWithdraw ); event AddressClaimed(address indexed _address, string hydroId); event AddressUnclaimed(address indexed _address, string hydroId); }
check that resolver-related details are correct
function handleAllowance(string hydroIdFrom, uint amount) internal { Identity storage identity = directory[hydroIdFrom]; require(identity.owner != address(0), "Must withdraw from a HydroID with a Snowflake"); require(identity.resolvers.contains(msg.sender), "Resolver has not been set by from tokenholder."); function withdrawSnowflakeBalanceFromVia( string hydroIdFrom, address via, string hydroIdTo, uint amount, bytes _bytes } function withdrawSnowflakeBalanceFromVia( string hydroIdFrom, address via, address to, uint amount, bytes _bytes } } } if (identity.resolverAllowances[msg.sender] < amount) { emit InsufficientAllowance(hydroIdFrom, msg.sender, identity.resolverAllowances[msg.sender], amount); require(false, "Insufficient Allowance"); } identity.resolverAllowances[msg.sender] = identity.resolverAllowances[msg.sender].sub(amount); }
5,536,592
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // Sources flattened with hardhat v2.8.3 https://hardhat.org // File contracts/Math/Math.sol /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File contracts/Curve/IveFXS.sol pragma abicoder v2; interface IveFXS { struct LockedBalance { int128 amount; uint256 end; } function commit_transfer_ownership(address addr) external; function apply_transfer_ownership() external; function commit_smart_wallet_checker(address addr) external; function apply_smart_wallet_checker() external; function toggleEmergencyUnlock() external; function recoverERC20(address token_addr, uint256 amount) external; function get_last_user_slope(address addr) external view returns (int128); function user_point_history__ts(address _addr, uint256 _idx) external view returns (uint256); function locked__end(address _addr) external view returns (uint256); function checkpoint() external; function deposit_for(address _addr, uint256 _value) external; function create_lock(uint256 _value, uint256 _unlock_time) external; function increase_amount(uint256 _value) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; function balanceOf(address addr) external view returns (uint256); function balanceOf(address addr, uint256 _t) external view returns (uint256); function balanceOfAt(address addr, uint256 _block) external view returns (uint256); function totalSupply() external view returns (uint256); function totalSupply(uint256 t) external view returns (uint256); function totalSupplyAt(uint256 _block) external view returns (uint256); function totalFXSSupply() external view returns (uint256); function totalFXSSupplyAt(uint256 _block) external view returns (uint256); function changeController(address _newController) external; function token() external view returns (address); function supply() external view returns (uint256); function locked(address addr) external view returns (LockedBalance memory); function epoch() external view returns (uint256); function point_history(uint256 arg0) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt); function user_point_history(address arg0, uint256 arg1) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt); function user_point_epoch(address arg0) external view returns (uint256); function slope_changes(uint256 arg0) external view returns (int128); function controller() external view returns (address); function transfersEnabled() external view returns (bool); function emergencyUnlockActive() external view returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function version() external view returns (string memory); function decimals() external view returns (uint256); function future_smart_wallet_checker() external view returns (address); function smart_wallet_checker() external view returns (address); function admin() external view returns (address); function future_admin() external view returns (address); } // File contracts/Curve/IFraxGaugeController.sol // https://github.com/swervefi/swerve/edit/master/packages/swerve-contracts/interfaces/IGaugeController.sol interface IFraxGaugeController { struct Point { uint256 bias; uint256 slope; } struct VotedSlope { uint256 slope; uint256 power; uint256 end; } // Public variables function admin() external view returns (address); function future_admin() external view returns (address); function token() external view returns (address); function voting_escrow() external view returns (address); function n_gauge_types() external view returns (int128); function n_gauges() external view returns (int128); function gauge_type_names(int128) external view returns (string memory); function gauges(uint256) external view returns (address); function vote_user_slopes(address, address) external view returns (VotedSlope memory); function vote_user_power(address) external view returns (uint256); function last_user_vote(address, address) external view returns (uint256); function points_weight(address, uint256) external view returns (Point memory); function time_weight(address) external view returns (uint256); function points_sum(int128, uint256) external view returns (Point memory); function time_sum(uint256) external view returns (uint256); function points_total(uint256) external view returns (uint256); function time_total() external view returns (uint256); function points_type_weight(int128, uint256) external view returns (uint256); function time_type_weight(uint256) external view returns (uint256); // Getter functions function gauge_types(address) external view returns (int128); function gauge_relative_weight(address) external view returns (uint256); function gauge_relative_weight(address, uint256) external view returns (uint256); function get_gauge_weight(address) external view returns (uint256); function get_type_weight(int128) external view returns (uint256); function get_total_weight() external view returns (uint256); function get_weights_sum_per_type(int128) external view returns (uint256); // External functions function commit_transfer_ownership(address) external; function apply_transfer_ownership() external; function add_gauge( address, int128, uint256 ) external; function checkpoint() external; function checkpoint_gauge(address) external; function global_emission_rate() external view returns (uint256); function gauge_relative_weight_write(address) external returns (uint256); function gauge_relative_weight_write(address, uint256) external returns (uint256); function add_type(string memory, uint256) external; function change_type_weight(int128, uint256) external; function change_gauge_weight(address, uint256) external; function change_global_emission_rate(uint256) external; function vote_for_gauge_weights(address, uint256) external; } // File contracts/Curve/IFraxGaugeFXSRewardsDistributor.sol interface IFraxGaugeFXSRewardsDistributor { function acceptOwnership() external; function curator_address() external view returns(address); function currentReward(address gauge_address) external view returns(uint256 reward_amount); function distributeReward(address gauge_address) external returns(uint256 weeks_elapsed, uint256 reward_tally); function distributionsOn() external view returns(bool); function gauge_whitelist(address) external view returns(bool); function is_middleman(address) external view returns(bool); function last_time_gauge_paid(address) external view returns(uint256); function nominateNewOwner(address _owner) external; function nominatedOwner() external view returns(address); function owner() external view returns(address); function recoverERC20(address tokenAddress, uint256 tokenAmount) external; function setCurator(address _new_curator_address) external; function setGaugeController(address _gauge_controller_address) external; function setGaugeState(address _gauge_address, bool _is_middleman, bool _is_active) external; function setTimelock(address _new_timelock) external; function timelock_address() external view returns(address); function toggleDistributions() external; } // File contracts/Common/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return 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; } } // File contracts/Math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/ERC20/IERC20.sol /** * @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); } // 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"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/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 {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory __name, string memory __symbol) public { _name = __name; _symbol = __symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address.approve(address spender, uint256 amount) */ 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 the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for `accounts`'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal virtual { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } /** * @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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File contracts/Uniswap/TransferHelper.sol // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/Utils/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () 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 contracts/Staking/Owned.sol // https://docs.synthetix.io/contracts/Owned contract Owned { address public owner; address public nominatedOwner; constructor (address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // File contracts/Staking/FraxUnifiedFarmTemplate.sol pragma experimental ABIEncoderV2; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ====================== FraxUnifiedFarmTemplate ===================== // ==================================================================== // Migratable Farming contract that accounts for veFXS // Overrideable for UniV3, ERC20s, etc // New for V2 // - Two reward tokens possible // - Can add to existing locked stakes // - Contract is aware of proxied veFXS // - veFXS multiplier formula changed // Apes together strong // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Reviewer(s) / Contributor(s) // Jason Huan: https://github.com/jasonhuan // Sam Kazemian: https://github.com/samkazemian // Dennis: github.com/denett // Sam Sun: https://github.com/samczsun // Originally inspired by Synthetix.io, but heavily modified by the Frax team // (Locked, veFXS, and UniV3 portions are new) // https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol contract FraxUnifiedFarmTemplate is Owned, ReentrancyGuard { using SafeERC20 for ERC20; /* ========== STATE VARIABLES ========== */ // Instances IveFXS private veFXS = IveFXS(0xc8418aF6358FFddA74e09Ca9CC3Fe03Ca6aDC5b0); // Frax related address internal frax_address = 0x853d955aCEf822Db058eb8505911ED77F175b99e; bool internal frax_is_token0; uint256 private fraxPerLPStored; // Constant for various precisions uint256 internal constant MULTIPLIER_PRECISION = 1e18; // Time tracking uint256 public periodFinish; uint256 public lastUpdateTime; // Lock time and multiplier settings uint256 public lock_max_multiplier = uint256(3e18); // E18. 1x = e18 uint256 public lock_time_for_max_multiplier = 3 * 365 * 86400; // 3 years uint256 public lock_time_min = 86400; // 1 * 86400 (1 day) // veFXS related uint256 public vefxs_boost_scale_factor = uint256(4e18); // E18. 4x = 4e18; 100 / scale_factor = % vefxs supply needed for max boost uint256 public vefxs_max_multiplier = uint256(2e18); // E18. 1x = 1e18 uint256 public vefxs_per_frax_for_max_boost = uint256(2e18); // E18. 2e18 means 2 veFXS must be held by the staker per 1 FRAX mapping(address => uint256) internal _vefxsMultiplierStored; mapping(address => bool) internal valid_vefxs_proxies; mapping(address => mapping(address => bool)) internal proxy_allowed_stakers; // Reward addresses, gauge addresses, reward rates, and reward managers mapping(address => address) public rewardManagers; // token addr -> manager addr address[] internal rewardTokens; address[] internal gaugeControllers; address[] internal rewardDistributors; uint256[] internal rewardRatesManual; mapping(address => uint256) public rewardTokenAddrToIdx; // token addr -> token index // Reward period uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days) // Reward tracking uint256[] private rewardsPerTokenStored; mapping(address => mapping(uint256 => uint256)) private userRewardsPerTokenPaid; // staker addr -> token id -> paid amount mapping(address => mapping(uint256 => uint256)) private rewards; // staker addr -> token id -> reward amount mapping(address => uint256) internal lastRewardClaimTime; // staker addr -> timestamp // Gauge tracking uint256[] private last_gauge_relative_weights; uint256[] private last_gauge_time_totals; // Balance tracking uint256 internal _total_liquidity_locked; uint256 internal _total_combined_weight; mapping(address => uint256) internal _locked_liquidity; mapping(address => uint256) internal _combined_weights; // List of valid migrators (set by governance) mapping(address => bool) internal valid_migrators; // Stakers set which migrator(s) they want to use mapping(address => mapping(address => bool)) internal staker_allowed_migrators; mapping(address => address) public staker_designated_proxies; // Keep public so users can see on the frontend if they have a proxy // Greylists mapping(address => bool) internal greylist; // Admin booleans for emergencies, migrations, and overrides bool public stakesUnlocked; // Release locked stakes in case of emergency bool internal migrationsOn; // Used for migrations. Prevents new stakes, but allows LP and reward withdrawals bool internal withdrawalsPaused; // For emergencies bool internal rewardsCollectionPaused; // For emergencies bool internal stakingPaused; // For emergencies /* ========== STRUCTS ========== */ // In children... /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == owner || msg.sender == 0x8412ebf45bAC1B340BbE8F318b928C466c4E39CA, "Not owner or timelock"); _; } modifier onlyTknMgrs(address reward_token_address) { require(msg.sender == owner || isTokenManagerFor(msg.sender, reward_token_address), "Not owner or tkn mgr"); _; } modifier isMigrating() { require(migrationsOn == true, "Not in migration"); _; } modifier updateRewardAndBalance(address account, bool sync_too) { _updateRewardAndBalance(account, sync_too); _; } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRatesManual, address[] memory _gaugeControllers, address[] memory _rewardDistributors ) Owned(_owner) { // Address arrays rewardTokens = _rewardTokens; gaugeControllers = _gaugeControllers; rewardDistributors = _rewardDistributors; rewardRatesManual = _rewardRatesManual; for (uint256 i = 0; i < _rewardTokens.length; i++){ // For fast token address -> token ID lookups later rewardTokenAddrToIdx[_rewardTokens[i]] = i; // Initialize the stored rewards rewardsPerTokenStored.push(0); // Initialize the reward managers rewardManagers[_rewardTokens[i]] = _rewardManagers[i]; // Push in empty relative weights to initialize the array last_gauge_relative_weights.push(0); // Push in empty time totals to initialize the array last_gauge_time_totals.push(0); } // Other booleans stakesUnlocked = false; // Initialization lastUpdateTime = block.timestamp; periodFinish = block.timestamp + rewardsDuration; } /* ============= VIEWS ============= */ // ------ REWARD RELATED ------ // See if the caller_addr is a manager for the reward token function isTokenManagerFor(address caller_addr, address reward_token_addr) public view returns (bool){ if (caller_addr == owner) return true; // Contract owner else if (rewardManagers[reward_token_addr] == caller_addr) return true; // Reward manager return false; } // All the reward tokens function getAllRewardTokens() external view returns (address[] memory) { return rewardTokens; } // Last time the reward was applicable function lastTimeRewardApplicable() internal view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardRates(uint256 token_idx) public view returns (uint256 rwd_rate) { address gauge_controller_address = gaugeControllers[token_idx]; if (gauge_controller_address != address(0)) { rwd_rate = (IFraxGaugeController(gauge_controller_address).global_emission_rate() * last_gauge_relative_weights[token_idx]) / 1e18; } else { rwd_rate = rewardRatesManual[token_idx]; } } // Amount of reward tokens per LP token / liquidity unit function rewardsPerToken() public view returns (uint256[] memory newRewardsPerTokenStored) { if (_total_liquidity_locked == 0 || _total_combined_weight == 0) { return rewardsPerTokenStored; } else { newRewardsPerTokenStored = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ newRewardsPerTokenStored[i] = rewardsPerTokenStored[i] + ( ((lastTimeRewardApplicable() - lastUpdateTime) * rewardRates(i) * 1e18) / _total_combined_weight ); } return newRewardsPerTokenStored; } } // Amount of reward tokens an account has earned / accrued // Note: In the edge-case of one of the account's stake expiring since the last claim, this will // return a slightly inflated number function earned(address account) public view returns (uint256[] memory new_earned) { uint256[] memory reward_arr = rewardsPerToken(); new_earned = new uint256[](rewardTokens.length); if (_combined_weights[account] > 0){ for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = ((_combined_weights[account] * (reward_arr[i] - userRewardsPerTokenPaid[account][i])) / 1e18) + rewards[account][i]; } } // if (_combined_weights[account] == 0){ // for (uint256 i = 0; i < rewardTokens.length; i++){ // new_earned[i] = 0; // } // } // else { // for (uint256 i = 0; i < rewardTokens.length; i++){ // new_earned[i] = ((_combined_weights[account] * (reward_arr[i] - userRewardsPerTokenPaid[account][i])) / 1e18) // + rewards[account][i]; // } // } } // Total reward tokens emitted in the given period function getRewardForDuration() external view returns (uint256[] memory rewards_per_duration_arr) { rewards_per_duration_arr = new uint256[](rewardRatesManual.length); for (uint256 i = 0; i < rewardRatesManual.length; i++){ rewards_per_duration_arr[i] = rewardRates(i) * rewardsDuration; } } // ------ LIQUIDITY AND WEIGHTS ------ // User locked liquidity / LP tokens function totalLiquidityLocked() external view returns (uint256) { return _total_liquidity_locked; } // Total locked liquidity / LP tokens function lockedLiquidityOf(address account) external view returns (uint256) { return _locked_liquidity[account]; } // Total combined weight function totalCombinedWeight() external view returns (uint256) { return _total_combined_weight; } // Total 'balance' used for calculating the percent of the pool the account owns // Takes into account the locked stake time multiplier and veFXS multiplier function combinedWeightOf(address account) external view returns (uint256) { return _combined_weights[account]; } // Calculated the combined weight for an account function calcCurCombinedWeight(address account) public virtual view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { revert("Need cCCW logic"); } // ------ LOCK RELATED ------ // Multiplier amount, given the length of the lock function lockMultiplier(uint256 secs) public view returns (uint256) { return Math.min( lock_max_multiplier, uint256(MULTIPLIER_PRECISION) + ( (secs * (lock_max_multiplier - MULTIPLIER_PRECISION)) / lock_time_for_max_multiplier ) ) ; } // ------ FRAX RELATED ------ function userStakedFrax(address account) public view returns (uint256) { return (fraxPerLPStored * _locked_liquidity[account]) / MULTIPLIER_PRECISION; } // Meant to be overridden function fraxPerLPToken() public virtual view returns (uint256) { revert("Need fPLPT logic"); } // ------ veFXS RELATED ------ function minVeFXSForMaxBoost(address account) public view returns (uint256) { return (userStakedFrax(account) * vefxs_per_frax_for_max_boost) / MULTIPLIER_PRECISION; } function veFXSMultiplier(address account) public view returns (uint256 vefxs_multiplier) { // Use either the user's or their proxy's veFXS balance uint256 vefxs_bal_to_use = 0; { uint256 vefxs_user_bal = veFXS.balanceOf(account); uint256 vefxs_proxy_bal = veFXS.balanceOf(staker_designated_proxies[account]); vefxs_bal_to_use = (vefxs_user_bal > vefxs_proxy_bal ? vefxs_user_bal : vefxs_proxy_bal); } // First option based on fraction of total veFXS supply, with an added scale factor uint256 mult_optn_1 = (vefxs_bal_to_use * vefxs_max_multiplier * vefxs_boost_scale_factor) / (veFXS.totalSupply() * MULTIPLIER_PRECISION); // Second based on old method, where the amount of FRAX staked comes into play uint256 mult_optn_2; { uint256 veFXS_needed_for_max_boost = minVeFXSForMaxBoost(account); if (veFXS_needed_for_max_boost > 0){ uint256 user_vefxs_fraction = (vefxs_bal_to_use * MULTIPLIER_PRECISION) / veFXS_needed_for_max_boost; mult_optn_2 = (user_vefxs_fraction * vefxs_max_multiplier) / MULTIPLIER_PRECISION; } else mult_optn_2 = 0; // This will happen with the first stake, when user_staked_frax is 0 } // Select the higher of the three vefxs_multiplier = (mult_optn_1 > mult_optn_2 ? mult_optn_1 : mult_optn_2); // Cap the boost to the vefxs_max_multiplier if (vefxs_multiplier > vefxs_max_multiplier) vefxs_multiplier = vefxs_max_multiplier; } /* =============== MUTATIVE FUNCTIONS =============== */ // ------ MIGRATIONS ------ // Staker can allow a migrator function stakerToggleMigrator(address migrator_address) external { require(valid_migrators[migrator_address], "Invalid migrator address"); staker_allowed_migrators[msg.sender][migrator_address] = !staker_allowed_migrators[msg.sender][migrator_address]; } // Staker can allow a veFXS proxy (the proxy will have to toggle them first) function stakerSetVeFXSProxy(address proxy_address) external { require(valid_vefxs_proxies[proxy_address], "Invalid proxy"); require(proxy_allowed_stakers[proxy_address][msg.sender], "Proxy has not allowed you"); staker_designated_proxies[msg.sender] = proxy_address; } // Proxy can allow a staker to use their veFXS balance (the staker will have to reciprocally toggle them too) // Must come before stakerSetVeFXSProxy function proxyToggleStaker(address staker_address) external { require(valid_vefxs_proxies[msg.sender], "Invalid proxy"); proxy_allowed_stakers[msg.sender][staker_address] = !proxy_allowed_stakers[msg.sender][staker_address]; // Disable the staker's set proxy if it was the toggler and is currently on if (staker_designated_proxies[staker_address] == msg.sender){ staker_designated_proxies[staker_address] = address(0); } } // ------ STAKING ------ // In children... // ------ WITHDRAWING ------ // In children... // ------ REWARDS SYNCING ------ function _updateRewardAndBalance(address account, bool sync_too) internal { // Need to retro-adjust some things if the period hasn't been renewed, then start a new one if (sync_too){ sync(); } if (account != address(0)) { // To keep the math correct, the user's combined weight must be recomputed to account for their // ever-changing veFXS balance. ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) = calcCurCombinedWeight(account); // Calculate the earnings first _syncEarned(account); // Update the user's stored veFXS multipliers _vefxsMultiplierStored[account] = new_vefxs_multiplier; // Update the user's and the global combined weights if (new_combined_weight >= old_combined_weight) { uint256 weight_diff = new_combined_weight - old_combined_weight; _total_combined_weight = _total_combined_weight + weight_diff; _combined_weights[account] = old_combined_weight + weight_diff; } else { uint256 weight_diff = old_combined_weight - new_combined_weight; _total_combined_weight = _total_combined_weight - weight_diff; _combined_weights[account] = old_combined_weight - weight_diff; } } } function _syncEarned(address account) internal { if (account != address(0)) { // Calculate the earnings uint256[] memory earned_arr = earned(account); // Update the rewards array for (uint256 i = 0; i < earned_arr.length; i++){ rewards[account][i] = earned_arr[i]; } // Update the rewards paid array for (uint256 i = 0; i < earned_arr.length; i++){ userRewardsPerTokenPaid[account][i] = rewardsPerTokenStored[i]; } } } // ------ REWARDS CLAIMING ------ function _getRewardExtraLogic(address rewardee, address destination_address) internal virtual { revert("Need gREL logic"); } // Two different getReward functions are needed because of delegateCall and msg.sender issues function getReward(address destination_address) external nonReentrant returns (uint256[] memory) { require(rewardsCollectionPaused == false, "Rewards collection paused"); return _getReward(msg.sender, destination_address); } // No withdrawer == msg.sender check needed since this is only internally callable function _getReward(address rewardee, address destination_address) internal updateRewardAndBalance(rewardee, true) returns (uint256[] memory rewards_before) { // Update the rewards array and distribute rewards rewards_before = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardTokens.length; i++){ rewards_before[i] = rewards[rewardee][i]; rewards[rewardee][i] = 0; TransferHelper.safeTransfer(rewardTokens[i], destination_address, rewards_before[i]); } // Handle additional reward logic _getRewardExtraLogic(rewardee, destination_address); // Update the last reward claim time lastRewardClaimTime[rewardee] = block.timestamp; } // ------ FARM SYNCING ------ // If the period expired, renew it function retroCatchUp() internal { // Pull in rewards from the rewards distributor, if applicable for (uint256 i = 0; i < rewardDistributors.length; i++){ address reward_distributor_address = rewardDistributors[i]; if (reward_distributor_address != address(0)) { IFraxGaugeFXSRewardsDistributor(reward_distributor_address).distributeReward(address(this)); } } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 num_periods_elapsed = uint256(block.timestamp - periodFinish) / rewardsDuration; // Floor division to the nearest period // Make sure there are enough tokens to renew the reward period for (uint256 i = 0; i < rewardTokens.length; i++){ require((rewardRates(i) * rewardsDuration * (num_periods_elapsed + 1)) <= ERC20(rewardTokens[i]).balanceOf(address(this)), string(abi.encodePacked("Not enough reward tokens available: ", rewardTokens[i])) ); } // uint256 old_lastUpdateTime = lastUpdateTime; // uint256 new_lastUpdateTime = block.timestamp; // lastUpdateTime = periodFinish; periodFinish = periodFinish + ((num_periods_elapsed + 1) * rewardsDuration); // Update the rewards and time _updateStoredRewardsAndTime(); // Update the fraxPerLPStored fraxPerLPStored = fraxPerLPToken(); } function _updateStoredRewardsAndTime() internal { // Get the rewards uint256[] memory rewards_per_token = rewardsPerToken(); // Update the rewardsPerTokenStored for (uint256 i = 0; i < rewardsPerTokenStored.length; i++){ rewardsPerTokenStored[i] = rewards_per_token[i]; } // Update the last stored time lastUpdateTime = lastTimeRewardApplicable(); } function sync_gauge_weights(bool force_update) public { // Loop through the gauge controllers for (uint256 i = 0; i < gaugeControllers.length; i++){ address gauge_controller_address = gaugeControllers[i]; if (gauge_controller_address != address(0)) { if (force_update || (block.timestamp > last_gauge_time_totals[i])){ // Update the gauge_relative_weight last_gauge_relative_weights[i] = IFraxGaugeController(gauge_controller_address).gauge_relative_weight_write(address(this), block.timestamp); last_gauge_time_totals[i] = IFraxGaugeController(gauge_controller_address).time_total(); } } } } function sync() public { // Sync the gauge weight, if applicable sync_gauge_weights(false); if (block.timestamp >= periodFinish) { retroCatchUp(); } else { _updateStoredRewardsAndTime(); } } function sync_other() external { // Update the fraxPerLPStored fraxPerLPStored = fraxPerLPToken(); } /* ========== RESTRICTED FUNCTIONS - Curator / migrator callable ========== */ // ------ FARM SYNCING ------ // In children... // ------ PAUSES AND GREYLISTING ------ function setPauses( bool _stakingPaused, bool _withdrawalsPaused, bool _rewardsCollectionPaused ) external onlyByOwnGov { stakingPaused = _stakingPaused; withdrawalsPaused = _withdrawalsPaused; rewardsCollectionPaused = _rewardsCollectionPaused; } function greylistAddress(address _address) external onlyByOwnGov { greylist[_address] = !(greylist[_address]); } /* ========== RESTRICTED FUNCTIONS - Owner or timelock only ========== */ function unlockStakes() external onlyByOwnGov { stakesUnlocked = !stakesUnlocked; } function toggleMigrations() external onlyByOwnGov { migrationsOn = !migrationsOn; } // Adds supported migrator address function toggleMigrator(address migrator_address) external onlyByOwnGov { valid_migrators[migrator_address] = !valid_migrators[migrator_address]; } // Adds a valid veFXS proxy address function toggleValidVeFXSProxy(address _proxy_addr) external onlyByOwnGov { valid_vefxs_proxies[_proxy_addr] = !valid_vefxs_proxies[_proxy_addr]; } // Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyTknMgrs(tokenAddress) { // Check if the desired token is a reward token bool isRewardToken = false; for (uint256 i = 0; i < rewardTokens.length; i++){ if (rewardTokens[i] == tokenAddress) { isRewardToken = true; break; } } // Only the reward managers can take back their reward tokens // Also, other tokens, like the staking token, airdrops, or accidental deposits, can be withdrawn by the owner if ( (isRewardToken && rewardManagers[tokenAddress] == msg.sender) || (!isRewardToken && (msg.sender == owner)) ) { TransferHelper.safeTransfer(tokenAddress, msg.sender, tokenAmount); return; } // If none of the above conditions are true else { revert("No valid tokens to recover"); } } function setMiscVariables( uint256[6] memory _misc_vars // [0]: uint256 _lock_max_multiplier, // [1] uint256 _vefxs_max_multiplier, // [2] uint256 _vefxs_per_frax_for_max_boost, // [3] uint256 _vefxs_boost_scale_factor, // [4] uint256 _lock_time_for_max_multiplier, // [5] uint256 _lock_time_min ) external onlyByOwnGov { require(_misc_vars[0] >= MULTIPLIER_PRECISION, "Must be >= MUL PREC"); require((_misc_vars[1] >= 0) && (_misc_vars[2] >= 0) && (_misc_vars[3] >= 0), "Must be >= 0"); require((_misc_vars[4] >= 1) && (_misc_vars[5] >= 1), "Must be >= 1"); lock_max_multiplier = _misc_vars[0]; vefxs_max_multiplier = _misc_vars[1]; vefxs_per_frax_for_max_boost = _misc_vars[2]; vefxs_boost_scale_factor = _misc_vars[3]; lock_time_for_max_multiplier = _misc_vars[4]; lock_time_min = _misc_vars[5]; } // The owner or the reward token managers can set reward rates function setRewardVars(address reward_token_address, uint256 _new_rate, address _gauge_controller_address, address _rewards_distributor_address) external onlyTknMgrs(reward_token_address) { rewardRatesManual[rewardTokenAddrToIdx[reward_token_address]] = _new_rate; gaugeControllers[rewardTokenAddrToIdx[reward_token_address]] = _gauge_controller_address; rewardDistributors[rewardTokenAddrToIdx[reward_token_address]] = _rewards_distributor_address; } // The owner or the reward token managers can change managers function changeTokenManager(address reward_token_address, address new_manager_address) external onlyTknMgrs(reward_token_address) { rewardManagers[reward_token_address] = new_manager_address; } /* ========== A CHICKEN ========== */ // // ,~. // ,-'__ `-, // {,-' `. } ,') // ,( a ) `-.__ ,',')~, // <=.) ( `-.__,==' ' ' '} // ( ) /) // `-'\ , ) // | \ `~. / // \ `._ \ / // \ `._____,' ,' // `-. ,' // `-._ _,-' // 77jj' // //_|| // __//--'/` // ,--'/` ' // // [hjw] https://textart.io/art/vw6Sa3iwqIRGkZsN1BC2vweF/chicken } // File contracts/Misc_AMOs/vesper/IVPool.sol interface IVPool { function DOMAIN_SEPARATOR() external view returns (bytes32); function MAX_BPS() external view returns (uint256); function VERSION() external view returns (string memory); function acceptGovernorship() external; function addInList(address _listToUpdate, address _addressToAdd) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function availableCreditLimit(address _strategy) external view returns (uint256); function balanceOf(address account) external view returns (uint256); function convertFrom18(uint256 _amount) external view returns (uint256); function decimalConversionFactor() external view returns (uint256); function decimals() external view returns (uint8); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function deposit(uint256 _amount) external; function depositWithPermit(uint256 _amount, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s) external; function excessDebt(address _strategy) external view returns (uint256); function feeCollector() external view returns (address); function feeWhitelist() external view returns (address); function getStrategies() external view returns (address[] memory); function getWithdrawQueue() external view returns (address[] memory); function governor() external view returns (address); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function initialize(string memory _name, string memory _symbol, address _token, address _poolAccountant, address _addressListFactory) external; function keepers() external view returns (address); function maintainers() external view returns (address); function migrateStrategy(address _old, address _new) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function name() external view returns (string memory); function nonces(address) external view returns (uint256); function open() external; function pause() external; function paused() external view returns (bool); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function poolAccountant() external view returns (address); function poolRewards() external view returns (address); function pricePerShare() external view returns (uint256); function removeFromList(address _listToUpdate, address _addressToRemove) external; function reportEarning(uint256 _profit, uint256 _loss, uint256 _payback) external; function reportLoss(uint256 _loss) external; function shutdown() external; function stopEverything() external view returns (bool); function strategy(address _strategy) external view returns (bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio); function sweepERC20(address _fromToken) external; function symbol() external view returns (string memory); function token() external view returns (address); function tokensHere() external view returns (uint256); function totalDebt() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalDebtRatio() external view returns (uint256); function totalSupply() external view returns (uint256); function totalValue() external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transferGovernorship(address _proposedGovernor) external; function unpause() external; function updateFeeCollector(address _newFeeCollector) external; function updatePoolRewards(address _newPoolRewards) external; function updateWithdrawFee(uint256 _newWithdrawFee) external; function whitelistedWithdraw(uint256 _shares) external; function withdraw(uint256 _shares) external; function withdrawFee() external view returns (uint256); } // File contracts/Staking/FraxUnifiedFarm_ERC20.sol // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // ======================= FraxUnifiedFarm_ERC20 ====================== // ==================================================================== // For ERC20 Tokens // Uses FraxUnifiedFarmTemplate.sol // -------------------- VARIES -------------------- // G-UNI // import "../Misc_AMOs/gelato/IGUniPool.sol"; // mStable // import '../Misc_AMOs/mstable/IFeederPool.sol'; // // StakeDAO sdETH-FraxPut // import '../Misc_AMOs/stakedao/IOpynPerpVault.sol'; // StakeDAO Vault // import '../Misc_AMOs/stakedao/IStakeDaoVault.sol'; // Uniswap V2 // import '../Uniswap/Interfaces/IUniswapV2Pair.sol'; // Vesper // ------------------------------------------------ contract FraxUnifiedFarm_ERC20 is FraxUnifiedFarmTemplate { /* ========== STATE VARIABLES ========== */ // -------------------- VARIES -------------------- // G-UNI // IGUniPool public stakingToken; // mStable // IFeederPool public stakingToken; // sdETH-FraxPut Vault // IOpynPerpVault public stakingToken; // StakeDAO Vault // IStakeDaoVault public stakingToken; // Uniswap V2 // IUniswapV2Pair public stakingToken; // Vesper IVPool public stakingToken; // ------------------------------------------------ // Stake tracking mapping(address => LockedStake[]) public lockedStakes; /* ========== STRUCTS ========== */ // Struct for the stake struct LockedStake { bytes32 kek_id; uint256 start_timestamp; uint256 liquidity; uint256 ending_timestamp; uint256 lock_multiplier; // 6 decimals of precision. 1x = 1000000 } /* ========== CONSTRUCTOR ========== */ constructor ( address _owner, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRatesManual, address[] memory _gaugeControllers, address[] memory _rewardDistributors, address _stakingToken ) FraxUnifiedFarmTemplate(_owner, _rewardTokens, _rewardManagers, _rewardRatesManual, _gaugeControllers, _rewardDistributors) { // -------------------- VARIES -------------------- // G-UNI // stakingToken = IGUniPool(_stakingToken); // address token0 = address(stakingToken.token0()); // frax_is_token0 = token0 == frax_address; // mStable // stakingToken = IFeederPool(_stakingToken); // StakeDAO sdETH-FraxPut Vault // stakingToken = IOpynPerpVault(_stakingToken); // StakeDAO Vault // stakingToken = IStakeDaoVault(_stakingToken); // Uniswap V2 // stakingToken = IUniswapV2Pair(_stakingToken); // address token0 = stakingToken.token0(); // if (token0 == frax_address) frax_is_token0 = true; // else frax_is_token0 = false; // Vesper stakingToken = IVPool(_stakingToken); // address token0 = address(stakingToken.token0()); // frax_is_token0 = token0 == frax_address; // ------------------------------------------------ } /* ============= VIEWS ============= */ // ------ FRAX RELATED ------ function fraxPerLPToken() public view override returns (uint256) { // Get the amount of FRAX 'inside' of the lp tokens uint256 frax_per_lp_token; // G-UNI // ============================================ // { // (uint256 reserve0, uint256 reserve1) = stakingToken.getUnderlyingBalances(); // uint256 total_frax_reserves = frax_is_token0 ? reserve0 : reserve1; // frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply(); // } // mStable // ============================================ // { // uint256 total_frax_reserves; // (, IFeederPool.BassetData memory vaultData) = (stakingToken.getBasset(frax_address)); // total_frax_reserves = uint256(vaultData.vaultBalance); // frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply(); // } // StakeDAO sdETH-FraxPut Vault // ============================================ // { // uint256 frax3crv_held = stakingToken.totalUnderlyingControlled(); // // Optimistically assume 50/50 FRAX/3CRV ratio in the metapool to save gas // frax_per_lp_token = ((frax3crv_held * 1e18) / stakingToken.totalSupply()) / 2; // } // StakeDAO Vault // ============================================ // { // uint256 frax3crv_held = stakingToken.balance(); // // Optimistically assume 50/50 FRAX/3CRV ratio in the metapool to save gas // frax_per_lp_token = ((frax3crv_held * 1e18) / stakingToken.totalSupply()) / 2; // } // Uniswap V2 // ============================================ // { // uint256 total_frax_reserves; // (uint256 reserve0, uint256 reserve1, ) = (stakingToken.getReserves()); // if (frax_is_token0) total_frax_reserves = reserve0; // else total_frax_reserves = reserve1; // frax_per_lp_token = (total_frax_reserves * 1e18) / stakingToken.totalSupply(); // } // Vesper // ============================================ frax_per_lp_token = stakingToken.pricePerShare(); return frax_per_lp_token; } // ------ LIQUIDITY AND WEIGHTS ------ // Calculated the combined weight for an account function calcCurCombinedWeight(address account) public override view returns ( uint256 old_combined_weight, uint256 new_vefxs_multiplier, uint256 new_combined_weight ) { // Get the old combined weight old_combined_weight = _combined_weights[account]; // Get the veFXS multipliers // For the calculations, use the midpoint (analogous to midpoint Riemann sum) new_vefxs_multiplier = veFXSMultiplier(account); uint256 midpoint_vefxs_multiplier; if (_locked_liquidity[account] == 0 && _combined_weights[account] == 0) { // This is only called for the first stake to make sure the veFXS multiplier is not cut in half midpoint_vefxs_multiplier = new_vefxs_multiplier; } else { midpoint_vefxs_multiplier = (new_vefxs_multiplier + _vefxsMultiplierStored[account]) / 2; } // Loop through the locked stakes, first by getting the liquidity * lock_multiplier portion new_combined_weight = 0; for (uint256 i = 0; i < lockedStakes[account].length; i++) { LockedStake memory thisStake = lockedStakes[account][i]; uint256 lock_multiplier = thisStake.lock_multiplier; // If the lock is expired if (thisStake.ending_timestamp <= block.timestamp) { // If the lock expired in the time since the last claim, the weight needs to be proportionately averaged this time if (lastRewardClaimTime[account] < thisStake.ending_timestamp){ uint256 time_before_expiry = thisStake.ending_timestamp - lastRewardClaimTime[account]; uint256 time_after_expiry = block.timestamp - thisStake.ending_timestamp; // Get the weighted-average lock_multiplier uint256 numerator = (lock_multiplier * time_before_expiry) + (MULTIPLIER_PRECISION * time_after_expiry); lock_multiplier = numerator / (time_before_expiry + time_after_expiry); } // Otherwise, it needs to just be 1x else { lock_multiplier = MULTIPLIER_PRECISION; } } uint256 liquidity = thisStake.liquidity; uint256 combined_boosted_amount = (liquidity * (lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION; new_combined_weight = new_combined_weight + combined_boosted_amount; } } // ------ LOCK RELATED ------ // All the locked stakes for a given account function lockedStakesOf(address account) external view returns (LockedStake[] memory) { return lockedStakes[account]; } // Returns the length of the locked stakes for a given account function lockedStakesOfLength(address account) external view returns (uint256) { return lockedStakes[account].length; } // // All the locked stakes for a given account [old-school method] // function lockedStakesOfMultiArr(address account) external view returns ( // bytes32[] memory kek_ids, // uint256[] memory start_timestamps, // uint256[] memory liquidities, // uint256[] memory ending_timestamps, // uint256[] memory lock_multipliers // ) { // for (uint256 i = 0; i < lockedStakes[account].length; i++){ // LockedStake memory thisStake = lockedStakes[account][i]; // kek_ids[i] = thisStake.kek_id; // start_timestamps[i] = thisStake.start_timestamp; // liquidities[i] = thisStake.liquidity; // ending_timestamps[i] = thisStake.ending_timestamp; // lock_multipliers[i] = thisStake.lock_multiplier; // } // } /* =============== MUTATIVE FUNCTIONS =============== */ // ------ STAKING ------ function _getStake(address staker_address, bytes32 kek_id) internal view returns (LockedStake memory locked_stake, uint256 arr_idx) { for (uint256 i = 0; i < lockedStakes[staker_address].length; i++){ if (kek_id == lockedStakes[staker_address][i].kek_id){ locked_stake = lockedStakes[staker_address][i]; arr_idx = i; break; } } require(locked_stake.kek_id == kek_id, "Stake not found"); } // Add additional LPs to an existing locked stake function lockAdditional(bytes32 kek_id, uint256 addl_liq) updateRewardAndBalance(msg.sender, true) public { // Get the stake and its index (LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(msg.sender, kek_id); // Calculate the new amount uint256 new_amt = thisStake.liquidity + addl_liq; // Checks require(addl_liq >= 0, "Must be nonzero"); // Pull the tokens from the sender TransferHelper.safeTransferFrom(address(stakingToken), msg.sender, address(this), addl_liq); // Update the stake lockedStakes[msg.sender][theArrayIndex] = LockedStake( kek_id, thisStake.start_timestamp, new_amt, thisStake.ending_timestamp, thisStake.lock_multiplier ); // Update liquidities _total_liquidity_locked += addl_liq; _locked_liquidity[msg.sender] += addl_liq; // Need to call to update the combined weights _updateRewardAndBalance(msg.sender, false); } // Two different stake functions are needed because of delegateCall and msg.sender issues (important for migration) function stakeLocked(uint256 liquidity, uint256 secs) nonReentrant external { _stakeLocked(msg.sender, msg.sender, liquidity, secs, block.timestamp); } function _stakeLockedInternalLogic( address source_address, uint256 liquidity ) internal virtual { revert("Need _stakeLockedInternalLogic logic"); } // If this were not internal, and source_address had an infinite approve, this could be exploitable // (pull funds from source_address and stake for an arbitrary staker_address) function _stakeLocked( address staker_address, address source_address, uint256 liquidity, uint256 secs, uint256 start_timestamp ) internal updateRewardAndBalance(staker_address, true) { require(stakingPaused == false || valid_migrators[msg.sender] == true, "Staking paused or in migration"); require(greylist[staker_address] == false, "Address has been greylisted"); require(secs >= lock_time_min, "Minimum stake time not met"); require(secs <= lock_time_for_max_multiplier,"Trying to lock for too long"); // Pull in the required token(s) // Varies per farm TransferHelper.safeTransferFrom(address(stakingToken), source_address, address(this), liquidity); // Get the lock multiplier and kek_id uint256 lock_multiplier = lockMultiplier(secs); bytes32 kek_id = keccak256(abi.encodePacked(staker_address, start_timestamp, liquidity, _locked_liquidity[staker_address])); // Create the locked stake lockedStakes[staker_address].push(LockedStake( kek_id, start_timestamp, liquidity, start_timestamp + secs, lock_multiplier )); // Update liquidities _total_liquidity_locked += liquidity; _locked_liquidity[staker_address] += liquidity; // Need to call again to make sure everything is correct _updateRewardAndBalance(staker_address, false); emit StakeLocked(staker_address, liquidity, secs, kek_id, source_address); } // ------ WITHDRAWING ------ // Two different withdrawLocked functions are needed because of delegateCall and msg.sender issues (important for migration) function withdrawLocked(bytes32 kek_id, address destination_address) nonReentrant external { require(withdrawalsPaused == false, "Withdrawals paused"); _withdrawLocked(msg.sender, destination_address, kek_id); } // No withdrawer == msg.sender check needed since this is only internally callable and the checks are done in the wrapper // functions like migrator_withdraw_locked() and withdrawLocked() function _withdrawLocked( address staker_address, address destination_address, bytes32 kek_id ) internal { // Collect rewards first and then update the balances _getReward(staker_address, destination_address); // Get the stake and its index (LockedStake memory thisStake, uint256 theArrayIndex) = _getStake(staker_address, kek_id); require(block.timestamp >= thisStake.ending_timestamp || stakesUnlocked == true || valid_migrators[msg.sender] == true, "Stake is still locked!"); uint256 liquidity = thisStake.liquidity; if (liquidity > 0) { // Update liquidities _total_liquidity_locked = _total_liquidity_locked - liquidity; _locked_liquidity[staker_address] = _locked_liquidity[staker_address] - liquidity; // Remove the stake from the array delete lockedStakes[staker_address][theArrayIndex]; // Give the tokens to the destination_address // Should throw if insufficient balance stakingToken.transfer(destination_address, liquidity); // Need to call again to make sure everything is correct _updateRewardAndBalance(staker_address, false); emit WithdrawLocked(staker_address, liquidity, kek_id, destination_address); } } function _getRewardExtraLogic(address rewardee, address destination_address) internal override { // Do nothing } /* ========== RESTRICTED FUNCTIONS - Curator / migrator callable ========== */ // Migrator can stake for someone else (they won't be able to withdraw it back though, only staker_address can). function migrator_stakeLocked_for(address staker_address, uint256 amount, uint256 secs, uint256 start_timestamp) external isMigrating { require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); _stakeLocked(staker_address, msg.sender, amount, secs, start_timestamp); } // Used for migrations function migrator_withdraw_locked(address staker_address, bytes32 kek_id) external isMigrating { require(staker_allowed_migrators[staker_address][msg.sender] && valid_migrators[msg.sender], "Mig. invalid or unapproved"); _withdrawLocked(staker_address, msg.sender, kek_id); } /* ========== RESTRICTED FUNCTIONS - Owner or timelock only ========== */ // Inherited... /* ========== EVENTS ========== */ event StakeLocked(address indexed user, uint256 amount, uint256 secs, bytes32 kek_id, address source_address); event WithdrawLocked(address indexed user, uint256 liquidity, bytes32 kek_id, address destination_address); } // File contracts/Staking/Variants/FraxUnifiedFarm_ERC20_Vesper_Orbit_FRAX.sol contract FraxUnifiedFarm_ERC20_Vesper_Orbit_FRAX is FraxUnifiedFarm_ERC20 { constructor ( address _owner, address[] memory _rewardTokens, address[] memory _rewardManagers, uint256[] memory _rewardRates, address[] memory _gaugeControllers, address[] memory _rewardDistributors, address _stakingToken ) FraxUnifiedFarm_ERC20(_owner , _rewardTokens, _rewardManagers, _rewardRates, _gaugeControllers, _rewardDistributors, _stakingToken) {} }
Amount of reward tokens an account has earned / accrued Note: In the edge-case of one of the account's stake expiring since the last claim, this will return a slightly inflated number
function earned(address account) public view returns (uint256[] memory new_earned) { uint256[] memory reward_arr = rewardsPerToken(); new_earned = new uint256[](rewardTokens.length); if (_combined_weights[account] > 0){ for (uint256 i = 0; i < rewardTokens.length; i++){ new_earned[i] = ((_combined_weights[account] * (reward_arr[i] - userRewardsPerTokenPaid[account][i])) / 1e18) + rewards[account][i]; } }
193,418
/** *Submitted for verification at Etherscan.io on 2021-07-08 */ // Sources flattened with hardhat v2.4.0 https://hardhat.org // File contracts/external/polygon/lib/RLPReader.sol // Copied mostly from Polygon demo FxTunnel repo: https://github.com/jdkanani/fx-portal. // There are two modifications such that this contract compiles with Solidity v8: // - Line 86: cannot convert directly from uint256 --> address // - Line 226: cannot rely on wrapping arithmetic, must explicitly catch underflow/overflow with an unchecked{...} // statement // More details on Solidity v0.8.0 breaking changes here: // https://docs.soliditylang.org/en/v0.8.4/080-breaking-changes.html#new-restrictions pragma solidity ^0.8.0; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(uint160(toUint(item))); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint256 memPtr) private pure returns (uint256) { uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy( uint256 src, uint256 dest, uint256 len ) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } unchecked { // left over bytes. Mask is used to remove unwanted bytes from the word uint256 mask = 256**(WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } } // File contracts/external/polygon/lib/MerklePatriciaProof.sol // Copied with no modifications from Polygon demo FxTunnel repo: https://github.com/jdkanani/fx-portal // except bumping version from 0.7.3 --> 0.8 pragma solidity ^0.8.0; 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( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if (keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value)) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[nextPathNibble])); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse(RLPReader.toBytes(currentNodeList[0]), path, pathPtr); if (pathPtr + traversed == path.length) { //leaf node if (keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value)) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // 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 (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { 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); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1(n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10); } } // File contracts/external/polygon/lib/Merkle.sol // Copied with no modifications from Polygon demo FxTunnel repo: https://github.com/jdkanani/fx-portal // except bumping version from 0.7.3 --> 0.8 pragma solidity ^0.8.0; library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2**proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } index = index / 2; } return computedHash == rootHash; } } // File contracts/external/polygon/tunnel/FxBaseRootTunnel.sol // Copied with no modifications from Polygon demo FxTunnel repo: https://github.com/jdkanani/fx-portal // except bumping version from 0.7.3 --> 0.8 pragma solidity ^0.8.0; interface IFxStateSender { function sendMessageToChild(address _receiver, bytes calldata _data) external; } contract ICheckpointManager { struct HeaderBlock { bytes32 root; uint256 start; uint256 end; uint256 createdAt; address proposer; } /** * @notice mapping of checkpoint header numbers to block details * @dev These checkpoints are submited by plasma contracts */ mapping(uint256 => HeaderBlock) public headerBlocks; } abstract contract FxBaseRootTunnel { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; // keccak256(MessageSent(bytes)) bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036; // state sender contract IFxStateSender public fxRoot; // root chain manager ICheckpointManager public checkpointManager; // child tunnel contract which receives and sends messages address public fxChildTunnel; // storage to avoid duplicate exits mapping(bytes32 => bool) public processedExits; constructor(address _checkpointManager, address _fxRoot) { checkpointManager = ICheckpointManager(_checkpointManager); fxRoot = IFxStateSender(_fxRoot); } // set fxChildTunnel if not set already function setFxChildTunnel(address _fxChildTunnel) public { require(fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET"); fxChildTunnel = _fxChildTunnel; } /** * @notice Send bytes message to Child Tunnel * @param message bytes message that will be sent to Child Tunnel * some message examples - * abi.encode(tokenId); * abi.encode(tokenId, tokenMetadata); * abi.encode(messageType, messageData); */ function _sendMessageToChild(bytes memory message) internal { fxRoot.sendMessageToChild(fxChildTunnel, message); } function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) { RLPReader.RLPItem[] memory inputDataRLPList = inputData.toRlpItem().toList(); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( inputDataRLPList[2].toUint(), // blockNumber // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask inputDataRLPList[9].toUint() // receiptLogIndex ) ); require(processedExits[exitHash] == false, "FxRootTunnel: EXIT_ALREADY_PROCESSED"); processedExits[exitHash] = true; RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6].toBytes().toRlpItem().toList(); RLPReader.RLPItem memory logRLP = receiptRLPList[3].toList()[ inputDataRLPList[9].toUint() // receiptLogIndex ]; RLPReader.RLPItem[] memory logRLPList = logRLP.toList(); // check child tunnel require(fxChildTunnel == RLPReader.toAddress(logRLPList[0]), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL"); // verify receipt inclusion require( MerklePatriciaProof.verify( inputDataRLPList[6].toBytes(), // receipt inputDataRLPList[8].toBytes(), // branchMask inputDataRLPList[7].toBytes(), // receiptProof bytes32(inputDataRLPList[5].toUint()) // receiptRoot ), "FxRootTunnel: INVALID_RECEIPT_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( inputDataRLPList[2].toUint(), // blockNumber inputDataRLPList[3].toUint(), // blockTime bytes32(inputDataRLPList[4].toUint()), // txRoot bytes32(inputDataRLPList[5].toUint()), // receiptRoot inputDataRLPList[0].toUint(), // headerNumber inputDataRLPList[1].toBytes() // blockProof ); RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics require( bytes32(logTopicRLPList[0].toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig "FxRootTunnel: INVALID_SIGNATURE" ); // received message data bytes memory receivedData = logRLPList[2].toBytes(); bytes memory message = abi.decode(receivedData, (bytes)); // event decodes params again, so decoding bytes to get message return message; } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { (bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber); require( keccak256(abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)).checkMembership( blockNumber - startBlock, headerRoot, blockProof ), "FxRootTunnel: INVALID_HEADER" ); return createdAt; } /** * @notice receive message from L2 to L1, validated by proof * @dev This function verifies if the transaction actually happened on child chain * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function receiveMessage(bytes memory inputData) public virtual { bytes memory message = _validateAndExtractMessage(inputData); _processMessageFromChild(message); } /** * @notice Process message received from Child Tunnel * @dev function needs to be implemented to handle message as per requirement * This is called by onStateReceive function. * Since it is called via a system call, any event will not be emitted during its execution. * @param message bytes message that was sent from Child Tunnel */ function _processMessageFromChild(bytes memory message) internal virtual; } // File contracts/oracle/interfaces/FinderInterface.sol pragma solidity ^0.8.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // File contracts/oracle/implementation/Constants.sol pragma solidity ^0.8.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; bytes32 public constant Bridge = "Bridge"; bytes32 public constant GenericHandler = "GenericHandler"; } // File contracts/polygon/OracleBaseTunnel.sol pragma solidity ^0.8.0; /** * @notice Enforces lifecycle of price requests for deriving contract. */ abstract contract OracleBaseTunnel { enum RequestState { NeverRequested, Requested, Resolved } struct Price { RequestState state; int256 price; } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be resolved by the DVM which refuses // to accept a price request made with ancillary data length over a certain size. uint256 public constant ancillaryBytesLimit = 8192; // Mapping of encoded price requests {identifier, time, ancillaryData} to Price objects. mapping(bytes32 => Price) internal prices; // Finder to provide addresses for DVM system contracts. FinderInterface public finder; event PriceRequestAdded(bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes32 indexed requestHash); event PushedPrice( bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price, bytes32 indexed requestHash ); /** * @notice Constructor. * @param _finderAddress finder to use to get addresses of DVM contracts. */ constructor(address _finderAddress) { finder = FinderInterface(_finderAddress); } /** * @notice Enqueues a request (if a request isn't already present) for the given (identifier, time, * ancillary data) combination. Will only emit an event if the request has never been requested. */ function _requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) internal { require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; if (lookup.state == RequestState.NeverRequested) { lookup.state = RequestState.Requested; emit PriceRequestAdded(identifier, time, ancillaryData, priceRequestId); } } /** * @notice Publishes price for a requested query. Will only emit an event if the request has never been resolved. */ function _publishPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) internal { bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); Price storage lookup = prices[priceRequestId]; if (lookup.state == RequestState.Requested) { lookup.price = price; lookup.state = RequestState.Resolved; emit PushedPrice(identifier, time, ancillaryData, lookup.price, priceRequestId); } } /** * @notice Returns the convenient way to store price requests, uniquely identified by {identifier, time, * ancillaryData }. */ function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) internal pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } } // File contracts/oracle/interfaces/OracleAncillaryInterface.sol pragma solidity ^0.8.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // File contracts/common/implementation/Lockable.sol pragma solidity ^0.8.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() { // Storing an initial non-zero value makes deployment a bit more expensive, but in exchange the refund on every // call to nonReentrant will be lower in amount. Since refunds are capped to a 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. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` function is not supported. It is possible to * prevent this from happening by making the `nonReentrant` function external, and making it call a `private` * function that does the actual state modification. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being // re-entered. Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and // then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File contracts/polygon/OracleRootTunnel.sol pragma solidity ^0.8.0; /** * @title Adapter deployed on mainnet that validates and sends price requests from sidechain to the DVM on mainnet. * @dev This contract must be a registered financial contract in order to make DVM price requests. */ contract OracleRootTunnel is OracleBaseTunnel, FxBaseRootTunnel, Lockable { constructor( address _checkpointManager, address _fxRoot, address _finderAddress ) OracleBaseTunnel(_finderAddress) FxBaseRootTunnel(_checkpointManager, _fxRoot) {} /** * @notice This is the first method that should be called in order to publish a price request to the sidechain. * @dev Publishes the DVM resolved price for the price request, or reverts if not resolved yet. This contract must * be registered with the DVM to query price requests. * @param identifier Identifier of price request to resolve. * @param time Timestamp of price request to resolve. * @param ancillaryData extra data of price request to resolve. */ function publishPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public nonReentrant() { // `getPrice` will revert if there is no price. int256 price = _getOracle().getPrice(identifier, time, ancillaryData); // This implementation allows duplicate MessageSent events via _sendMessageToRoot. The child tunnel on the // sidechain will not have a problem handling duplicate price resolutions (it will just ignore them). This is // potentially a fallback in case the automatic state sync to the sidechain is missing the `publishPrice` // transaction for some reason. There is little risk in duplicating MessageSent emissions because the sidechain // bridge does not impose any rate-limiting. _publishPrice(identifier, time, ancillaryData, price); _sendMessageToChild(abi.encode(identifier, time, ancillaryData, price)); } /** * @notice Submits a price request. * @dev This internal method will be called inside `receiveMessage(bytes memory inputData)`. The `inputData` is a * proof of transaction that is derived from the transaction hash of the transaction on the child chain that * originated the cross-chain price request via _sendMessageToRoot. This contract must be registered with the DVM * to submit price requests. * @param data ABI encoded params with which to call `requestPrice`. */ function _processMessageFromChild(bytes memory data) internal override { (bytes32 identifier, uint256 time, bytes memory ancillaryData) = abi.decode(data, (bytes32, uint256, bytes)); _requestPrice(identifier, time, ancillaryData); _getOracle().requestPrice(identifier, time, ancillaryData); } /** * @notice Return DVM for this network. */ function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } }
return entire rlp item byte length
function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { itemLen := add(dataLen, add(byteLen, 1)) itemLen = byte0 - LIST_SHORT_START + 1; assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; }
2,025,997
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { TransferWithSigERC20 } from "../eip712/TransferWithSigERC20.sol"; contract sTSX is Ownable, TransferWithSigERC20 { // Token details string public constant NAME = "TradeStars sTSX"; string public constant SYMBOL = "sTSX"; // allowed address to manage the supply for this token address public minter; modifier onlyMinter() { require(msg.sender == minter, "sTSX: caller is not minter"); _; } constructor() Ownable() ERC20(NAME, SYMBOL) public { } /** * @dev Sets the minter role for this contract * @param _minter address */ function setMinterAddress(address _minter) public onlyOwner { minter = _minter; } /** * @dev Sets approval amount for an operator to spend on token owner's behalf * @param _owner of the tokens * @param _operator spender address * @param _amount max amount of tokens allowed to spend */ function approveOperator( address _owner, address _operator, uint256 _amount ) public onlyOwner { _approve(_owner, _operator, _amount); } /** * @dev Mints a specific amount of tokens. * @param _to address to send new tokens to. * @param _amount of token to be minted. */ function mint(address _to, uint256 _amount) external onlyMinter { _mint(_to, _amount); } /** * @dev Destroys `amount` tokens from the caller. * @param _amount of token to be burned. */ function burn(uint256 _amount) external onlyMinter { _burn(msg.sender, _amount); } }
Sets the minter role for this contract _minter address/
function setMinterAddress(address _minter) public onlyOwner { minter = _minter; }
5,448,454
pragma solidity ^0.4.24; 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); } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title TMTGOwnable * * @dev Due to ownable change in zeppelin, the authorities in TMTGOwnable include hiddenOwner, * superOwner, owner, centerBanker, and operator. * Each authority has different roles. */ contract TMTGOwnable { address public owner; address public centralBanker; address public superOwner; address public hiddenOwner; enum Role { owner, centralBanker, superOwner, hiddenOwner } mapping(address => bool) public operators; event TMTG_RoleTransferred( Role indexed ownerType, address indexed previousOwner, address indexed newOwner ); event TMTG_SetOperator(address indexed operator); event TMTG_DeletedOperator(address indexed operator); modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyOwnerOrOperator() { require(msg.sender == owner || operators[msg.sender]); _; } modifier onlyNotBankOwner(){ require(msg.sender != centralBanker); _; } modifier onlyBankOwner(){ require(msg.sender == centralBanker); _; } modifier onlySuperOwner() { require(msg.sender == superOwner); _; } modifier onlyhiddenOwner(){ require(msg.sender == hiddenOwner); _; } constructor() public { owner = msg.sender; centralBanker = msg.sender; superOwner = msg.sender; hiddenOwner = msg.sender; } /** * @dev Set the address to operator * @param _operator has the ability to pause transaction, has the ability to blacklisting & unblacklisting. */ function setOperator(address _operator) external onlySuperOwner { operators[_operator] = true; emit TMTG_SetOperator(_operator); } /** * @dev Remove the address from operator * @param _operator has the ability to pause transaction, has the ability to blacklisting & unblacklisting. */ function delOperator(address _operator) external onlySuperOwner { operators[_operator] = false; emit TMTG_DeletedOperator(_operator); } /** * @dev It is possible to hand over owner’s authority. Only superowner is available. * @param newOwner */ function transferOwnership(address newOwner) public onlySuperOwner { emit TMTG_RoleTransferred(Role.owner, owner, newOwner); owner = newOwner; } /** * @dev It is possible to hand over centerBanker’s authority. Only superowner is available. * @param newBanker centerBanker is a kind of a central bank, transaction is impossible. * The amount of money to deposit is determined in accordance with cash reserve ratio and the amount of currency in circulation * To withdraw money out of a wallet and give it to owner, audit is inevitable */ function transferBankOwnership(address newBanker) public onlySuperOwner { emit TMTG_RoleTransferred(Role.centralBanker, centralBanker, newBanker); centralBanker = newBanker; } /** * @dev It is possible to hand over superOwner’s authority. Only hiddenowner is available. * @param newSuperOwner SuperOwner manages all authorities except for hiddenOwner and superOwner */ function transferSuperOwnership(address newSuperOwner) public onlyhiddenOwner { emit TMTG_RoleTransferred(Role.superOwner, superOwner, newSuperOwner); superOwner = newSuperOwner; } /** * @dev It is possible to hand over hiddenOwner’s authority. Only hiddenowner is available * @param newhiddenOwner NewhiddenOwner and hiddenOwner don’t have many functions, * but they can set and remove authorities of superOwner and hiddenOwner. */ function changeHiddenOwner(address newhiddenOwner) public onlyhiddenOwner { emit TMTG_RoleTransferred(Role.hiddenOwner, hiddenOwner, newhiddenOwner); hiddenOwner = newhiddenOwner; } } /** * @title TMTGPausable * * @dev It is used to stop trading in emergency situation */ contract TMTGPausable is TMTGOwnable { event TMTG_Pause(); event TMTG_Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } /** * @dev Block trading. Only owner and operator are available. */ function pause() onlyOwnerOrOperator whenNotPaused public { paused = true; emit TMTG_Pause(); } /** * @dev Unlock limit for trading. Owner and operator are available and this function can be operated in paused mode. */ function unpause() onlyOwnerOrOperator whenPaused public { paused = false; emit TMTG_Unpause(); } } /** * @title TMTGBlacklist * * @dev Block trading of the suspicious account address. */ contract TMTGBlacklist is TMTGOwnable { mapping(address => bool) blacklisted; event TMTG_Blacklisted(address indexed blacklist); event TMTG_Whitelisted(address indexed whitelist); modifier whenPermitted(address node) { require(!blacklisted[node]); _; } /** * @dev Check a certain node is in a blacklist * @param node Check whether the user at a certain node is in a blacklist */ function isPermitted(address node) public view returns (bool) { return !blacklisted[node]; } /** * @dev Process blacklisting * @param node Process blacklisting. Put the user in the blacklist. */ function blacklist(address node) public onlyOwnerOrOperator { blacklisted[node] = true; emit TMTG_Blacklisted(node); } /** * @dev Process unBlacklisting. * @param node Remove the user from the blacklist. */ function unblacklist(address node) public onlyOwnerOrOperator { blacklisted[node] = false; emit TMTG_Whitelisted(node); } } /** * @title HasNoEther */ contract HasNoEther is TMTGOwnable { /** * @dev Constructor that rejects incoming Ether * The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } } /** * @title TMTGBaseToken - Major functions such as authority setting on tockenlock are registered. */ contract TMTGBaseToken is StandardToken, TMTGPausable, TMTGBlacklist, HasNoEther { uint256 public openingTime; struct investor { uint256 _sentAmount; uint256 _initialAmount; uint256 _limit; } mapping(address => investor) public searchInvestor; mapping(address => bool) public superInvestor; mapping(address => bool) public CEx; mapping(address => bool) public investorList; event TMTG_SetCEx(address indexed CEx); event TMTG_DeleteCEx(address indexed CEx); event TMTG_SetSuperInvestor(address indexed SuperInvestor); event TMTG_DeleteSuperInvestor(address indexed SuperInvestor); event TMTG_SetInvestor(address indexed investor); event TMTG_DeleteInvestor(address indexed investor); event TMTG_Stash(uint256 _value); event TMTG_Unstash(uint256 _value); event TMTG_TransferFrom(address indexed owner, address indexed spender, address indexed to, uint256 value); event TMTG_Burn(address indexed burner, uint256 value); /** * @dev Register the address as a cex address * @param _CEx Register the address as a cex address */ function setCEx(address _CEx) external onlySuperOwner { CEx[_CEx] = true; emit TMTG_SetCEx(_CEx); } /** * @dev Remove authorities of the address used in Exchange * @param _CEx Remove authorities of the address used in Exchange */ function delCEx(address _CEx) external onlySuperOwner { CEx[_CEx] = false; emit TMTG_DeleteCEx(_CEx); } /** * @dev Register the address as a superinvestor address * @param _super Register the address as a superinvestor address */ function setSuperInvestor(address _super) external onlySuperOwner { superInvestor[_super] = true; emit TMTG_SetSuperInvestor(_super); } /** * @param _super Remove authorities of the address as a superinvestor */ function delSuperInvestor(address _super) external onlySuperOwner { superInvestor[_super] = false; emit TMTG_DeleteSuperInvestor(_super); } /** * @param _addr Remove authorities of the address as a investor . */ function delInvestor(address _addr) onlySuperOwner public { investorList[_addr] = false; searchInvestor[_addr] = investor(0,0,0); emit TMTG_DeleteInvestor(_addr); } function setOpeningTime() onlyOwner public returns(bool) { openingTime = block.timestamp; } /** * @dev After one month, the amount will be 1, which means 10% of the coins can be used. * After 7 months, 70% of the amount can be used. */ function getLimitPeriod() external view returns (uint256) { uint256 presentTime = block.timestamp; uint256 timeValue = presentTime.sub(openingTime); uint256 result = timeValue.div(31 days); return result; } /** * @dev Check the latest limit * @param who Check the latest limit. * Return the limit value of the user at the present moment. After 3 months, _result value will be 30% of initialAmount */ function _timelimitCal(address who) internal view returns (uint256) { uint256 presentTime = block.timestamp; uint256 timeValue = presentTime.sub(openingTime); uint256 _result = timeValue.div(31 days); return _result.mul(searchInvestor[who]._limit); } /** * @dev In case of investor transfer, values will be limited by timelock * @param _to address to send * @param _value tmtg's amount */ function _transferInvestor(address _to, uint256 _value) internal returns (bool ret) { uint256 addedValue = searchInvestor[msg.sender]._sentAmount.add(_value); require(_timelimitCal(msg.sender) >= addedValue); searchInvestor[msg.sender]._sentAmount = addedValue; ret = super.transfer(_to, _value); if (!ret) { searchInvestor[msg.sender]._sentAmount = searchInvestor[msg.sender]._sentAmount.sub(_value); } } /** * @dev When the transfer function is run, * there are two different types; transfer from superinvestors to investor and to non-investors. * In the latter case, the non-investors will be investor and 10% of the initial amount will be allocated. * And when investor operates the transfer function, the values will be limited by timelock. * @param _to address to send * @param _value tmtg's amount */ function transfer(address _to, uint256 _value) public whenPermitted(msg.sender) whenPermitted(_to) whenNotPaused onlyNotBankOwner returns (bool) { if(investorList[msg.sender]) { return _transferInvestor(_to, _value); } else { if (superInvestor[msg.sender]) { require(_to != owner); require(!superInvestor[_to]); require(!CEx[_to]); if(!investorList[_to]){ investorList[_to] = true; searchInvestor[_to] = investor(0, _value, _value.div(10)); emit TMTG_SetInvestor(_to); } } return super.transfer(_to, _value); } } /** * @dev If investor is from in transforFrom, values will be limited by timelock * @param _from send amount from this address * @param _to address to send * @param _value tmtg's amount */ function _transferFromInvestor(address _from, address _to, uint256 _value) public returns(bool ret) { uint256 addedValue = searchInvestor[_from]._sentAmount.add(_value); require(_timelimitCal(_from) >= addedValue); searchInvestor[_from]._sentAmount = addedValue; ret = super.transferFrom(_from, _to, _value); if (!ret) { searchInvestor[_from]._sentAmount = searchInvestor[_from]._sentAmount.sub(_value); }else { emit TMTG_TransferFrom(_from, msg.sender, _to, _value); } } /** * @dev If from is superinvestor in transforFrom, the function can’t be used because of limit in Approve. * And if from is investor, the amount of coins to send is limited by timelock. * @param _from send amount from this address * @param _to address to send * @param _value tmtg's amount */ function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused whenPermitted(_from) whenPermitted(_to) whenPermitted(msg.sender) returns (bool ret) { if(investorList[_from]) { return _transferFromInvestor(_from, _to, _value); } else { ret = super.transferFrom(_from, _to, _value); emit TMTG_TransferFrom(_from, msg.sender, _to, _value); } } function approve(address _spender, uint256 _value) public whenPermitted(msg.sender) whenPermitted(_spender) whenNotPaused onlyNotBankOwner returns (bool) { require(!superInvestor[msg.sender]); return super.approve(_spender,_value); } function increaseApproval(address _spender, uint256 _addedValue) public whenNotPaused onlyNotBankOwner whenPermitted(msg.sender) whenPermitted(_spender) returns (bool) { require(!superInvestor[msg.sender]); return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint256 _subtractedValue) public whenNotPaused onlyNotBankOwner whenPermitted(msg.sender) whenPermitted(_spender) returns (bool) { require(!superInvestor[msg.sender]); return super.decreaseApproval(_spender, _subtractedValue); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Transfer(_who, address(0), _value); emit TMTG_Burn(_who, _value); } function burn(uint256 _value) onlyOwner public returns (bool) { _burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) onlyOwner public returns (bool) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); return true; } /** * @dev onlyOwner is available and the amount of coins can be deposited in centerBanker. * @param _value tmtg's amount */ function stash(uint256 _value) public onlyOwner { require(balances[owner] >= _value); balances[owner] = balances[owner].sub(_value); balances[centralBanker] = balances[centralBanker].add(_value); emit TMTG_Stash(_value); } /** * @dev Only centerBanker is available and withdrawal of the amount of coins to owner is possible. But audit is inevitable. * @param _value tmtg's amount */ function unstash(uint256 _value) public onlyBankOwner { require(balances[centralBanker] >= _value); balances[centralBanker] = balances[centralBanker].sub(_value); balances[owner] = balances[owner].add(_value); emit TMTG_Unstash(_value); } function reclaimToken() external onlyOwner { transfer(owner, balanceOf(this)); } function destory() onlyhiddenOwner public { selfdestruct(superOwner); } /** * @dev When investors buy additional coins in Exchange, the amount will require tockenlock for 10 months. In this case, it is possible to move the amount in the presence of owner. * @param _investor * @param _to * @param _amount */ function refreshInvestor(address _investor, address _to, uint _amount) onlyOwner public { require(investorList[_investor]); require(_to != address(0)); require(_amount <= balances[_investor]); balances[_investor] = balances[_investor].sub(_amount); balances[_to] = balances[_to].add(_amount); } } contract TMTG is TMTGBaseToken { string public constant name = "The Midas Touch Gold"; string public constant symbol = "TMTG"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 1e10 * (10 ** uint256(decimals)); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; openingTime = block.timestamp; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } }
Unlock limit for trading. Owner and operator are available and this function can be operated in paused mode./
function unpause() onlyOwnerOrOperator whenPaused public { paused = false; emit TMTG_Unpause(); }
558,679
./full_match/1/0x70996FeE3bc1BA38e36Ea356aee5d855161e6e52/sources/contracts/ChainPortal.sol
chainSelectors Array of chain selectors. portals Array of portal addresses corresponding to each chain selector in the chainSelectors array. The chainSelectors and portals arrays must have the same length./
function _setChainPortals(uint64[] calldata chainSelectors, address[] calldata portals) internal { if (chainSelectors.length != portals.length) { revert ChainPortal__ArrayLengthMismatch(); } for (uint256 i; i < chainSelectors.length;) { if(!IRouterClient(i_router).isChainSupported(chainSelectors[i])){ revert IRouterClient.UnsupportedDestinationChain(chainSelectors[i]); } s_chainPortal[chainSelectors[i]] = portals[i]; unchecked { ++i; } } emit ChainPortalsChanged(chainSelectors, portals); }
16,577,516
pragma solidity ^0.8.0; import "../token/ERC20/utils/SafeERC20.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /* Modification of PaymentSplitter so that shares is given by an overridable function instead of a private variable. This way, the shares can be retrieved from an external source, e.g. an ERC20 contract such as this: IERC20 token; function getShares(address account) public view override returns (uint256) { return token.balanceOf(account); } function getTotalShares() public view override returns (uint256) { return token.totalShares(); } */ /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitterOverrideShares is Context { event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalReleased; mapping(address => uint256) private _released; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor() payable { } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function getTotalShares() virtual public view returns (uint256) { //return getTotalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function getShares(address account) virtual public view returns (uint256) { // return getShares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } function release(address payable account) public { require(getShares(account) > 0, "PaymentSplitter: account has no shares"); uint256 payment = pendingPaymentEth(account); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public { require(getShares(account) > 0, "PaymentSplitter: account has no shares"); uint256 payment = pendingPaymentToken(account, token); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /* * @dev now-public function computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function pendingPaymentEth(address account) public view returns (uint256) { uint256 totalReceived = address(this).balance + totalReleased(); uint256 totalOwed_ = (totalReceived * getShares(account)) / getTotalShares(); uint256 totalReleased_ = released(account); if (totalReleased_ > totalOwed_) { return 0; } else { return totalOwed_ - totalReleased_; } } /** * @dev now-public function computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function pendingPaymentToken(address account, IERC20 token) public view returns (uint256) { uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 totalOwed_ = (totalReceived * getShares(account)) / getTotalShares(); uint256 totalReleased_ = released(token, account); if (totalReleased_ > totalOwed_) { return 0; } else { return totalOwed_ - totalReleased_; } } }
now-public function computing the pending payment of an `account` given the token historical balances and already released amounts./
function pendingPaymentEth(address account) public view returns (uint256) { uint256 totalReceived = address(this).balance + totalReleased(); uint256 totalOwed_ = (totalReceived * getShares(account)) / getTotalShares(); uint256 totalReleased_ = released(account); if (totalReleased_ > totalOwed_) { return 0; return totalOwed_ - totalReleased_; } }
975,230
pragma solidity 0.5.15; contract IAugur { function CREATECHILDUNIVERSE712(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function ISKNOWNUNIVERSE698(IUniverse _universe) public view returns (bool); //inject NONSTANDARD NAMING function TRUSTEDCASHTRANSFER967(address _from, address _to, uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function ISTRUSTEDSENDER635(address _address) public returns (bool); //inject NONSTANDARD NAMING function ONCATEGORICALMARKETCREATED679(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); //inject NONSTANDARD NAMING function ONYESNOMARKETCREATED215(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); //inject NONSTANDARD NAMING function ONSCALARMARKETCREATED844(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTSUBMITTED874(IUniverse _universe, address _reporter, address _market, address _initialReporter, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); //inject NONSTANDARD NAMING function DISPUTECROWDSOURCERCREATED646(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCONTRIBUTION255(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERCOMPLETED546(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERREDEEMED338(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERREDEEMED9(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETFINALIZED368(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETMIGRATED444(IMarket _market, IUniverse _originalUniverse) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGPARTICIPANTDISAVOWED43(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETPARTICIPANTSDISAVOWED537(IUniverse _universe) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSPURCHASED486(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); //inject NONSTANDARD NAMING function LOGCOMPLETESETSSOLD144(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETOICHANGED928(IUniverse _universe, IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function LOGTRADINGPROCEEDSCLAIMED757(IUniverse _universe, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _fees) public returns (bool); //inject NONSTANDARD NAMING function LOGUNIVERSEFORKED116(IMarket _forkingMarket) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSTRANSFERRED904(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSBURNED995(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGREPUTATIONTOKENSMINTED985(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGSHARETOKENSBALANCECHANGED123(address _account, IMarket _market, uint256 _outcome, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSTRANSFERRED932(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSBURNED518(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTECROWDSOURCERTOKENSMINTED48(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGDISPUTEWINDOWCREATED79(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSREDEEMED534(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); //inject NONSTANDARD NAMING function LOGTIMESTAMPSET762(uint256 _newTimestamp) public returns (bool); //inject NONSTANDARD NAMING function LOGINITIALREPORTERTRANSFERRED573(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETTRANSFERRED247(IUniverse _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSTRANSFERRED386(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSBURNED957(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGPARTICIPATIONTOKENSMINTED248(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETREPBONDTRANSFERRED31(address _universe, address _from, address _to) public returns (bool); //inject NONSTANDARD NAMING function LOGWARPSYNCDATAUPDATED845(address _universe, uint256 _warpSyncHash, uint256 _marketEndTime) public returns (bool); //inject NONSTANDARD NAMING function ISKNOWNFEESENDER211(address _feeSender) public view returns (bool); //inject NONSTANDARD NAMING function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function GETTIMESTAMP626() public view returns (uint256); //inject NONSTANDARD NAMING function GETMAXIMUMMARKETENDDATE626() public returns (uint256); //inject NONSTANDARD NAMING function ISKNOWNMARKET166(IMarket _market) public view returns (bool); //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); //inject NONSTANDARD NAMING function LOGVALIDITYBONDCHANGED992(uint256 _validityBond) public returns (bool); //inject NONSTANDARD NAMING function LOGDESIGNATEDREPORTSTAKECHANGED748(uint256 _designatedReportStake) public returns (bool); //inject NONSTANDARD NAMING function LOGNOSHOWBONDCHANGED254(uint256 _noShowBond) public returns (bool); //inject NONSTANDARD NAMING function LOGREPORTINGFEECHANGED596(uint256 _reportingFee) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSEFORKINDEX548(IUniverse _universe) public view returns (uint256); //inject NONSTANDARD NAMING } contract IOwnable { function GETOWNER826() public view returns (address); //inject NONSTANDARD NAMING function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool); //inject NONSTANDARD NAMING } contract ITyped { function GETTYPENAME153() public view returns (bytes32); //inject NONSTANDARD NAMING } library SafeMathUint256 { function MUL760(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV647(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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 SUB692(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); return a - b; } function ADD571(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MIN885(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a <= b) { return a; } else { return b; } } function MAX990(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a >= b) { return a; } else { return b; } } function SQRT858(uint256 y) internal pure returns (uint256 z) { //inject NONSTANDARD NAMING if (y > 3) { uint256 x = (y + 1) / 2; z = y; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function GETUINT256MIN331() internal pure returns (uint256) { //inject NONSTANDARD NAMING return 0; } function GETUINT256MAX467() internal pure returns (uint256) { //inject NONSTANDARD NAMING // 2 ** 256 - 1 return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function ISMULTIPLEOF540(uint256 a, uint256 b) internal pure returns (bool) { //inject NONSTANDARD NAMING return a % b == 0; } // Float [fixed point] Operations function FXPMUL102(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, b), base); } function FXPDIV922(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV647(MUL760(a, base), b); } } interface IERC1155 { event TRANSFERSINGLE49( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TRANSFERBATCH882( //inject NONSTANDARD NAMING address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event APPROVALFORALL731( //inject NONSTANDARD NAMING address indexed owner, address indexed operator, bool approved ); event URI998( //inject NONSTANDARD NAMING string value, uint256 indexed id ); function SAFETRANSFERFROM689( //inject NONSTANDARD NAMING address from, address to, uint256 id, uint256 value, bytes calldata data ) external; function SAFEBATCHTRANSFERFROM779( //inject NONSTANDARD NAMING address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external; function SETAPPROVALFORALL494(address operator, bool approved) external; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL901(address owner, address operator) external view returns (bool); //inject NONSTANDARD NAMING function BALANCEOF492(address owner, uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY304(uint256 id) external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFBATCH918( //inject NONSTANDARD NAMING address[] calldata owners, uint256[] calldata ids ) external view returns (uint256[] memory balances_); } contract IERC20 { function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint256 amount) public returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING // solhint-disable-next-line no-simple-event-func-name event TRANSFER723(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL665(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ICash is IERC20 { } contract ERC20 is IERC20 { using SafeMathUint256 for uint256; uint8 constant public decimals866 = 18; //inject NONSTANDARD NAMING uint256 public totalSupply; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowances; function BALANCEOF492(address _account) public view returns (uint256) { //inject NONSTANDARD NAMING return balances[_account]; } function TRANSFER644(address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(msg.sender, _recipient, _amount); return true; } function ALLOWANCE377(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING return allowances[_owner][_spender]; } function APPROVE293(address _spender, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, _amount); return true; } function TRANSFERFROM669(address _sender, address _recipient, uint256 _amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER433(_sender, _recipient, _amount); _APPROVE571(_sender, msg.sender, allowances[_sender][msg.sender].SUB692(_amount)); return true; } function INCREASEALLOWANCE307(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].ADD571(_addedValue)); return true; } function DECREASEALLOWANCE757(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE571(msg.sender, _spender, allowances[msg.sender][_spender].SUB692(_subtractedValue)); return true; } function _TRANSFER433(address _sender, address _recipient, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); balances[_sender] = balances[_sender].SUB692(_amount); balances[_recipient] = balances[_recipient].ADD571(_amount); emit TRANSFER723(_sender, _recipient, _amount); ONTOKENTRANSFER292(_sender, _recipient, _amount); } function _MINT880(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.ADD571(_amount); balances[_account] = balances[_account].ADD571(_amount); emit TRANSFER723(address(0), _account, _amount); } function _BURN356(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_account != address(0), "ERC20: burn from the zero address"); balances[_account] = balances[_account].SUB692(_amount); totalSupply = totalSupply.SUB692(_amount); emit TRANSFER723(_account, address(0), _amount); } function _APPROVE571(address _owner, address _spender, uint256 _amount) internal { //inject NONSTANDARD NAMING require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); allowances[_owner][_spender] = _amount; emit APPROVAL665(_owner, _spender, _amount); } function _BURNFROM317(address _account, uint256 _amount) internal { //inject NONSTANDARD NAMING _BURN356(_account, _amount); _APPROVE571(_account, msg.sender, allowances[_account][msg.sender].SUB692(_amount)); } // Subclasses of this token generally want to send additional logs through the centralized Augur log emitter contract function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal; //inject NONSTANDARD NAMING } contract VariableSupplyToken is ERC20 { using SafeMathUint256 for uint256; function MINT146(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _MINT880(_target, _amount); ONMINT315(_target, _amount); return true; } function BURN234(address _target, uint256 _amount) internal returns (bool) { //inject NONSTANDARD NAMING _BURN356(_target, _amount); ONBURN653(_target, _amount); return true; } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONMINT315(address, uint256) internal { //inject NONSTANDARD NAMING } // Subclasses of this token may want to send additional logs through the centralized Augur log emitter contract function ONBURN653(address, uint256) internal { //inject NONSTANDARD NAMING } } contract IAffiliateValidator { function VALIDATEREFERENCE609(address _account, address _referrer) external view returns (bool); //inject NONSTANDARD NAMING } contract IDisputeWindow is ITyped, IERC20 { function INVALIDMARKETSTOTAL511() external view returns (uint256); //inject NONSTANDARD NAMING function VALIDITYBONDTOTAL28() external view returns (uint256); //inject NONSTANDARD NAMING function INCORRECTDESIGNATEDREPORTTOTAL522() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALREPORTBONDTOTAL695() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTNOSHOWSTOTAL443() external view returns (uint256); //inject NONSTANDARD NAMING function DESIGNATEDREPORTERNOSHOWBONDTOTAL703() external view returns (uint256); //inject NONSTANDARD NAMING function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime) public; //inject NONSTANDARD NAMING function TRUSTEDBUY954(address _buyer, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IReputationToken); //inject NONSTANDARD NAMING function GETSTARTTIME383() public view returns (uint256); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINDOWID901() public view returns (uint256); //inject NONSTANDARD NAMING function ISACTIVE720() public view returns (bool); //inject NONSTANDARD NAMING function ISOVER108() public view returns (bool); //inject NONSTANDARD NAMING function ONMARKETFINALIZED596() public; //inject NONSTANDARD NAMING function REDEEM559(address _account) public returns (bool); //inject NONSTANDARD NAMING } contract IMarket is IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function INITIALIZE90(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function DERIVEPAYOUTDISTRIBUTIONHASH812(uint256[] memory _payoutNumerators) public view returns (bytes32); //inject NONSTANDARD NAMING function DOINITIALREPORT448(uint256[] memory _payoutNumerators, string memory _description, uint256 _additionalStake) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETDISPUTEWINDOW804() public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETNUMBEROFOUTCOMES636() public view returns (uint256); //inject NONSTANDARD NAMING function GETNUMTICKS752() public view returns (uint256); //inject NONSTANDARD NAMING function GETMARKETCREATORSETTLEMENTFEEDIVISOR51() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket _market); //inject NONSTANDARD NAMING function GETENDTIME626() public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTDISTRIBUTIONHASH916() public view returns (bytes32); //inject NONSTANDARD NAMING function GETWINNINGPAYOUTNUMERATOR375(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGREPORTINGPARTICIPANT424() public view returns (IReportingParticipant); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFINALIZATIONTIME347() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTER212() public view returns (IInitialReporter); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGENDTIME834() public view returns (uint256); //inject NONSTANDARD NAMING function GETVALIDITYBONDATTOCASH123() public view returns (uint256); //inject NONSTANDARD NAMING function AFFILIATEFEEDIVISOR322() external view returns (uint256); //inject NONSTANDARD NAMING function GETNUMPARTICIPANTS137() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTEPACINGON415() public view returns (bool); //inject NONSTANDARD NAMING function DERIVEMARKETCREATORFEEAMOUNT558(uint256 _amount) public view returns (uint256); //inject NONSTANDARD NAMING function RECORDMARKETCREATORFEES738(uint256 _marketCreatorFees, address _sourceAccount, bytes32 _fingerprint) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function ISFINALIZEDASINVALID362() public view returns (bool); //inject NONSTANDARD NAMING function FINALIZE310() public returns (bool); //inject NONSTANDARD NAMING function ISFINALIZED623() public view returns (bool); //inject NONSTANDARD NAMING function GETOPENINTEREST251() public view returns (uint256); //inject NONSTANDARD NAMING } contract IReportingParticipant { function GETSTAKE932() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTDISTRIBUTIONHASH1000() public view returns (bytes32); //inject NONSTANDARD NAMING function LIQUIDATELOSING232() public; //inject NONSTANDARD NAMING function REDEEM559(address _redeemer) public returns (bool); //inject NONSTANDARD NAMING function ISDISAVOWED173() public view returns (bool); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETMARKET927() public view returns (IMarket); //inject NONSTANDARD NAMING function GETSIZE85() public view returns (uint256); //inject NONSTANDARD NAMING } contract IDisputeCrowdsourcer is IReportingParticipant, IERC20 { function INITIALIZE90(IAugur _augur, IMarket market, uint256 _size, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _crowdsourcerGeneration) public; //inject NONSTANDARD NAMING function CONTRIBUTE720(address _participant, uint256 _amount, bool _overload) public returns (uint256); //inject NONSTANDARD NAMING function SETSIZE177(uint256 _size) public; //inject NONSTANDARD NAMING function GETREMAININGTOFILL115() public view returns (uint256); //inject NONSTANDARD NAMING function CORRECTSIZE807() public returns (bool); //inject NONSTANDARD NAMING function GETCROWDSOURCERGENERATION652() public view returns (uint256); //inject NONSTANDARD NAMING } contract IInitialReporter is IReportingParticipant, IOwnable { function INITIALIZE90(IAugur _augur, IMarket _market, address _designatedReporter) public; //inject NONSTANDARD NAMING function REPORT291(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; //inject NONSTANDARD NAMING function DESIGNATEDREPORTERSHOWED809() public view returns (bool); //inject NONSTANDARD NAMING function INITIALREPORTERWASCORRECT338() public view returns (bool); //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTER404() public view returns (address); //inject NONSTANDARD NAMING function GETREPORTTIMESTAMP304() public view returns (uint256); //inject NONSTANDARD NAMING function MIGRATETONEWUNIVERSE701(address _designatedReporter) public; //inject NONSTANDARD NAMING function RETURNREPFROMDISAVOW512() public; //inject NONSTANDARD NAMING } contract IReputationToken is IERC20 { function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool); //inject NONSTANDARD NAMING function GETUNIVERSE719() public view returns (IUniverse); //inject NONSTANDARD NAMING function GETTOTALMIGRATED220() public view returns (uint256); //inject NONSTANDARD NAMING function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256); //inject NONSTANDARD NAMING function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool); //inject NONSTANDARD NAMING } contract IShareToken is ITyped, IERC1155 { function INITIALIZE90(IAugur _augur) external; //inject NONSTANDARD NAMING function INITIALIZEMARKET720(IMarket _market, uint256 _numOutcomes, uint256 _numTicks) public; //inject NONSTANDARD NAMING function UNSAFETRANSFERFROM654(address _from, address _to, uint256 _id, uint256 _value) public; //inject NONSTANDARD NAMING function UNSAFEBATCHTRANSFERFROM211(address _from, address _to, uint256[] memory _ids, uint256[] memory _values) public; //inject NONSTANDARD NAMING function CLAIMTRADINGPROCEEDS854(IMarket _market, address _shareHolder, bytes32 _fingerprint) external returns (uint256[] memory _outcomeFees); //inject NONSTANDARD NAMING function GETMARKET927(uint256 _tokenId) external view returns (IMarket); //inject NONSTANDARD NAMING function GETOUTCOME167(uint256 _tokenId) external view returns (uint256); //inject NONSTANDARD NAMING function GETTOKENID371(IMarket _market, uint256 _outcome) public pure returns (uint256 _tokenId); //inject NONSTANDARD NAMING function GETTOKENIDS530(IMarket _market, uint256[] memory _outcomes) public pure returns (uint256[] memory _tokenIds); //inject NONSTANDARD NAMING function BUYCOMPLETESETS983(IMarket _market, address _account, uint256 _amount) external returns (bool); //inject NONSTANDARD NAMING function BUYCOMPLETESETSFORTRADE277(IMarket _market, uint256 _amount, uint256 _longOutcome, address _longRecipient, address _shortRecipient) external returns (bool); //inject NONSTANDARD NAMING function SELLCOMPLETESETS485(IMarket _market, address _holder, address _recipient, uint256 _amount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function SELLCOMPLETESETSFORTRADE561(IMarket _market, uint256 _outcome, uint256 _amount, address _shortParticipant, address _longParticipant, address _shortRecipient, address _longRecipient, uint256 _price, address _sourceAccount, bytes32 _fingerprint) external returns (uint256 _creatorFee, uint256 _reportingFee); //inject NONSTANDARD NAMING function TOTALSUPPLYFORMARKETOUTCOME526(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFMARKETOUTCOME21(IMarket _market, uint256 _outcome, address _account) public view returns (uint256); //inject NONSTANDARD NAMING function LOWESTBALANCEOFMARKETOUTCOMES298(IMarket _market, uint256[] memory _outcomes, address _account) public view returns (uint256); //inject NONSTANDARD NAMING } contract IUniverse { function CREATIONTIME597() external view returns (uint256); //inject NONSTANDARD NAMING function MARKETBALANCE692(address) external view returns (uint256); //inject NONSTANDARD NAMING function FORK341() public returns (bool); //inject NONSTANDARD NAMING function UPDATEFORKVALUES73() public returns (bool); //inject NONSTANDARD NAMING function GETPARENTUNIVERSE169() public view returns (IUniverse); //inject NONSTANDARD NAMING function CREATECHILDUNIVERSE712(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); //inject NONSTANDARD NAMING function GETCHILDUNIVERSE576(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); //inject NONSTANDARD NAMING function GETREPUTATIONTOKEN35() public view returns (IV2ReputationToken); //inject NONSTANDARD NAMING function GETFORKINGMARKET637() public view returns (IMarket); //inject NONSTANDARD NAMING function GETFORKENDTIME510() public view returns (uint256); //inject NONSTANDARD NAMING function GETFORKREPUTATIONGOAL776() public view returns (uint256); //inject NONSTANDARD NAMING function GETPARENTPAYOUTDISTRIBUTIONHASH230() public view returns (bytes32); //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONINSECONDS412(bool _initial) public view returns (uint256); //inject NONSTANDARD NAMING function GETORCREATEDISPUTEWINDOWBYTIMESTAMP65(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATECURRENTDISPUTEWINDOW813(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATENEXTDISPUTEWINDOW682(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETORCREATEPREVIOUSDISPUTEWINDOW575(bool _initial) public returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETOPENINTERESTINATTOCASH866() public view returns (uint256); //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPINATTOCASH438() public view returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEVALIDITYBOND873() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTSTAKE630() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEDESIGNATEDREPORTNOSHOWBOND936() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEMARKETREPBOND533() public returns (uint256); //inject NONSTANDARD NAMING function GETORCACHEREPORTINGFEEDIVISOR44() public returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORFORK42() public view returns (uint256); //inject NONSTANDARD NAMING function GETDISPUTETHRESHOLDFORDISPUTEPACING311() public view returns (uint256); //inject NONSTANDARD NAMING function GETINITIALREPORTMINVALUE947() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATORS444() public view returns (uint256[] memory); //inject NONSTANDARD NAMING function GETREPORTINGFEEDIVISOR13() public view returns (uint256); //inject NONSTANDARD NAMING function GETPAYOUTNUMERATOR512(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETWINNINGCHILDPAYOUTNUMERATOR599(uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function ISOPENINTERESTCASH47(address) public view returns (bool); //inject NONSTANDARD NAMING function ISFORKINGMARKET534() public view returns (bool); //inject NONSTANDARD NAMING function GETCURRENTDISPUTEWINDOW862(bool _initial) public view returns (IDisputeWindow); //inject NONSTANDARD NAMING function GETDISPUTEWINDOWSTARTTIMEANDDURATION802(uint256 _timestamp, bool _initial) public view returns (uint256, uint256); //inject NONSTANDARD NAMING function ISPARENTOF319(IUniverse _shadyChild) public view returns (bool); //inject NONSTANDARD NAMING function UPDATETENTATIVEWINNINGCHILDUNIVERSE89(bytes32 _parentPayoutDistributionHash) public returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORMARKET856(IMarket _shadyTarget) public view returns (bool); //inject NONSTANDARD NAMING function ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant _reportingParticipant) public view returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETOUT672(IUniverse _destinationUniverse) public returns (bool); //inject NONSTANDARD NAMING function MIGRATEMARKETIN285(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTEREST834(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function DECREMENTOPENINTERESTFROMMARKET346(IMarket _market) public returns (bool); //inject NONSTANDARD NAMING function INCREMENTOPENINTEREST645(uint256 _amount) public returns (bool); //inject NONSTANDARD NAMING function GETWINNINGCHILDUNIVERSE709() public view returns (IUniverse); //inject NONSTANDARD NAMING function ISFORKING853() public view returns (bool); //inject NONSTANDARD NAMING function DEPOSIT693(address _sender, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function WITHDRAW474(address _recipient, uint256 _amount, address _market) public returns (bool); //inject NONSTANDARD NAMING function CREATESCALARMARKET875(uint256 _endTime, uint256 _feePerCashInAttoCash, IAffiliateValidator _affiliateValidator, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, int256[] memory _prices, uint256 _numTicks, string memory _extraInfo) public returns (IMarket _newMarket); //inject NONSTANDARD NAMING } contract IV2ReputationToken is IReputationToken { function PARENTUNIVERSE976() external returns (IUniverse); //inject NONSTANDARD NAMING function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool); //inject NONSTANDARD NAMING function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool); //inject NONSTANDARD NAMING } library Reporting { uint256 private constant designated_reporting_duration_seconds939 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_round_duration_seconds351 = 7 days; //inject NONSTANDARD NAMING uint256 private constant initial_dispute_round_duration_seconds185 = 1 days; //inject NONSTANDARD NAMING uint256 private constant dispute_window_buffer_seconds655 = 1 hours; //inject NONSTANDARD NAMING uint256 private constant fork_duration_seconds463 = 60 days; //inject NONSTANDARD NAMING uint256 private constant base_market_duration_maximum20 = 30 days; // A market of 30 day length can always be created //inject NONSTANDARD NAMING uint256 private constant upgrade_cadence254 = 365 days; //inject NONSTANDARD NAMING uint256 private constant initial_upgrade_timestamp605 = 1627776000; // Aug 1st 2021 //inject NONSTANDARD NAMING uint256 private constant initial_rep_supply507 = 11 * 10 ** 6 * 10 ** 18; // 11 Million REP //inject NONSTANDARD NAMING uint256 private constant affiliate_source_cut_divisor194 = 5; // The trader gets 20% of the affiliate fee when an affiliate fee is taken //inject NONSTANDARD NAMING uint256 private constant default_validity_bond803 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant validity_bond_floor708 = 10 ether; // 10 Cash (Dai) //inject NONSTANDARD NAMING uint256 private constant default_reporting_fee_divisor809 = 10000; // .01% fees //inject NONSTANDARD NAMING uint256 private constant maximum_reporting_fee_divisor548 = 10000; // Minimum .01% fees //inject NONSTANDARD NAMING uint256 private constant minimum_reporting_fee_divisor749 = 3; // Maximum 33.3~% fees. Note than anything less than a value of 2 here will likely result in bugs such as divide by 0 cases. //inject NONSTANDARD NAMING uint256 private constant target_invalid_markets_divisor747 = 100; // 1% of markets are expected to be invalid //inject NONSTANDARD NAMING uint256 private constant target_incorrect_designated_report_markets_divisor83 = 100; // 1% of markets are expected to have an incorrect designate report //inject NONSTANDARD NAMING uint256 private constant target_designated_report_no_shows_divisor678 = 20; // 5% of markets are expected to have a no show //inject NONSTANDARD NAMING uint256 private constant target_rep_market_cap_multiplier475 = 5; // We multiply and divide by constants since we may want to multiply by a fractional amount //inject NONSTANDARD NAMING uint256 private constant fork_threshold_divisor49 = 40; // 2.5% of the total REP supply being filled in a single dispute bond will trigger a fork //inject NONSTANDARD NAMING uint256 private constant maximum_dispute_rounds529 = 20; // We ensure that after 20 rounds of disputes a fork will occur //inject NONSTANDARD NAMING uint256 private constant minimum_slow_rounds438 = 8; // We ensure that at least 8 dispute rounds take DISPUTE_ROUND_DURATION_SECONDS+ seconds to complete until the next round begins //inject NONSTANDARD NAMING function GETDESIGNATEDREPORTINGDURATIONSECONDS10() internal pure returns (uint256) { return designated_reporting_duration_seconds939; } //inject NONSTANDARD NAMING function GETINITIALDISPUTEROUNDDURATIONSECONDS286() internal pure returns (uint256) { return initial_dispute_round_duration_seconds185; } //inject NONSTANDARD NAMING function GETDISPUTEWINDOWBUFFERSECONDS683() internal pure returns (uint256) { return dispute_window_buffer_seconds655; } //inject NONSTANDARD NAMING function GETDISPUTEROUNDDURATIONSECONDS187() internal pure returns (uint256) { return dispute_round_duration_seconds351; } //inject NONSTANDARD NAMING function GETFORKDURATIONSECONDS842() internal pure returns (uint256) { return fork_duration_seconds463; } //inject NONSTANDARD NAMING function GETBASEMARKETDURATIONMAXIMUM759() internal pure returns (uint256) { return base_market_duration_maximum20; } //inject NONSTANDARD NAMING function GETUPGRADECADENCE338() internal pure returns (uint256) { return upgrade_cadence254; } //inject NONSTANDARD NAMING function GETINITIALUPGRADETIMESTAMP486() internal pure returns (uint256) { return initial_upgrade_timestamp605; } //inject NONSTANDARD NAMING function GETDEFAULTVALIDITYBOND656() internal pure returns (uint256) { return default_validity_bond803; } //inject NONSTANDARD NAMING function GETVALIDITYBONDFLOOR634() internal pure returns (uint256) { return validity_bond_floor708; } //inject NONSTANDARD NAMING function GETTARGETINVALIDMARKETSDIVISOR906() internal pure returns (uint256) { return target_invalid_markets_divisor747; } //inject NONSTANDARD NAMING function GETTARGETINCORRECTDESIGNATEDREPORTMARKETSDIVISOR444() internal pure returns (uint256) { return target_incorrect_designated_report_markets_divisor83; } //inject NONSTANDARD NAMING function GETTARGETDESIGNATEDREPORTNOSHOWSDIVISOR524() internal pure returns (uint256) { return target_designated_report_no_shows_divisor678; } //inject NONSTANDARD NAMING function GETTARGETREPMARKETCAPMULTIPLIER935() internal pure returns (uint256) { return target_rep_market_cap_multiplier475; } //inject NONSTANDARD NAMING function GETMAXIMUMREPORTINGFEEDIVISOR201() internal pure returns (uint256) { return maximum_reporting_fee_divisor548; } //inject NONSTANDARD NAMING function GETMINIMUMREPORTINGFEEDIVISOR230() internal pure returns (uint256) { return minimum_reporting_fee_divisor749; } //inject NONSTANDARD NAMING function GETDEFAULTREPORTINGFEEDIVISOR804() internal pure returns (uint256) { return default_reporting_fee_divisor809; } //inject NONSTANDARD NAMING function GETINITIALREPSUPPLY859() internal pure returns (uint256) { return initial_rep_supply507; } //inject NONSTANDARD NAMING function GETAFFILIATESOURCECUTDIVISOR779() internal pure returns (uint256) { return affiliate_source_cut_divisor194; } //inject NONSTANDARD NAMING function GETFORKTHRESHOLDDIVISOR823() internal pure returns (uint256) { return fork_threshold_divisor49; } //inject NONSTANDARD NAMING function GETMAXIMUMDISPUTEROUNDS774() internal pure returns (uint256) { return maximum_dispute_rounds529; } //inject NONSTANDARD NAMING function GETMINIMUMSLOWROUNDS218() internal pure returns (uint256) { return minimum_slow_rounds438; } //inject NONSTANDARD NAMING } contract IAugurTrading { function LOOKUP594(bytes32 _key) public view returns (address); //inject NONSTANDARD NAMING function LOGPROFITLOSSCHANGED911(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCREATED154(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERCANCELED389(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); //inject NONSTANDARD NAMING function LOGORDERFILLED166(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); //inject NONSTANDARD NAMING function LOGMARKETVOLUMECHANGED635(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes, uint256 _totalTrades) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERFILLED898(IUniverse _universe, IMarket _market, bytes32 _orderHash, bytes32 _tradeGroupId, uint8 _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); //inject NONSTANDARD NAMING function LOGZEROXORDERCANCELED137(address _universe, address _market, address _account, uint256 _outcome, uint256 _price, uint256 _amount, uint8 _type, bytes32 _orderHash) public; //inject NONSTANDARD NAMING } contract IOrders { function SAVEORDER165(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender) external returns (bytes32 _orderId); //inject NONSTANDARD NAMING function REMOVEORDER407(bytes32 _orderId) external returns (bool); //inject NONSTANDARD NAMING function GETMARKET927(bytes32 _orderId) public view returns (IMarket); //inject NONSTANDARD NAMING function GETORDERTYPE39(bytes32 _orderId) public view returns (Order.Types); //inject NONSTANDARD NAMING function GETOUTCOME167(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETAMOUNT930(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETPRICE598(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERCREATOR755(bytes32 _orderId) public view returns (address); //inject NONSTANDARD NAMING function GETORDERSHARESESCROWED20(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERMONEYESCROWED161(bytes32 _orderId) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERDATAFORCANCEL357(bytes32 _orderId) public view returns (uint256, uint256, Order.Types, IMarket, uint256, address); //inject NONSTANDARD NAMING function GETORDERDATAFORLOGS935(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); //inject NONSTANDARD NAMING function GETBETTERORDERID822(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSEORDERID439(bytes32 _orderId) public view returns (bytes32); //inject NONSTANDARD NAMING function GETBESTORDERID727(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETWORSTORDERID835(Order.Types _type, IMarket _market, uint256 _outcome) public view returns (bytes32); //inject NONSTANDARD NAMING function GETLASTOUTCOMEPRICE593(IMarket _market, uint256 _outcome) public view returns (uint256); //inject NONSTANDARD NAMING function GETORDERID157(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) public pure returns (bytes32); //inject NONSTANDARD NAMING function GETTOTALESCROWED463(IMarket _market) public view returns (uint256); //inject NONSTANDARD NAMING function ISBETTERPRICE274(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ISWORSEPRICE692(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTBETTERPRICE18(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); //inject NONSTANDARD NAMING function ASSERTISNOTWORSEPRICE875(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); //inject NONSTANDARD NAMING function RECORDFILLORDER693(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); //inject NONSTANDARD NAMING function SETPRICE687(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); //inject NONSTANDARD NAMING } library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IMarket market; IAugur augur; IAugurTrading augurTrading; IShareToken shareToken; ICash cash; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } function CREATE815(IAugur _augur, IAugurTrading _augurTrading, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId) internal view returns (Data memory) { //inject NONSTANDARD NAMING require(_outcome < _market.GETNUMBEROFOUTCOMES636(), "Order.create: Outcome is not within market range"); require(_price != 0, "Order.create: Price may not be 0"); require(_price < _market.GETNUMTICKS752(), "Order.create: Price is outside of market range"); require(_attoshares > 0, "Order.create: Cannot use amount of 0"); require(_creator != address(0), "Order.create: Creator is 0x0"); IShareToken _shareToken = IShareToken(_augur.LOOKUP594("ShareToken")); return Data({ market: _market, augur: _augur, augurTrading: _augurTrading, shareToken: _shareToken, cash: ICash(_augur.LOOKUP594("Cash")), id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function GETORDERID157(Order.Data memory _orderData, IOrders _orders) internal view returns (bytes32) { //inject NONSTANDARD NAMING if (_orderData.id == bytes32(0)) { bytes32 _orderId = CALCULATEORDERID856(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed); require(_orders.GETAMOUNT930(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible"); _orderData.id = _orderId; } return _orderData.id; } function CALCULATEORDERID856(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed) internal pure returns (bytes32) { //inject NONSTANDARD NAMING return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed)); } function GETORDERTRADINGTYPEFROMMAKERDIRECTION100(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function GETORDERTRADINGTYPEFROMFILLERDIRECTION800(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { //inject NONSTANDARD NAMING return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function SAVEORDER165(Order.Data memory _orderData, bytes32 _tradeGroupId, IOrders _orders) internal returns (bytes32) { //inject NONSTANDARD NAMING GETORDERID157(_orderData, _orders); uint256[] memory _uints = new uint256[](5); _uints[0] = _orderData.amount; _uints[1] = _orderData.price; _uints[2] = _orderData.outcome; _uints[3] = _orderData.moneyEscrowed; _uints[4] = _orderData.sharesEscrowed; bytes32[] memory _bytes32s = new bytes32[](4); _bytes32s[0] = _orderData.betterOrderId; _bytes32s[1] = _orderData.worseOrderId; _bytes32s[2] = _tradeGroupId; _bytes32s[3] = _orderData.id; return _orders.SAVEORDER165(_uints, _bytes32s, _orderData.orderType, _orderData.market, _orderData.creator); } } interface IUniswapV2Pair { event APPROVAL665(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER723(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME524() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL582() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS958() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY304() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF492(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE377(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE293(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER644(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM669(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR256() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH256() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES605(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT866(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT159(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN674(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP992( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC856(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY585() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY704() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0151() external view returns (address); //inject NONSTANDARD NAMING function TOKEN132() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES901() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST708() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST245() external view returns (uint); //inject NONSTANDARD NAMING function KLAST943() external view returns (uint); //inject NONSTANDARD NAMING function MINT146(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN234(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP505(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM81(address to) external; //inject NONSTANDARD NAMING function SYNC86() external; //inject NONSTANDARD NAMING function INITIALIZE90(address, address) external; //inject NONSTANDARD NAMING } contract IRepSymbol { function GETREPSYMBOL498(address _augur, address _universe) external view returns (string memory); //inject NONSTANDARD NAMING } contract ReputationToken is VariableSupplyToken, IV2ReputationToken { using SafeMathUint256 for uint256; string constant public name600 = "Reputation"; //inject NONSTANDARD NAMING IUniverse internal universe; IUniverse public parentUniverse; uint256 internal totalMigrated; IERC20 public legacyRepToken; IAugur public augur; address public warpSync; constructor(IAugur _augur, IUniverse _universe, IUniverse _parentUniverse) public { augur = _augur; universe = _universe; parentUniverse = _parentUniverse; warpSync = _augur.LOOKUP594("WarpSync"); legacyRepToken = IERC20(_augur.LOOKUP594("LegacyReputationToken")); require(warpSync != address(0)); require(legacyRepToken != IERC20(0)); } function SYMBOL582() public view returns (string memory) { //inject NONSTANDARD NAMING return IRepSymbol(augur.LOOKUP594("RepSymbol")).GETREPSYMBOL498(address(augur), address(universe)); } function MIGRATEOUTBYPAYOUT436(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(_attotokens > 0); IUniverse _destinationUniverse = universe.CREATECHILDUNIVERSE712(_payoutNumerators); IReputationToken _destination = _destinationUniverse.GETREPUTATIONTOKEN35(); BURN234(msg.sender, _attotokens); _destination.MIGRATEIN692(msg.sender, _attotokens); return true; } function MIGRATEIN692(address _reporter, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING IUniverse _parentUniverse = parentUniverse; require(ReputationToken(msg.sender) == _parentUniverse.GETREPUTATIONTOKEN35()); require(augur.GETTIMESTAMP626() < _parentUniverse.GETFORKENDTIME510()); MINT146(_reporter, _attotokens); totalMigrated += _attotokens; // Update the fork tentative winner and finalize if we can if (!_parentUniverse.GETFORKINGMARKET637().ISFINALIZED623()) { _parentUniverse.UPDATETENTATIVEWINNINGCHILDUNIVERSE89(universe.GETPARENTPAYOUTDISTRIBUTIONHASH230()); } return true; } function MINTFORREPORTINGPARTICIPANT798(uint256 _amountMigrated) public returns (bool) { //inject NONSTANDARD NAMING IReportingParticipant _reportingParticipant = IReportingParticipant(msg.sender); require(parentUniverse.ISCONTAINERFORREPORTINGPARTICIPANT696(_reportingParticipant)); // simulate a 40% ROI which would have occured during a normal dispute had this participant's outcome won the dispute uint256 _bonus = _amountMigrated.MUL760(2) / 5; MINT146(address(_reportingParticipant), _bonus); return true; } function MINTFORWARPSYNC909(uint256 _amountToMint, address _target) public returns (bool) { //inject NONSTANDARD NAMING require(warpSync == msg.sender); MINT146(_target, _amountToMint); universe.UPDATEFORKVALUES73(); return true; } function BURNFORMARKET683(uint256 _amountToBurn) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); BURN234(msg.sender, _amountToBurn); return true; } function TRUSTEDUNIVERSETRANSFER148(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(IUniverse(msg.sender) == universe); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDMARKETTRANSFER61(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORMARKET856(IMarket(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDREPORTINGPARTICIPANTTRANSFER10(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORREPORTINGPARTICIPANT696(IReportingParticipant(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function TRUSTEDDISPUTEWINDOWTRANSFER53(address _source, address _destination, uint256 _attotokens) public returns (bool) { //inject NONSTANDARD NAMING require(universe.ISCONTAINERFORDISPUTEWINDOW320(IDisputeWindow(msg.sender))); _TRANSFER433(_source, _destination, _attotokens); return true; } function ASSERTREPUTATIONTOKENISLEGITCHILD164(IReputationToken _shadyReputationToken) private view { //inject NONSTANDARD NAMING IUniverse _universe = _shadyReputationToken.GETUNIVERSE719(); require(universe.ISPARENTOF319(_universe)); require(_universe.GETREPUTATIONTOKEN35() == _shadyReputationToken); } function GETUNIVERSE719() public view returns (IUniverse) { //inject NONSTANDARD NAMING return universe; } function GETTOTALMIGRATED220() public view returns (uint256) { //inject NONSTANDARD NAMING return totalMigrated; } function GETLEGACYREPTOKEN110() public view returns (IERC20) { //inject NONSTANDARD NAMING return legacyRepToken; } function GETTOTALTHEORETICALSUPPLY552() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 _totalSupply = totalSupply; if (parentUniverse == IUniverse(0)) { return _totalSupply.ADD571(legacyRepToken.TOTALSUPPLY304()).SUB692(legacyRepToken.BALANCEOF492(address(1))).SUB692(legacyRepToken.BALANCEOF492(address(0))); } else if (augur.GETTIMESTAMP626() >= parentUniverse.GETFORKENDTIME510()) { return _totalSupply; } else { return _totalSupply + parentUniverse.GETREPUTATIONTOKEN35().GETTOTALTHEORETICALSUPPLY552(); } } function ONTOKENTRANSFER292(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSTRANSFERRED904(universe, _from, _to, _value, balances[_from], balances[_to]); } function ONMINT315(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSMINTED985(universe, _target, _amount, totalSupply, balances[_target]); } function ONBURN653(address _target, uint256 _amount) internal { //inject NONSTANDARD NAMING augur.LOGREPUTATIONTOKENSBURNED995(universe, _target, _amount, totalSupply, balances[_target]); } function MIGRATEFROMLEGACYREPUTATIONTOKEN918() public returns (bool) { //inject NONSTANDARD NAMING require(parentUniverse == IUniverse(0)); uint256 _legacyBalance = legacyRepToken.BALANCEOF492(msg.sender); require(legacyRepToken.TRANSFERFROM669(msg.sender, address(1), _legacyBalance)); MINT146(msg.sender, _legacyBalance); return true; } }
inject NONSTANDARD NAMING
function TRANSFEROWNERSHIP284(address _newOwner) public returns (bool);
2,553,826
./partial_match/1/0xCb8007FED878050958942C4589E989626eA8E0A9/sources/ElonDogs.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Elon Dogs", "GATSBYMARVIN") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyLiquidityFee = 0; uint256 _sellMarketingFee = 1; uint256 _sellLiquidityFee = 0; uint256 _sellTeamFee = 0; uint256 totalSupply = 100_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyTeamFee = _buyTeamFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyTeamFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellTeamFee = _sellTeamFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellTeamFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
2,653,894
pragma solidity ^0.4.19; /** * @title Multisignio Contract * @author Alex 'AL_X' Papageorgiou * @dev The MSG ERC-20 & ERC-223 Compliant Token Contract */ contract Multisignio { string public name = "Multisignio"; string public symbol = "MSG"; address public admin; uint8 public decimals = 16; uint256 public totalFunds; uint256 public totalSupply = 270000000*(10**16); uint256 public tokenSaleDate; uint256 public transparentCost; uint256 public liteCost; uint256 public availableFreeWallets; uint256 public airdropTokens; uint256 private decimalMultiplier = 10**16; bool private running; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; mapping(address => bool) freeWallet; mapping(address => bool) airdropClaimed; mapping(address => bool) whitelisted; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event WalletCreation(address indexed _owner, uint256 _type, bytes32 _partialSeed); /** * @notice Ensures admin is caller */ modifier isAdmin() { require(msg.sender == admin); _; } /** * @notice Re-entry protection */ modifier isRunning() { require(!running); running = true; _; running = false; } /** * @notice SafeMath Library safeSub Import * @dev Since we are dealing with a limited currency circulation of 270 million tokens and values that will not surpass the uint256 limit, only safeSub is required to prevent underflows. */ function safeSub(uint256 a, uint256 b) internal pure returns (uint256 z) { assert((z = a - b) <= a); } /** * @notice MSG Constructor * @dev Normal constructor function, 94m tokens on sale during the ICO, 1m tokens for bounties & 5m tokens for the developers. */ function Multisignio() public { admin = msg.sender; balances[msg.sender] = 66000000*decimalMultiplier; airdropTokens = 4000000*decimalMultiplier; balances[this] = 200000000*decimalMultiplier; tokenSaleDate = ~uint256(0); liteCost = 1200*decimalMultiplier; transparentCost = liteCost*10; availableFreeWallets = 10000; } /** * @notice Check the name of the token ~ ERC-20 Standard * @return { "_name": "The token name" } */ function name() external constant returns (string _name) { return name; } /** * @notice Check the symbol of the token ~ ERC-20 Standard * @return { "_symbol": "The token symbol" } */ function symbol() external constant returns (string _symbol) { return symbol; } /** * @notice Check the decimals of the token ~ ERC-20 Standard * @return { "_decimals": "The token decimals" } */ function decimals() external constant returns (uint8 _decimals) { return decimals; } /** * @notice Check the total supply of the token ~ ERC-20 Standard * @return { "_totalSupply": "Total supply of tokens" } */ function totalSupply() external constant returns (uint256 _totalSupply) { return totalSupply; } /** * @notice Query the available balance of an address ~ ERC-20 Standard * @param _owner The address whose balance we wish to retrieve * @return { "balance": "Balance of the address" } */ function balanceOf(address _owner) external constant returns (uint256 balance) { return balances[_owner]; } /** * @notice Query the amount of tokens the spender address can withdraw from the owner address ~ ERC-20 Standard * @param _owner The address who owns the tokens * @param _spender The address who can withdraw the tokens * @return { "remaining": "Remaining withdrawal amount" } */ function allowance(address _owner, address _spender) external constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @notice Transfer tokens from an address to another ~ ERC-20 Standard * @param _from The address whose balance we will transfer * @param _to The recipient address * @param _value The amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) external { var _allowance = allowed[_from][_to]; balances[_to] = balances[_to]+_value; balances[_from] = safeSub(balances[_from], _value); allowed[_from][_to] = safeSub(_allowance, _value); Transfer(_from, _to, _value); } /** * @notice Authorize an address to retrieve funds from you ~ ERC-20 Standard * @dev Each approval comes with a default cooldown of 30 minutes to prevent against the ERC-20 race attack. * @param _spender The address you wish to authorize * @param _value The amount of tokens you wish to authorize */ function approve(address _spender, uint256 _value) external { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @notice Transfer the specified amount to the target address ~ ERC-20 Standard * @dev A boolean is returned so that callers of the function will know if their transaction went through. * @param _to The address you wish to send the tokens to * @param _value The amount of tokens you wish to send * @return { "success": "Transaction success" } */ function transfer(address _to, uint256 _value) external isRunning returns (bool success){ bytes memory empty; if (_to == address(this)) { revert(); } else if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } /** * @notice Check whether address is a contract ~ ERC-223 Proposed Standard * @param _address The address to check * @return { "is_contract": "Result of query" } */ function isContract(address _address) internal view returns (bool is_contract) { uint length; assembly { length := extcodesize(_address) } return length > 0; } /** * @notice Transfer the specified amount to the target address with embedded bytes data ~ ERC-223 Proposed Standard * @dev Includes an extra buyWallet function to handle wallet purchases * @param _to The address to transfer to * @param _value The amount of tokens to transfer * @param _data Any extra embedded data of the transaction * @return { "success": "Transaction success" } */ function transfer(address _to, uint256 _value, bytes _data) external isRunning returns (bool success) { if (_to == address(this)) { revert(); } else if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @notice Handles transfer to an ECA (Externally Controlled Account), a normal account ~ ERC-223 Proposed Standard * @param _to The address to transfer to * @param _value The amount of tokens to transfer * @param _data Any extra embedded data of the transaction * @return { "success": "Transaction success" } */ function transferToAddress(address _to, uint256 _value, bytes _data) internal returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = balances[_to]+_value; Transfer(msg.sender, _to, _value); return true; } /** * @notice Handles transfer to a contract ~ ERC-223 Proposed Standard * @param _to The address to transfer to * @param _value The amount of tokens to transfer * @param _data Any extra embedded data of the transaction * @return { "success": "Transaction success" } */ function transferToContract(address _to, uint256 _value, bytes _data) internal returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = balances[_to]+_value; Multisignio rec = Multisignio(_to); rec.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * @notice Empty tokenFallback method to ensure ERC-223 compatibility * @param _sender The address who sent the ERC-223 tokens * @param _value The amount of tokens the address sent to this contract * @param _data Any embedded data of the transaction */ function tokenFallback(address _sender, uint256 _value, bytes _data) public {} /** * @notice Retrieve ERC Tokens sent to contract * @dev Feel free to contact us and retrieve your ERC tokens should you wish so. * @param _token The token contract address */ function claimTokens(address _token) isAdmin external { require(_token != address(this)); Multisignio token = Multisignio(_token); uint balance = token.balanceOf(this); token.transfer(admin, balance); } /** * @notice Fallback function * @dev Triggered when Ether is sent to the contract. */ function() payable external { require(msg.value > 1*decimalMultiplier*10); totalFunds += msg.value; if (now > tokenSaleDate) { uint256 tokenAmount; tokenAmount = tokenMultiplier(msg.value); balances[msg.sender] += tokenAmount; balances[this] = safeSub(balances[this],tokenAmount); Transfer(this, msg.sender, tokenAmount); admin.transfer(msg.value); } else if (tokenSaleDate == ~uint256(0)) { require(whitelisted[msg.sender] && msg.value > 2*decimalMultiplier*(10**2) && totalFunds < 13335*decimalMultiplier*10); tokenAmount = 150*msg.value; balances[msg.sender] += tokenAmount; balances[this] = safeSub(balances[this],tokenAmount); Transfer(this, msg.sender, tokenAmount); admin.transfer(msg.value); } else { revert(); } } /** * @notice Token Multiplier getter * @dev The token price adjustes based on both demand & a time-based sale */ function tokenMultiplier(uint256 etherSent) public view returns (uint256) { if (now < tokenSaleDate + 7 days && (200000000*decimalMultiplier - balances[this]) <= 60000000*decimalMultiplier) { return 100*etherSent; } else if (now < tokenSaleDate + 14 days && (200000000*decimalMultiplier - balances[this]) <= 100000000*decimalMultiplier) { return 75*etherSent; } else if (now < tokenSaleDate + 21 days && (200000000*decimalMultiplier - balances[this]) <= 140000000*decimalMultiplier) { return 50*etherSent; } else { return 30*etherSent; } } /** * @notice Burning function * @dev Burns any leftover crowdfunding tokens to ensure a proper value is * set in the crypto market cap. */ function burnLeftovers() external { require(tokenSaleDate + 30 days < now && balances[this] > 0); totalSupply -= balances[this]; balances[this] = 0; tokenSaleDate = ~uint256(0) - 1; } /** * @notice Set recirculation contract address * @dev Recirculates tokens acquired through the sale of MSG Wallets, * helping achieve a stable token price. * @param _contractAddress The recirculation contract address */ function setRecirculationContract(address _contractAddress) external isAdmin { recirculationAddress = _contractAddress; } /** * @notice Wallet Creation function * @dev Creates a wallet based on the input seed as far as the necessary token amount has been sent * @param _value Amount correlating to the wallet type * @param _seed The string to base the wallet creation on */ function buyWallet(uint256 _value, bytes32 _seed) public returns (bool success) { uint256 check = ~uint256(0) - 1; require(tokenSaleDate == check && recirculationAddress != 0x0); if (_value == transparentCost) { balances[msg.sender] = safeSub(balances[msg.sender], transparentCost); balances[recirculationAddress] += transparentCost; if (freeWallet[msg.sender]) { availableFreeWallets++; freeWallet[msg.sender] = false; } WalletCreation(msg.sender, transparentCost, _seed); Transfer(msg.sender, this, transparentCost); return true; } else if (_value == liteCost) { balances[msg.sender] = safeSub(balances[msg.sender], liteCost); balances[recirculationAddress] += liteCost; if (freeWallet[msg.sender]) { availableFreeWallets++; freeWallet[msg.sender] = false; } WalletCreation(msg.sender, liteCost, _seed); Transfer(msg.sender, this, liteCost); return true; } else if (_value == 0) { require(availableFreeWallets >= 1); require(!freeWallet[msg.sender]); availableFreeWallets--; freeWallet[msg.sender] = true; WalletCreation(msg.sender, 0, _seed); return true; } else { revert(); } } /** * @notice Token Sale Initiation * @dev Begins the token sale on the date this function is called */ function beginSale() external isAdmin { require(tokenSaleDate == ~uint256(0)); tokenSaleDate = now; } /** * @notice Wallet Price Adjustment * @dev Function to adjust prices based on current token market price */ function adjustWalletPrices(uint256 _liteCost) external isAdmin { liteCost = _liteCost*decimalMultiplier; transparentCost = liteCost*10; } /** * @notice Airdrop Function * @dev Function to claim 1000 tokens from the AirDrop */ function claimAirdropTokens() external { require(!airdropClaimed[msg.sender]); airdropClaimed[msg.sender] = true; balances[msg.sender] += 1000*decimalMultiplier; airdropTokens = safeSub(airdropTokens, 1000*decimalMultiplier); Transfer(this, msg.sender, 1000*decimalMultiplier); } /** * @notice Whitelist Function * @dev Function to whitelist addresses for the 1 day presale * @param toWhitelist Address to add to whitelist */ function whitelistAddress(address toWhitelist) external isAdmin { whitelisted[toWhitelist] = true; } }
Airdrop Function Function to claim 1000 tokens from the AirDrop/
function claimAirdropTokens() external { require(!airdropClaimed[msg.sender]); airdropClaimed[msg.sender] = true; balances[msg.sender] += 1000*decimalMultiplier; airdropTokens = safeSub(airdropTokens, 1000*decimalMultiplier); Transfer(this, msg.sender, 1000*decimalMultiplier); }
13,048,784
./full_match/4/0x5588447345106F002A7A7566F3880064Ba7172EA/sources/Solidity/FundMe.sol
AggregatorV3Interface price = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
function fund() public payable{ addrToAmountFunded[msg.sender] += msg.value; }
732,118
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("ECDSA: invalid signature length"); } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (governor) that can be granted exclusive access to * specific functions. * * By default, the governor account will be the one that deploys the contract. This * can later be changed with {transferGovernorship}. * */ contract Governed is Context, Initializable { address public governor; address private proposedGovernor; event UpdatedGovernor(address indexed previousGovernor, address indexed proposedGovernor); /** * @dev Initializes the contract setting the deployer as the initial governor. */ constructor() { address msgSender = _msgSender(); governor = msgSender; emit UpdatedGovernor(address(0), msgSender); } /** * @dev If inheriting child is using proxy then child contract can use * _initializeGoverned() function to initialization this contract */ function _initializeGoverned() internal initializer { address msgSender = _msgSender(); governor = msgSender; emit UpdatedGovernor(address(0), msgSender); } /** * @dev Throws if called by any account other than the governor. */ modifier onlyGovernor { require(governor == _msgSender(), "not-the-governor"); _; } /** * @dev Transfers governorship of the contract to a new account (`proposedGovernor`). * Can only be called by the current owner. */ function transferGovernorship(address _proposedGovernor) external onlyGovernor { require(_proposedGovernor != address(0), "proposed-governor-is-zero"); proposedGovernor = _proposedGovernor; } /** * @dev Allows new governor to accept governorship of the contract. */ function acceptGovernorship() external { require(proposedGovernor == _msgSender(), "not-the-proposed-governor"); emit UpdatedGovernor(governor, proposedGovernor); governor = proposedGovernor; proposedGovernor = address(0); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * */ contract Pausable is Context { event Paused(address account); event Shutdown(address account); event Unpaused(address account); event Open(address account); bool public paused; bool public stopEverything; modifier whenNotPaused() { require(!paused, "paused"); _; } modifier whenPaused() { require(paused, "not-paused"); _; } modifier whenNotShutdown() { require(!stopEverything, "shutdown"); _; } modifier whenShutdown() { require(stopEverything, "not-shutdown"); _; } /// @dev Pause contract operations, if contract is not paused. function _pause() internal virtual whenNotPaused { paused = true; emit Paused(_msgSender()); } /// @dev Unpause contract operations, allow only if contract is paused and not shutdown. function _unpause() internal virtual whenPaused whenNotShutdown { paused = false; emit Unpaused(_msgSender()); } /// @dev Shutdown contract operations, if not already shutdown. function _shutdown() internal virtual whenNotShutdown { stopEverything = true; paused = true; emit Shutdown(_msgSender()); } /// @dev Open contract operations, if contract is in shutdown state function _open() internal virtual whenShutdown { stopEverything = false; emit Open(_msgSender()); } } // 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: MIT pragma solidity 0.8.3; interface IPoolAccountant { function decreaseDebt(address _strategy, uint256 _decreaseBy) external; function migrateStrategy(address _old, address _new) external; function reportEarning( address _strategy, uint256 _profit, uint256 _loss, uint256 _payback ) external returns ( uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee ); function reportLoss(address _strategy, uint256 _loss) external; function availableCreditLimit(address _strategy) external view returns (uint256); function excessDebt(address _strategy) external view returns (uint256); function getStrategies() external view returns (address[] memory); function getWithdrawQueue() external view returns (address[] memory); function strategy(address _strategy) external view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio, uint256 _externalDepositFee ); function externalDepositFee() external view returns (uint256); function totalDebt() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalDebtRatio() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IPoolRewards { /// Emitted after reward added event RewardAdded(address indexed rewardToken, uint256 reward, uint256 rewardDuration); /// Emitted whenever any user claim rewards event RewardPaid(address indexed user, address indexed rewardToken, uint256 reward); /// Emitted after adding new rewards token into rewardTokens array event RewardTokenAdded(address indexed rewardToken, address[] existingRewardTokens); function claimReward(address) external; function notifyRewardAmount( address _rewardToken, uint256 _rewardAmount, uint256 _rewardDuration ) external; function notifyRewardAmount( address[] memory _rewardTokens, uint256[] memory _rewardAmounts, uint256[] memory _rewardDurations ) external; function updateReward(address) external; function claimable(address _account) external view returns (address[] memory _rewardTokens, uint256[] memory _claimableAmounts); function lastTimeRewardApplicable(address _rewardToken) external view returns (uint256); function rewardForDuration() external view returns (address[] memory _rewardTokens, uint256[] memory _rewardForDuration); function rewardPerToken() external view returns (address[] memory _rewardTokens, uint256[] memory _rewardPerTokenRate); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; interface IStrategy { function rebalance() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function feeCollector() external view returns (address); function isReservedToken(address _token) external view returns (bool); function keepers() external view returns (address[] memory); function migrate(address _newStrategy) external; function token() external view returns (address); function totalValue() external view returns (uint256); function totalValueCurrent() external returns (uint256); function pool() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /// @title Errors library library Errors { string public constant INVALID_COLLATERAL_AMOUNT = "1"; // Collateral must be greater than 0 string public constant INVALID_SHARE_AMOUNT = "2"; // Share must be greater than 0 string public constant INVALID_INPUT_LENGTH = "3"; // Input array length must be greater than 0 string public constant INPUT_LENGTH_MISMATCH = "4"; // Input array length mismatch with another array length string public constant NOT_WHITELISTED_ADDRESS = "5"; // Caller is not whitelisted to withdraw without fee string public constant MULTI_TRANSFER_FAILED = "6"; // Multi transfer of tokens has failed string public constant FEE_COLLECTOR_NOT_SET = "7"; // Fee Collector is not set string public constant NOT_ALLOWED_TO_SWEEP = "8"; // Token is not allowed to sweep string public constant INSUFFICIENT_BALANCE = "9"; // Insufficient balance to performs operations to follow string public constant INPUT_ADDRESS_IS_ZERO = "10"; // Input address is zero string public constant FEE_LIMIT_REACHED = "11"; // Fee must be less than MAX_BPS string public constant ALREADY_INITIALIZED = "12"; // Data structure, contract, or logic already initialized and can not be called again string public constant ADD_IN_LIST_FAILED = "13"; // Cannot add address in address list string public constant REMOVE_FROM_LIST_FAILED = "14"; // Cannot remove address from address list string public constant STRATEGY_IS_ACTIVE = "15"; // Strategy is already active, an inactive strategy is required string public constant STRATEGY_IS_NOT_ACTIVE = "16"; // Strategy is not active, an active strategy is required string public constant INVALID_STRATEGY = "17"; // Given strategy is not a strategy of this pool string public constant DEBT_RATIO_LIMIT_REACHED = "18"; // Debt ratio limit reached. It must be less than MAX_BPS string public constant TOTAL_DEBT_IS_NOT_ZERO = "19"; // Strategy total debt must be 0 string public constant LOSS_TOO_HIGH = "20"; // Strategy reported loss must be less than current debt } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/utils/Context.sol"; // solhint-disable reason-string, no-empty-blocks ///@title Pool ERC20 to use with proxy. Inspired by OpenZeppelin ERC20 abstract contract PoolERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the decimals of the token. default to 18 */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev Returns total supply of the token. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += 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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _setName(string memory name_) internal { _name = name_; } function _setSymbol(string memory symbol_) internal { _symbol = symbol_; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "./PoolERC20.sol"; ///@title Pool ERC20 Permit to use with proxy. Inspired by OpenZeppelin ERC20Permit // solhint-disable var-name-mixedcase abstract contract PoolERC20Permit is PoolERC20, IERC20Permit { bytes32 private constant _EIP712_VERSION = keccak256(bytes("1")); bytes32 private constant _EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private _CACHED_DOMAIN_SEPARATOR; bytes32 private _HASHED_NAME; uint256 private _CACHED_CHAIN_ID; /** * @dev See {IERC20Permit-nonces}. */ mapping(address => uint256) public override nonces; /** * @dev Initializes the domain separator using the `name` parameter, and setting `version` to `"1"`. * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function _initializePermit(string memory name_) internal { _HASHED_NAME = keccak256(bytes(name_)); _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION); } /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); uint256 _currentNonce = nonces[owner]; bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _currentNonce, deadline)); bytes32 hash = keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); nonces[owner] = _currentNonce + 1; _approve(owner, spender, value); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() private view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_EIP712_DOMAIN_TYPEHASH, _HASHED_NAME, _EIP712_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 name, bytes32 version ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, name, version, block.chainid, address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./PoolERC20Permit.sol"; import "./PoolStorage.sol"; import "./Errors.sol"; import "../Governed.sol"; import "../Pausable.sol"; import "../interfaces/vesper/IPoolAccountant.sol"; import "../interfaces/vesper/IPoolRewards.sol"; /// @title Holding pool share token // solhint-disable no-empty-blocks abstract contract PoolShareToken is Initializable, PoolERC20Permit, Governed, Pausable, ReentrancyGuard, PoolStorageV2 { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; uint256 public constant MAX_BPS = 10_000; event Deposit(address indexed owner, uint256 shares, uint256 amount); event Withdraw(address indexed owner, uint256 shares, uint256 amount); // We are using constructor to initialize implementation with basic details constructor( string memory _name, string memory _symbol, address _token ) PoolERC20(_name, _symbol) { // 0x0 is acceptable as has no effect on functionality token = IERC20(_token); } /// @dev Equivalent to constructor for proxy. It can be called only once per proxy. function _initializePool( string memory _name, string memory _symbol, address _token ) internal initializer { require(_token != address(0), Errors.INPUT_ADDRESS_IS_ZERO); _setName(_name); _setSymbol(_symbol); _initializePermit(_name); token = IERC20(_token); // Assuming token supports 18 or less decimals uint256 _decimals = IERC20Metadata(_token).decimals(); decimalConversionFactor = 10**(18 - _decimals); } /** * @notice Deposit ERC20 tokens and receive pool shares depending on the current share price. * @param _amount ERC20 token amount. */ function deposit(uint256 _amount) external virtual nonReentrant whenNotPaused { _updateRewards(_msgSender()); _deposit(_amount); } /** * @notice Deposit ERC20 tokens and claim rewards if any * @param _amount ERC20 token amount. */ function depositAndClaim(uint256 _amount) external virtual nonReentrant whenNotPaused { _depositAndClaim(_amount); } /** * @notice Deposit ERC20 tokens with permit aka gasless approval. * @param _amount ERC20 token amount. * @param _deadline The time at which signature will expire * @param _v The recovery byte of the signature * @param _r Half of the ECDSA signature pair * @param _s Half of the ECDSA signature pair */ function depositWithPermit( uint256 _amount, uint256 _deadline, uint8 _v, bytes32 _r, bytes32 _s ) external virtual nonReentrant whenNotPaused { IERC20Permit(address(token)).permit(_msgSender(), address(this), _amount, _deadline, _v, _r, _s); _deposit(_amount); } /** * @notice Withdraw collateral based on given shares and the current share price. * Withdraw fee, if any, will be deduced from given shares and transferred to feeCollector. * Burn remaining shares and return collateral. * @param _shares Pool shares. It will be in 18 decimals. */ function withdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown { _updateRewards(_msgSender()); _withdraw(_shares); } /** * @notice Withdraw collateral and claim rewards if any * @param _shares Pool shares. It will be in 18 decimals. */ function withdrawAndClaim(uint256 _shares) external virtual nonReentrant whenNotShutdown { _withdrawAndClaim(_shares); } /** * @notice Withdraw collateral based on given shares and the current share price. * @dev Burn shares and return collateral. No withdraw fee will be assessed * when this function is called. Only some white listed address can call this function. * @param _shares Pool shares. It will be in 18 decimals. * This function is deprecated, normal withdraw will check for whitelisted address */ function whitelistedWithdraw(uint256 _shares) external virtual nonReentrant whenNotShutdown { require(_feeWhitelist.contains(_msgSender()), Errors.NOT_WHITELISTED_ADDRESS); require(_shares != 0, Errors.INVALID_SHARE_AMOUNT); _claimRewards(_msgSender()); _withdrawWithoutFee(_shares); } /** * @notice Transfer tokens to multiple recipient * @dev Address array and amount array are 1:1 and are in order. * @param _recipients array of recipient addresses * @param _amounts array of token amounts * @return true/false */ function multiTransfer(address[] calldata _recipients, uint256[] calldata _amounts) external returns (bool) { require(_recipients.length == _amounts.length, Errors.INPUT_LENGTH_MISMATCH); for (uint256 i = 0; i < _recipients.length; i++) { require(transfer(_recipients[i], _amounts[i]), Errors.MULTI_TRANSFER_FAILED); } return true; } /** * @notice Get price per share * @dev Return value will be in token defined decimals. */ function pricePerShare() public view returns (uint256) { if (totalSupply() == 0 || totalValue() == 0) { return convertFrom18(1e18); } return (totalValue() * 1e18) / totalSupply(); } /** * @notice Calculate how much shares user will get for given amount. Also return externalDepositFee if any. * @param _amount Collateral amount * @return _shares Amount of share that user will get */ function calculateMintage(uint256 _amount) public view returns (uint256 _shares) { require(_amount != 0, Errors.INVALID_COLLATERAL_AMOUNT); uint256 _externalDepositFee = (_amount * IPoolAccountant(poolAccountant).externalDepositFee()) / MAX_BPS; _shares = _calculateShares(_amount - _externalDepositFee); } /// @dev Convert from 18 decimals to token defined decimals. function convertFrom18(uint256 _amount) public view virtual returns (uint256) { return _amount / decimalConversionFactor; } /// @dev Returns the token stored in the pool. It will be in token defined decimals. function tokensHere() public view virtual returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Returns sum of token locked in other contracts and token stored in the pool. * Default tokensHere. It will be in token defined decimals. */ function totalValue() public view virtual returns (uint256); /** * @dev Hook that is called just before burning tokens. This withdraw collateral from withdraw queue * @param _share Pool share in 18 decimals */ function _beforeBurning(uint256 _share) internal virtual returns (uint256) {} /** * @dev Hook that is called just after burning tokens. * @param _amount Collateral amount in collateral token defined decimals. */ function _afterBurning(uint256 _amount) internal virtual returns (uint256) { token.safeTransfer(_msgSender(), _amount); return _amount; } /** * @dev Hook that is called just before minting new tokens. To be used i.e. * if the deposited amount is to be transferred from user to this contract. * @param _amount Collateral amount in collateral token defined decimals. */ function _beforeMinting(uint256 _amount) internal virtual { token.safeTransferFrom(_msgSender(), address(this), _amount); } /** * @dev Hook that is called just after minting new tokens. To be used i.e. * if the deposited amount is to be transferred to a different contract. * @param _amount Collateral amount in collateral token defined decimals. */ function _afterMinting(uint256 _amount) internal virtual {} /// @dev Update pool rewards of sender and receiver during transfer. function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { if (poolRewards != address(0)) { IPoolRewards(poolRewards).updateReward(sender); IPoolRewards(poolRewards).updateReward(recipient); } super._transfer(sender, recipient, amount); } /** * @dev Calculate shares to mint/burn based on the current share price and given amount. * @param _amount Collateral amount in collateral token defined decimals. * @return share amount in 18 decimal */ function _calculateShares(uint256 _amount) internal view returns (uint256) { uint256 _share = ((_amount * 1e18) / pricePerShare()); return _amount > ((_share * pricePerShare()) / 1e18) ? _share + 1 : _share; } /// @notice claim rewards of account function _claimRewards(address _account) internal { if (poolRewards != address(0)) { IPoolRewards(poolRewards).claimReward(_account); } } function _updateRewards(address _account) internal { if (poolRewards != address(0)) { IPoolRewards(poolRewards).updateReward(_account); } } /// @dev Deposit incoming token and mint pool token i.e. shares. function _deposit(uint256 _amount) internal virtual { uint256 _shares = calculateMintage(_amount); _beforeMinting(_amount); _mint(_msgSender(), _shares); _afterMinting(_amount); emit Deposit(_msgSender(), _shares, _amount); } /// @dev Deposit token and claim rewards if any function _depositAndClaim(uint256 _amount) internal { _claimRewards(_msgSender()); _deposit(_amount); } /// @dev Burns shares and returns the collateral value, after fee, of those. function _withdraw(uint256 _shares) internal virtual { require(_shares != 0, Errors.INVALID_SHARE_AMOUNT); if (withdrawFee == 0 || _feeWhitelist.contains(_msgSender())) { _withdrawWithoutFee(_shares); } else { uint256 _fee = (_shares * withdrawFee) / MAX_BPS; uint256 _sharesAfterFee = _shares - _fee; uint256 _amountWithdrawn = _beforeBurning(_sharesAfterFee); // Recalculate proportional share on actual amount withdrawn uint256 _proportionalShares = _calculateShares(_amountWithdrawn); // Using convertFrom18() to avoid dust. // Pool share token is in 18 decimal and collateral token decimal is <=18. // Anything less than 10**(18-collateralTokenDecimal) is dust. if (convertFrom18(_proportionalShares) < convertFrom18(_sharesAfterFee)) { // Recalculate shares to withdraw, fee and shareAfterFee _shares = (_proportionalShares * MAX_BPS) / (MAX_BPS - withdrawFee); _fee = _shares - _proportionalShares; _sharesAfterFee = _proportionalShares; } _burn(_msgSender(), _sharesAfterFee); _transfer(_msgSender(), feeCollector, _fee); _afterBurning(_amountWithdrawn); emit Withdraw(_msgSender(), _shares, _amountWithdrawn); } } /// @dev Withdraw collateral and claim rewards if any function _withdrawAndClaim(uint256 _shares) internal { _claimRewards(_msgSender()); _withdraw(_shares); } /// @dev Burns shares and returns the collateral value of those. function _withdrawWithoutFee(uint256 _shares) internal { uint256 _amountWithdrawn = _beforeBurning(_shares); uint256 _proportionalShares = _calculateShares(_amountWithdrawn); if (convertFrom18(_proportionalShares) < convertFrom18(_shares)) { _shares = _proportionalShares; } _burn(_msgSender(), _shares); _afterBurning(_amountWithdrawn); emit Withdraw(_msgSender(), _shares, _amountWithdrawn); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract PoolStorageV1 { IERC20 public token; // Collateral token address public poolAccountant; // PoolAccountant address address public poolRewards; // PoolRewards contract address address private feeWhitelistObsolete; // Obsolete in favor of AddressSet of feeWhitelist address private keepersObsolete; // Obsolete in favor of AddressSet of keepers address private maintainersObsolete; // Obsolete in favor of AddressSet of maintainers address public feeCollector; // Fee collector address uint256 public withdrawFee; // Withdraw fee for this pool uint256 public decimalConversionFactor; // It can be used in converting value to/from 18 decimals bool internal withdrawInETH; // This flag will be used by VETH pool as switch to withdraw ETH or WETH } contract PoolStorageV2 is PoolStorageV1 { EnumerableSet.AddressSet internal _feeWhitelist; // List of addresses whitelisted for feeless withdraw EnumerableSet.AddressSet internal _keepers; // List of keeper addresses EnumerableSet.AddressSet internal _maintainers; // List of maintainer addresses } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./VPoolBase.sol"; //solhint-disable no-empty-blocks contract VPool is VPoolBase { string public constant VERSION = "4.0.0"; constructor( string memory _name, string memory _symbol, address _token ) VPoolBase(_name, _symbol, _token) {} function initialize( string memory _name, string memory _symbol, address _token, address _poolAccountant ) public initializer { _initializeBase(_name, _symbol, _token, _poolAccountant); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "./Errors.sol"; import "./PoolShareToken.sol"; import "../interfaces/vesper/IStrategy.sol"; abstract contract VPoolBase is PoolShareToken { using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector); event UpdatedPoolRewards(address indexed previousPoolRewards, address indexed newPoolRewards); event UpdatedWithdrawFee(uint256 previousWithdrawFee, uint256 newWithdrawFee); constructor( string memory _name, string memory _symbol, address _token // solhint-disable-next-line no-empty-blocks ) PoolShareToken(_name, _symbol, _token) {} /// @dev Equivalent to constructor for proxy. It can be called only once per proxy. function _initializeBase( string memory _name, string memory _symbol, address _token, address _poolAccountant ) internal initializer { require(_poolAccountant != address(0), Errors.INPUT_ADDRESS_IS_ZERO); _initializePool(_name, _symbol, _token); _initializeGoverned(); require(_keepers.add(_msgSender()), Errors.ADD_IN_LIST_FAILED); require(_maintainers.add(_msgSender()), Errors.ADD_IN_LIST_FAILED); poolAccountant = _poolAccountant; } modifier onlyKeeper() { require(_keepers.contains(_msgSender()), "not-a-keeper"); _; } modifier onlyMaintainer() { require(_maintainers.contains(_msgSender()), "not-a-maintainer"); _; } ////////////////////////////// Only Governor ////////////////////////////// /** * @notice Migrate existing strategy to new strategy. * @dev Migrating strategy aka old and new strategy should be of same type. * @param _old Address of strategy being migrated * @param _new Address of new strategy */ function migrateStrategy(address _old, address _new) external onlyGovernor { require( IStrategy(_new).pool() == address(this) && IStrategy(_old).pool() == address(this), Errors.INVALID_STRATEGY ); IPoolAccountant(poolAccountant).migrateStrategy(_old, _new); IStrategy(_old).migrate(_new); } /** * @notice Update fee collector address for this pool * @param _newFeeCollector new fee collector address */ function updateFeeCollector(address _newFeeCollector) external onlyGovernor { require(_newFeeCollector != address(0), Errors.INPUT_ADDRESS_IS_ZERO); emit UpdatedFeeCollector(feeCollector, _newFeeCollector); feeCollector = _newFeeCollector; } /** * @notice Update pool rewards address for this pool * @param _newPoolRewards new pool rewards address */ function updatePoolRewards(address _newPoolRewards) external onlyGovernor { require(_newPoolRewards != address(0), Errors.INPUT_ADDRESS_IS_ZERO); emit UpdatedPoolRewards(poolRewards, _newPoolRewards); poolRewards = _newPoolRewards; } /** * @notice Update withdraw fee for this pool * @dev Format: 1500 = 15% fee, 100 = 1% * @param _newWithdrawFee new withdraw fee */ function updateWithdrawFee(uint256 _newWithdrawFee) external onlyGovernor { require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET); require(_newWithdrawFee <= MAX_BPS, Errors.FEE_LIMIT_REACHED); emit UpdatedWithdrawFee(withdrawFee, _newWithdrawFee); withdrawFee = _newWithdrawFee; } ///////////////////////////// Only Keeper /////////////////////////////// function pause() external onlyKeeper { _pause(); } function unpause() external onlyKeeper { _unpause(); } function shutdown() external onlyKeeper { _shutdown(); } function open() external onlyKeeper { _open(); } /// @notice Return list of whitelisted addresses function feeWhitelist() external view returns (address[] memory) { return _feeWhitelist.values(); } function isFeeWhitelisted(address _address) external view returns (bool) { return _feeWhitelist.contains(_address); } /** * @notice Add given address in feeWhitelist. * @param _addressToAdd Address to add in feeWhitelist. */ function addToFeeWhitelist(address _addressToAdd) external onlyKeeper { require(_feeWhitelist.add(_addressToAdd), Errors.ADD_IN_LIST_FAILED); } /** * @notice Remove given address from feeWhitelist. * @param _addressToRemove Address to remove from feeWhitelist. */ function removeFromFeeWhitelist(address _addressToRemove) external onlyKeeper { require(_feeWhitelist.remove(_addressToRemove), Errors.REMOVE_FROM_LIST_FAILED); } /// @notice Return list of keepers function keepers() external view returns (address[] memory) { return _keepers.values(); } function isKeeper(address _address) external view returns (bool) { return _keepers.contains(_address); } /** * @notice Add given address in keepers list. * @param _keeperAddress keeper address to add. */ function addKeeper(address _keeperAddress) external onlyKeeper { require(_keepers.add(_keeperAddress), Errors.ADD_IN_LIST_FAILED); } /** * @notice Remove given address from keepers list. * @param _keeperAddress keeper address to remove. */ function removeKeeper(address _keeperAddress) external onlyKeeper { require(_keepers.remove(_keeperAddress), Errors.REMOVE_FROM_LIST_FAILED); } /// @notice Return list of maintainers function maintainers() external view returns (address[] memory) { return _maintainers.values(); } function isMaintainer(address _address) external view returns (bool) { return _maintainers.contains(_address); } /** * @notice Add given address in maintainers list. * @param _maintainerAddress maintainer address to add. */ function addMaintainer(address _maintainerAddress) external onlyKeeper { require(_maintainers.add(_maintainerAddress), Errors.ADD_IN_LIST_FAILED); } /** * @notice Remove given address from maintainers list. * @param _maintainerAddress maintainer address to remove. */ function removeMaintainer(address _maintainerAddress) external onlyKeeper { require(_maintainers.remove(_maintainerAddress), Errors.REMOVE_FROM_LIST_FAILED); } /////////////////////////////////////////////////////////////////////////// /** * @dev Strategy call this in regular interval. * @param _profit yield generated by strategy. Strategy get performance fee on this amount * @param _loss Reduce debt ,also reduce debtRatio, increase loss in record. * @param _payback strategy willing to payback outstanding above debtLimit. no performance fee on this amount. * when governance has reduced debtRatio of strategy, strategy will report profit and payback amount separately. */ function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) public virtual { (uint256 _actualPayback, uint256 _creditLine, uint256 _interestFee) = IPoolAccountant(poolAccountant).reportEarning(_msgSender(), _profit, _loss, _payback); uint256 _totalPayback = _profit + _actualPayback; // After payback, if strategy has credit line available then send more fund to strategy // If payback is more than available credit line then get fund from strategy if (_totalPayback < _creditLine) { token.safeTransfer(_msgSender(), _creditLine - _totalPayback); } else if (_totalPayback > _creditLine) { token.safeTransferFrom(_msgSender(), address(this), _totalPayback - _creditLine); } // Mint interest fee worth shares at feeCollector address if (_interestFee != 0) { _mint(IStrategy(_msgSender()).feeCollector(), _calculateShares(_interestFee)); } } /** * @notice Report loss outside of rebalance activity. * @dev Some strategies pay deposit fee thus realizing loss at deposit. * For example: Curve's 3pool has some slippage due to deposit of one asset in 3pool. * Strategy may want report this loss instead of waiting for next rebalance. * @param _loss Loss that strategy want to report */ function reportLoss(uint256 _loss) external { if (_loss != 0) { IPoolAccountant(poolAccountant).reportLoss(_msgSender(), _loss); } } /** * @dev Transfer given ERC20 token to feeCollector * @param _fromToken Token address to sweep */ function sweepERC20(address _fromToken) external virtual onlyKeeper { require(_fromToken != address(token), Errors.NOT_ALLOWED_TO_SWEEP); require(feeCollector != address(0), Errors.FEE_COLLECTOR_NOT_SET); IERC20(_fromToken).safeTransfer(feeCollector, IERC20(_fromToken).balanceOf(address(this))); } /** * @notice Get available credit limit of strategy. This is the amount strategy can borrow from pool * @dev Available credit limit is calculated based on current debt of pool and strategy, current debt limit of pool and strategy. * credit available = min(pool's debt limit, strategy's debt limit, max debt per rebalance) * when some strategy do not pay back outstanding debt, this impact credit line of other strategy if totalDebt of pool >= debtLimit of pool * @param _strategy Strategy address */ function availableCreditLimit(address _strategy) external view returns (uint256) { return IPoolAccountant(poolAccountant).availableCreditLimit(_strategy); } /** * @notice Debt above current debt limit * @param _strategy Address of strategy */ function excessDebt(address _strategy) external view returns (uint256) { return IPoolAccountant(poolAccountant).excessDebt(_strategy); } function getStrategies() public view returns (address[] memory) { return IPoolAccountant(poolAccountant).getStrategies(); } function getWithdrawQueue() public view returns (address[] memory) { return IPoolAccountant(poolAccountant).getWithdrawQueue(); } function strategy(address _strategy) public view returns ( bool _active, uint256 _interestFee, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio, uint256 _externalDepositFee ) { return IPoolAccountant(poolAccountant).strategy(_strategy); } /// @notice Get total debt of pool function totalDebt() external view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebt(); } /** * @notice Get total debt of given strategy * @param _strategy Strategy address */ function totalDebtOf(address _strategy) public view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebtOf(_strategy); } /// @notice Get total debt ratio. Total debt ratio helps us keep buffer in pool function totalDebtRatio() external view returns (uint256) { return IPoolAccountant(poolAccountant).totalDebtRatio(); } /// @dev Returns total value of vesper pool, in terms of collateral token function totalValue() public view override returns (uint256) { return IPoolAccountant(poolAccountant).totalDebt() + tokensHere(); } function _withdrawCollateral(uint256 _amount) internal virtual { // Withdraw amount from queue uint256 _debt; uint256 _balanceAfter; uint256 _balanceBefore; uint256 _amountWithdrawn; uint256 _totalAmountWithdrawn; address[] memory _withdrawQueue = getWithdrawQueue(); uint256 _len = _withdrawQueue.length; for (uint256 i; i < _len; i++) { uint256 _amountNeeded = _amount - _totalAmountWithdrawn; address _strategy = _withdrawQueue[i]; _debt = totalDebtOf(_strategy); if (_debt == 0) { continue; } if (_amountNeeded > _debt) { // Should not withdraw more than current debt of strategy. _amountNeeded = _debt; } _balanceBefore = tokensHere(); //solhint-disable no-empty-blocks try IStrategy(_strategy).withdraw(_amountNeeded) {} catch { continue; } _balanceAfter = tokensHere(); _amountWithdrawn = _balanceAfter - _balanceBefore; // Adjusting totalDebt. Assuming that during next reportEarning(), strategy will report loss if amountWithdrawn < _amountNeeded IPoolAccountant(poolAccountant).decreaseDebt(_strategy, _amountWithdrawn); _totalAmountWithdrawn += _amountWithdrawn; if (_totalAmountWithdrawn >= _amount) { // withdraw done break; } } } /** * @dev Before burning hook. * withdraw amount from strategies */ function _beforeBurning(uint256 _share) internal override returns (uint256 actualWithdrawn) { uint256 _amount = (_share * pricePerShare()) / 1e18; uint256 _balanceNow = tokensHere(); if (_amount > _balanceNow) { _withdrawCollateral(_amount - _balanceNow); _balanceNow = tokensHere(); } actualWithdrawn = _balanceNow < _amount ? _balanceNow : _amount; require(actualWithdrawn != 0, Errors.INVALID_COLLATERAL_AMOUNT); } }
Return list of maintainers
function maintainers() external view returns (address[] memory) { return _maintainers.values(); }
416,798
./partial_match/4/0x748d2AC32B0A5efE67Bd13D3B9657716aCedbffa/sources/ToshimonMinter.sol
Creates a new token type and assigns _initialSupply to an address _maxSupply max supply allowed _initialSupply Optional amount to supply the first owner _uri Optional URI for this token type _data Optional data to pass if receiver is contract return The newly created token ID/
function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyWhitelistAdmin returns (uint256 tokenId) { require( _initialSupply <= _maxSupply, 'Initial supply cannot be more than max supply' ); uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = msg.sender; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data); tokenSupply[_id] = _initialSupply; tokenMaxSupply[_id] = _maxSupply; return _id; }
8,524,336
./full_match/80001/0xc7b2dd5cba7Fe8538F240B217714401c5Aa4BebF/sources/project_/contracts/libs/Product020802Lib.sol
if (endorsementParams.requestedCoverageStartDate != 0) { uint256 coverageStartDate = computeCoverageStartDate( endorsementParams.requestedCoverageStartDate, allPolicies[endorsementParams.onChainPolicyId].subscriptionDate, 1 ); allPolicies[endorsementParams.onChainPolicyId].coverageStartDate = coverageStartDate; allPolicies[endorsementParams.onChainPolicyId].expirationDate = coverageStartDate.addYears( 1, 1 ); } if (bytes(endorsementParams.package).length != 0) { allPolicies[endorsementParams.onChainPolicyId].package = endorsementParams.package; } if (endorsementParams.exposure.vehicleType != 0) { allPolicies[endorsementParams.onChainPolicyId].exposure.vehicleType = endorsementParams.exposure.vehicleType; } if (bytes(endorsementParams.exposure.brand).length != 0) { allPolicies[endorsementParams.onChainPolicyId].exposure.brand = endorsementParams.exposure.brand; } if (bytes(endorsementParams.exposure.model).length != 0) { allPolicies[endorsementParams.onChainPolicyId].exposure.model = endorsementParams.exposure.model; } if (endorsementParams.exposure.purchaseDate != 0) { allPolicies[endorsementParams.onChainPolicyId].exposure.purchaseDate = endorsementParams .exposure .purchaseDate; } if (endorsementParams.exposure.purchasePrice != 0) { allPolicies[endorsementParams.onChainPolicyId].exposure.purchasePrice = endorsementParams .exposure .purchasePrice; } if (endorsementParams.exposure.usage != 0) { allPolicies[endorsementParams.onChainPolicyId].exposure.usage = endorsementParams.exposure.usage; } if (endorsementParams.exposure.householdSize != 0) { allPolicies[endorsementParams.onChainPolicyId].exposure.householdSize = endorsementParams .exposure .householdSize; } if (endorsementParams.exposure.maxSpeed != 0) { allPolicies[endorsementParams.onChainPolicyId].exposure.maxSpeed = endorsementParams.exposure.maxSpeed; } if (endorsementParams.split != 0) { allPolicies[endorsementParams.onChainPolicyId].split = endorsementParams.split; } if (bytes(endorsementParams.commonSensitiveData).length != 0) { allPolicies[endorsementParams.onChainPolicyId].commonSensitiveData = endorsementParams.commonSensitiveData; } if (bytes(endorsementParams.claimsAdminSensitiveData).length != 0) { allPolicies[endorsementParams.onChainPolicyId].claimsAdminSensitiveData = endorsementParams .claimsAdminSensitiveData; } if (bytes(endorsementParams.policiesAdminSensitiveData).length != 0) { allPolicies[endorsementParams.onChainPolicyId].policiesAdminSensitiveData = endorsementParams .policiesAdminSensitiveData; } if (bytes(endorsementParams.distributorSensitiveData).length != 0) { allPolicies[endorsementParams.onChainPolicyId].distributorSensitiveData = endorsementParams .distributorSensitiveData; } if (bytes(endorsementParams.insurerSensitiveData).length != 0) { allPolicies[endorsementParams.onChainPolicyId].insurerSensitiveData = endorsementParams.insurerSensitiveData; } if (endorsementParams.updateSelectedOptions) { allPolicies[endorsementParams.onChainPolicyId].selectedOptions = endorsementParams.selectedOptions; } if (endorsementParams.updateCoverages) { delete allPolicies[endorsementParams.onChainPolicyId].selectedCoverages; for (uint256 index = 0; index < endorsementParams.selectedCoverages.length; index++) { allPolicies[endorsementParams.onChainPolicyId].selectedCoverages.push( endorsementParams.selectedCoverages[index] ); } } allPolicies[endorsementParams.onChainPolicyId].operationType = endorsementParams.operationType; allPolicies[endorsementParams.onChainPolicyId].operationEffectiveDate = block.timestamp;
function endorsePolicy( Product020802Lib.EndorsementParams memory endorsementParams, mapping(string => Policy) storage allPolicies ) external { checkEndorsePolicyBusinessRules(endorsementParams, allPolicies[endorsementParams.onChainPolicyId].operationType ); }
876,386
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // SPDX-License-Identifier: MIT 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 Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { struct Item { uint256 id; address creator; string uri; uint8 royalties ; } /** * @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); function items(uint256 _tokenId) external view returns (Item memory); /** * @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; } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @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 Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } 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; } abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } 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); } } } } contract EscrowUpgradeable is Initializable, OwnableUpgradeable { function initialize() public virtual initializer { __Escrow_init(); } function __Escrow_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Escrow_init_unchained(); } function __Escrow_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; using AddressUpgradeable for address payable; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private _deposits; function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public virtual payable onlyOwner { uint256 amount = msg.value; _deposits[payee] = _deposits[payee].add(amount); emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee, forwarding all gas to the * recipient. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee) public virtual onlyOwner { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.sendValue(payment); emit Withdrawn(payee, payment); } uint256[49] private __gap; } abstract contract PullPaymentUpgradeable is Initializable { EscrowUpgradeable private _escrow; function __PullPayment_init() internal initializer { __PullPayment_init_unchained(); } function __PullPayment_init_unchained() internal initializer { _escrow = new EscrowUpgradeable(); _escrow.initialize(); } /** * @dev Withdraw accumulated payments, forwarding all gas to the recipient. * * Note that _any_ account can call this function, not just the `payee`. * This means that contracts unaware of the `PullPayment` protocol can still * receive funds this way, by having a separate account call * {withdrawPayments}. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee Whose payments will be withdrawn. */ function withdrawPayments(address payable payee) public virtual { _escrow.withdraw(payee); } /** * @dev Returns the payments owed to an address. * @param dest The creditor's address. */ function payments(address dest) public view returns (uint256) { return _escrow.depositsOf(dest); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * Funds sent in this way are stored in an intermediate {Escrow} contract, so * there is no danger of them being spent before withdrawal. * * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function _asyncTransfer(address dest, uint256 amount) internal virtual { _escrow.deposit{ value: amount }(dest); } uint256[49] private __gap; } interface ISendValueProxy { function sendValue(address payable _to) external payable; } /** * @dev Contract that attempts to send value to an address. */ contract SendValueProxy is ISendValueProxy { /** * @dev Send some wei to the address. * @param _to address to send some value to. */ function sendValue(address payable _to) external override payable { // Note that `<address>.transfer` limits gas sent to receiver. It may // not support complex contract operations in the future. _to.transfer(msg.value); } } /** * @dev Contract with a ISendValueProxy that will catch reverts when attempting to transfer funds. */ contract MaybeSendValue { SendValueProxy proxy; // constructor() internal { // proxy = new SendValueProxy(); // } constructor() public { proxy = new SendValueProxy(); } /** * @dev Maybe send some wei to the address via a proxy. Returns true on success and false if transfer fails. * @param _to address to send some value to. * @param _value uint256 amount to send. */ function maybeSendValue(address payable _to, uint256 _value) internal returns (bool) { // Call sendValue on the proxy contract and forward the mesg.value. /* solium-disable-next-line */ (bool success,) = address(proxy).call{value : _value}( abi.encodeWithSignature("sendValue(address)", _to) ); return success; } } /** * @dev Contract to make payments. If a direct transfer fails, it will store the payment in escrow until the address decides to pull the payment. */ contract SendValueOrEscrow is MaybeSendValue, PullPaymentUpgradeable { ///////////////////////////////////////////////////////////////////////// // Events ///////////////////////////////////////////////////////////////////////// event SendValue(address indexed _payee, uint256 amount); ///////////////////////////////////////////////////////////////////////// // sendValueOrEscrow ///////////////////////////////////////////////////////////////////////// /** * @dev Send some value to an address. * @param _to address to send some value to. * @param _value uint256 amount to send. */ function sendValueOrEscrow(address payable _to, uint256 _value) internal { // attempt to make the transfer _to.transfer(_value); // if it fails, transfer it into escrow for them to redeem at their will. // if (!successfulTransfer) { // _asyncTransfer(_to, _value); // } emit SendValue(_to, _value); } function sendViaTransfer(address payable _to, uint256 _value) internal { // This function is no longer recommended for sending Ether. _to.transfer(_value); } function sendViaSend(address payable _to, uint256 _value) internal { // Send returns a boolean value indicating success or failure. // This function is not recommended for sending Ether. bool sent = _to.send(_value); require(sent, "Failed to send Ether"); } function sendViaCall(address payable _to, uint256 _value) internal { // Call returns a boolean value indicating success or failure. // This is the current recommended method to use. (bool sent, bytes memory data) = _to.call{value: _value}(""); require(sent, "Failed to send Ether"); } } /** * @title Payments contract for SuperRare Marketplaces. */ contract Payments is SendValueOrEscrow { using SafeMathUpgradeable for uint256; using SafeMathUpgradeable for uint8; ///////////////////////////////////////////////////////////////////////// // refund ///////////////////////////////////////////////////////////////////////// /** * @dev Internal function to refund an address. Typically for canceled bids or offers. * Requirements: * * - _payee cannot be the zero address * * @param _marketplacePercentage uint8 percentage of the fee for the marketplace. * @param _amount uint256 value to be split. * @param _payee address seller of the token. */ function refund( uint8 _marketplacePercentage, address payable _payee, uint256 _amount ) internal { require( _payee != address(0), "refund::no payees can be the zero address" ); if (_amount > 0) { SendValueOrEscrow.sendValueOrEscrow( _payee, _amount.add( calcPercentagePayment(_amount, _marketplacePercentage) ) ); } } ///////////////////////////////////////////////////////////////////////// // payout ///////////////////////////////////////////////////////////////////////// /** * @dev Internal function to pay the seller, creator, and maintainer. * Requirements: * * - _marketplacePercentage + _royaltyPercentage + _primarySalePercentage <= 100 * - no payees can be the zero address * * @param _amount uint256 value to be split. * @param _isPrimarySale bool of whether this is a primary sale. * @param _marketplacePercentage uint8 percentage of the fee for the marketplace. * @param _royaltyPercentage uint8 percentage of the fee for the royalty. * @param _primarySalePercentage uint8 percentage primary sale fee for the marketplace. * @param _payee address seller of the token. * @param _marketplacePayee address seller of the token. * @param _royaltyPayee address seller of the token. * @param _primarySalePayee address seller of the token. */ function payout( uint256 _amount, bool _isPrimarySale, uint8 _marketplacePercentage, uint8 _royaltyPercentage, uint8 _primarySalePercentage, address payable _payee, address payable _marketplacePayee, address payable _royaltyPayee, address payable _primarySalePayee ) internal { require( _marketplacePercentage <= 100, "payout::marketplace percentage cannot be above 100" ); require( _royaltyPercentage.add(_primarySalePercentage) <= 100, "payout::percentages cannot go beyond 100" ); require( _payee != address(0) && _primarySalePayee != address(0) && _marketplacePayee != address(0) && _royaltyPayee != address(0), "payout::no payees can be the zero address" ); // Note:: Solidity is kind of terrible in that there is a limit to local // variables that can be put into the stack. The real pain is that // one can put structs, arrays, or mappings into memory but not basic // data types. Hence our payments array that stores these values. uint256[4] memory payments; // uint256 marketplacePayment payments[0] = calcPercentagePayment(_amount, _marketplacePercentage); // uint256 royaltyPayment payments[1] = calcRoyaltyPayment( _isPrimarySale, _amount, _royaltyPercentage ); // uint256 primarySalePayment payments[2] = calcPrimarySalePayment( _isPrimarySale, _amount, _primarySalePercentage ); // uint256 payeePayment payments[3] = _amount.sub(payments[1]).sub(payments[2]); // marketplacePayment if (payments[0] > 0) { SendValueOrEscrow.sendValueOrEscrow(_marketplacePayee, payments[0]); // SendValueOrEscrow.sendViaCall(_marketplacePayee, payments[0]-1); } // royaltyPayment if (payments[1] > 0) { SendValueOrEscrow.sendValueOrEscrow(_royaltyPayee, payments[1]); // SendValueOrEscrow.sendViaCall(_royaltyPayee, payments[1]-1); } // primarySalePayment if (payments[2] > 0) { SendValueOrEscrow.sendValueOrEscrow(_primarySalePayee, payments[2]); // SendValueOrEscrow.sendViaCall(_primarySalePayee, payments[2]-1); } // payeePayment if (payments[3] > 0) { SendValueOrEscrow.sendValueOrEscrow(_payee, payments[3]); // SendValueOrEscrow.sendViaCall(_payee, payments[3]-1); } } function simplePayout( uint256 _amount, address payable _payee ) internal { require( _payee != address(0), "payout::no payees can be the zero address" ); SendValueOrEscrow.sendValueOrEscrow(_payee, _amount); } ///////////////////////////////////////////////////////////////////////// // calcRoyaltyPayment ///////////////////////////////////////////////////////////////////////// /** * @dev Private function to calculate Royalty amount. * If primary sale: 0 * If no royalty percentage: 0 * otherwise: royalty in wei * @param _isPrimarySale bool of whether this is a primary sale * @param _amount uint256 value to be split * @param _percentage uint8 royalty percentage * @return uint256 wei value owed for royalty */ function calcRoyaltyPayment( bool _isPrimarySale, uint256 _amount, uint8 _percentage ) private pure returns (uint256) { if (_isPrimarySale) { return 0; } return calcPercentagePayment(_amount, _percentage); } ///////////////////////////////////////////////////////////////////////// // calcPrimarySalePayment ///////////////////////////////////////////////////////////////////////// /** * @dev Private function to calculate PrimarySale amount. * If not primary sale: 0 * otherwise: primary sale in wei+ * @param _isPrimarySale bool of whether this is a primary sale * @param _amount uint256 value to be split * @param _percentage uint8 royalty percentage * @return uint256 wei value owed for primary sale */ function calcPrimarySalePayment( bool _isPrimarySale, uint256 _amount, uint8 _percentage ) private pure returns (uint256) { if (_isPrimarySale) { return calcPercentagePayment(_amount, _percentage); } return 0; } ///////////////////////////////////////////////////////////////////////// // calcPercentagePayment ///////////////////////////////////////////////////////////////////////// /** * @dev Internal function to calculate percentage value. * @param _amount uint256 wei value * @param _percentage uint8 percentage * @return uint256 wei value based on percentage. */ function calcPercentagePayment(uint256 _amount, uint8 _percentage) internal pure returns (uint256) { return _amount.mul(_percentage).div(100); } } /** * @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); } contract MarketPlace is OwnableUpgradeable, Payments { using SafeMathUpgradeable for uint256; // rougeeToken IERC20 refference IERC20 public rougeeToken; ///////////////////////////////////////////////////////////////////////// // Structs ///////////////////////////////////////////////////////////////////////// // The active bid for a given token, contains the bidder, the marketplace fee at the time of the bid, and the amount of wei placed on the token struct ActiveBid { address payable bidder; uint8 marketplaceFee; uint256 amount; } // The sale price for a given token containing the seller and the amount of wei to be sold for struct SalePrice { address payable seller; uint256 amount; } // Mapping from ERC721 contract to mapping of tokenId to sale price. mapping(address => mapping(uint256 => SalePrice)) private tokenPrices; // Mapping from ERC721 contract to mapping of tokenId to sale price using Token Rougee mapping(address => mapping(uint256 => SalePrice)) private tokenPricesRougee; // Mapping of ERC721 contract to mapping of token ID to the current bid amount. mapping(address => mapping(uint256 => ActiveBid)) private tokenCurrentBids; // Mapping from ERC721 contract to mapping of tokenId to current bid using Token Rougee mapping(address => mapping(uint256 => ActiveBid)) private tokenCurrentBidsRougee; // A minimum increase in bid amount when out bidding someone. uint8 public minimumBidIncreasePercentage; // 10 = 10% ///////////////////////////////////////////////////////////////////////////// // Events ///////////////////////////////////////////////////////////////////////////// event Sold( address indexed _originContract, address indexed _buyer, address indexed _seller, uint256 _amount, uint256 _tokenId ); event SetSalePrice( address indexed _originContract, uint256 _amount, uint256 _tokenId ); event Bid( address indexed _originContract, address indexed _bidder, uint256 _amount, uint256 _tokenId ); event AcceptBid( address indexed _originContract, address indexed _bidder, address indexed _seller, uint256 _amount, uint256 _tokenId ); event CancelBid( address indexed _originContract, address indexed _bidder, uint256 _amount, uint256 _tokenId ); ///////////////////////////////////////////////////////////////////////// // Constructor ///////////////////////////////////////////////////////////////////////// /** * @dev Initializes the contract setting the market settings and creator royalty interfaces. */ constructor() public { minimumBidIncreasePercentage = 1; __Ownable_init(); rougeeToken = IERC20(0xA1c7D450130bb77c6a23DdFAeCbC4a060215384b); } /** * @dev Admin function to set the minimum bid increase percentage. * Rules: * - only owner * @param _percentage uint8 to set as the new percentage. */ function setMinimumBidIncreasePercentage(uint8 _percentage) public onlyOwner { minimumBidIncreasePercentage = _percentage; } ///////////////////////////////////////////////////////////////////////// // Modifiers (as functions) ///////////////////////////////////////////////////////////////////////// /** * @dev Checks that the token owner is approved for the ERC721Market * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token */ function ownerMustHaveMarketplaceApproved( address _originContract, uint256 _tokenId ) internal view { IERC721 erc721 = IERC721(_originContract); address owner = erc721.ownerOf(_tokenId); require( erc721.isApprovedForAll(owner, address(this)), "owner must have approved contract" ); } /** * @dev Checks that the token is owned by the sender * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token */ function senderMustBeTokenOwner(address _originContract, uint256 _tokenId) internal view { IERC721 erc721 = IERC721(_originContract); require( erc721.ownerOf(_tokenId) == msg.sender, "sender must be the token owner" ); } ///////////////////////////////////////////////////////////////////////// // setSalePrice ///////////////////////////////////////////////////////////////////////// /** * @dev Set the token for sale. The owner of the token must be the sender and have the marketplace approved. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token * @param _amount uint256 wei value that the item is for sale */ function setSalePrice( address _originContract, uint256 _tokenId, uint256 _amount ) external { // The owner of the token must have the marketplace approved ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // The sender must be the token owner senderMustBeTokenOwner(_originContract, _tokenId); if (_amount == 0) { // Set not for sale and exit _resetTokenPrice(_originContract, _tokenId); emit SetSalePrice(_originContract, _amount, _tokenId); return; } tokenPrices[_originContract][_tokenId] = SalePrice(msg.sender, _amount); emit SetSalePrice(_originContract, _amount, _tokenId); } ///////////////////////////////////////////////////////////////////////// // setSalePrice For rougeeToken ///////////////////////////////////////////////////////////////////////// /** * @dev Set the token for sale. The owner of the token must be the sender and have the marketplace approved. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token * @param _amount uint256 wei value that the item is for sale */ function setSalePriceForRougee( address _originContract, uint256 _tokenId, uint256 _amount ) external { // The owner of the token must have the marketplace approved ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // The sender must be the token owner senderMustBeTokenOwner(_originContract, _tokenId); if (_amount == 0) { // Set not for sale and exit _resetTokenPrice(_originContract, _tokenId); emit SetSalePrice(_originContract, _amount, _tokenId); return; } tokenPricesRougee[_originContract][_tokenId] = SalePrice(msg.sender, _amount); emit SetSalePrice(_originContract, _amount, _tokenId); } ///////////////////////////////////////////////////////////////////////// // safeBuy ///////////////////////////////////////////////////////////////////////// /** * @dev Purchase the token with the expected amount. The current token owner must have the marketplace approved. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token * @param _amount uint256 wei amount expecting to purchase the token for. */ function safeBuy( address _originContract, uint256 _tokenId, uint256 _amount ) external payable { // Make sure the tokenPrice is the expected amount require( tokenPrices[_originContract][_tokenId].amount == _amount, "safeBuy::Purchase amount must equal expected amount" ); buy(_originContract, _tokenId); } ///////////////////////////////////////////////////////////////////////// // safeBuyUsingRougee ///////////////////////////////////////////////////////////////////////// /** * @dev Purchase the token with the expected amount. The current token owner must have the marketplace approved. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token * @param _amount uint256 wei amount expecting to purchase the token for. */ function safeBuyUsingRougee( address _originContract, uint256 _tokenId, uint256 _amount ) external payable { // Make sure the tokenPrice is the expected amount require( tokenPricesRougee[_originContract][_tokenId].amount == _amount, "safeBuy::Purchase amount must equal expected amount" ); buyUsingRougee(_originContract, _tokenId); } ///////////////////////////////////////////////////////////////////////// // buy ///////////////////////////////////////////////////////////////////////// /** * @dev Purchases the token if it is for sale. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token. */ function buy(address _originContract, uint256 _tokenId) public payable { // The owner of the token must have the marketplace approved ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // Check that the person who set the price still owns the token. require( _priceSetterStillOwnsTheToken(_originContract, _tokenId), "buy::Current token owner must be the person to have the latest price." ); SalePrice memory sp = tokenPrices[_originContract][_tokenId]; // Check that token is for sale. require(sp.amount > 0, "buy::Tokens priced at 0 are not for sale."); // Check that enough ether was sent. require( tokenPriceFeeIncluded(_originContract, _tokenId) == msg.value, "buy::Must purchase the token for the correct price(buy)" ); // Get token contract details. IERC721 erc721 = IERC721(_originContract); address tokenOwner = erc721.ownerOf(_tokenId); // Wipe the token price. _resetTokenPrice(_originContract, _tokenId); // Transfer token. erc721.safeTransferFrom(tokenOwner, msg.sender, _tokenId); // if the buyer had an existing bid, return it if (_addressHasBidOnToken(msg.sender, _originContract, _tokenId)) { _refundBid(_originContract, _tokenId); } Payments.simplePayout( sp.amount, _makePayable(tokenOwner) ); emit Sold(_originContract, msg.sender, tokenOwner, sp.amount, _tokenId); } ///////////////////////////////////////////////////////////////////////// // buy using Rougee token ///////////////////////////////////////////////////////////////////////// /** * @dev Purchases the token if it is for sale. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token. */ function buyUsingRougee(address _originContract, uint256 _tokenId) public payable { // The owner of the token must have the marketplace approved ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // Get token contract details. IERC721 erc721 = IERC721(_originContract); address tokenOwner = erc721.ownerOf(_tokenId); // Check that the person who set the price still owns the token. require( erc721.ownerOf(_tokenId) == tokenPricesRougee[_originContract][_tokenId].seller, "buy::Current token owner must be the person to have the latest price." ); SalePrice memory sp = tokenPricesRougee[_originContract][_tokenId]; // Check that token is for sale. require(sp.amount > 0, "buy::Tokens priced at 0 are not for sale."); require( rougeeToken.allowance(msg.sender, address(this)) >= sp.amount, 'Not enough Allowance for Rougee Tokens' ); // Wipe the token price. _resetTokenPrice(_originContract, _tokenId); // Transfer token. erc721.safeTransferFrom(tokenOwner, msg.sender, _tokenId); // if the buyer had an existing bid, return it if (_addressHasBidOnToken(msg.sender, _originContract, _tokenId)) { _refundBid(_originContract, _tokenId); } rougeeToken.transferFrom(msg.sender, tokenOwner, (sp.amount) ); emit Sold(_originContract, msg.sender, tokenOwner, (sp.amount), _tokenId); } ///////////////////////////////////////////////////////////////////////// // tokenPrice ///////////////////////////////////////////////////////////////////////// /** * @dev Gets the sale price of the token * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token * @return uint256 sale price of the token */ function tokenPrice(address _originContract, uint256 _tokenId) external view returns (uint256) { // The owner of the token must have the marketplace approved ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // TODO: Make sure to write test to verify that this returns 0 when it fails if (_priceSetterStillOwnsTheToken(_originContract, _tokenId)) { return tokenPrices[_originContract][_tokenId].amount; } return 0; } ///////////////////////////////////////////////////////////////////////// // tokenPriceInRougee ///////////////////////////////////////////////////////////////////////// /** * @dev Gets the sale price of the token * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token * @return uint256 sale price of the token */ function tokenPriceInRougee(address _originContract, uint256 _tokenId) external view returns (uint256) { // The owner of the token must have the marketplace approved ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // TODO: Make sure to write test to verify that this returns 0 when it fails IERC721 erc721 = IERC721(_originContract); if (erc721.ownerOf(_tokenId) == tokenPricesRougee[_originContract][_tokenId].seller) { return tokenPricesRougee[_originContract][_tokenId].amount; } return 0; } ///////////////////////////////////////////////////////////////////////// // tokenPriceFeeIncluded ///////////////////////////////////////////////////////////////////////// /** * @dev Gets the sale price of the token including the marketplace fee. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token * @return uint256 sale price of the token including the fee. */ function tokenPriceFeeIncluded(address _originContract, uint256 _tokenId) public view returns (uint256) { // The owner of the token must have the marketplace approved ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // TODO: Make sure to write test to verify that this returns 0 when it fails if (_priceSetterStillOwnsTheToken(_originContract, _tokenId)) { return tokenPrices[_originContract][_tokenId].amount.add(0); } return 0; } ///////////////////////////////////////////////////////////////////////// // tokenPriceRougeeFeeIncluded ///////////////////////////////////////////////////////////////////////// /** * @dev Gets the sale price of the token including the marketplace fee. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token * @return uint256 sale price of the token including the fee. */ function tokenPriceRougeeFeeIncluded(address _originContract, uint256 _tokenId) public view returns (uint256) { // The owner of the token must have the marketplace approved ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // TODO: Make sure to write test to verify that this returns 0 when it fails if (_priceSetterStillOwnsTheToken(_originContract, _tokenId)) { return tokenPricesRougee[_originContract][_tokenId].amount.add(0); } return 0; } ///////////////////////////////////////////////////////////////////////// // bid ///////////////////////////////////////////////////////////////////////// /** * @dev Bids on the token, replacing the bid if the bid is higher than the current bid. You cannot bid on a token you already own. * @param _newBidAmount uint256 value in wei to bid. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token */ function bid( uint256 _newBidAmount, address _originContract, uint256 _tokenId ) external payable { // Check that bid is greater than 0. require(_newBidAmount > 0, "bid::Cannot bid 0 Wei."); // Check that bid is higher than previous bid uint256 currentBidAmount = tokenCurrentBids[_originContract][_tokenId].amount; require( _newBidAmount > currentBidAmount && _newBidAmount >= currentBidAmount.add( currentBidAmount.mul(minimumBidIncreasePercentage).div(100) ), "bid::Must place higher bid than existing bid + minimum percentage." ); // Check that enough ether was sent. uint256 requiredCost = _newBidAmount.add( 0 ); require( requiredCost == msg.value, "bid::Must purchase the token for the correct price." ); // Check that bidder is not owner. IERC721 erc721 = IERC721(_originContract); address tokenOwner = erc721.ownerOf(_tokenId); require(tokenOwner != msg.sender, "bid::Bidder cannot be owner."); // Refund previous bidder. _refundBid(_originContract, _tokenId); // Set the new bid. _setBid(_newBidAmount, msg.sender, _originContract, _tokenId); emit Bid(_originContract, msg.sender, _newBidAmount, _tokenId); } ///////////////////////////////////////////////////////////////////////// // safeAcceptBid ///////////////////////////////////////////////////////////////////////// /** * @dev Accept the bid on the token with the expected bid amount. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token * @param _amount uint256 wei amount of the bid */ function safeAcceptBid( address _originContract, uint256 _tokenId, uint256 _amount ) external { // Make sure accepting bid is the expected amount require( tokenCurrentBids[_originContract][_tokenId].amount == _amount, "safeAcceptBid::Bid amount must equal expected amount" ); acceptBid(_originContract, _tokenId); } ///////////////////////////////////////////////////////////////////////// // acceptBid ///////////////////////////////////////////////////////////////////////// /** * @dev Accept the bid on the token. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token */ function acceptBid(address _originContract, uint256 _tokenId) public { // The owner of the token must have the marketplace approved ownerMustHaveMarketplaceApproved(_originContract, _tokenId); // The sender must be the token owner senderMustBeTokenOwner(_originContract, _tokenId); // Check that a bid exists. require( _tokenHasBid(_originContract, _tokenId), "acceptBid::Cannot accept a bid when there is none." ); // Get current bid on token ActiveBid memory currentBid = tokenCurrentBids[_originContract][_tokenId]; // Wipe the token price and bid. _resetTokenPrice(_originContract, _tokenId); _resetBid(_originContract, _tokenId); // Transfer token. IERC721 erc721 = IERC721(_originContract); erc721.safeTransferFrom(msg.sender, currentBid.bidder, _tokenId); Payments.simplePayout( currentBid.amount, _makePayable(msg.sender) ); emit AcceptBid( _originContract, currentBid.bidder, msg.sender, currentBid.amount, _tokenId ); } ///////////////////////////////////////////////////////////////////////// // cancelBid ///////////////////////////////////////////////////////////////////////// /** * @dev Cancel the bid on the token. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 ID of the token. */ function cancelBid(address _originContract, uint256 _tokenId) external { // Check that sender has a current bid. require( _addressHasBidOnToken(msg.sender, _originContract, _tokenId), "cancelBid::Cannot cancel a bid if sender hasn't made one." ); // Refund the bidder. _refundBid(_originContract, _tokenId); emit CancelBid( _originContract, msg.sender, tokenCurrentBids[_originContract][_tokenId].amount, _tokenId ); } ///////////////////////////////////////////////////////////////////////// // currentBidDetailsOfToken ///////////////////////////////////////////////////////////////////////// /** * @dev Function to get current bid and bidder of a token. * @param _originContract address of ERC721 contract. * @param _tokenId uin256 id of the token. */ function currentBidDetailsOfToken(address _originContract, uint256 _tokenId) public view returns (uint256, address) { return ( tokenCurrentBids[_originContract][_tokenId].amount, tokenCurrentBids[_originContract][_tokenId].bidder ); } ///////////////////////////////////////////////////////////////////////// // _priceSetterStillOwnsTheToken ///////////////////////////////////////////////////////////////////////// /** * @dev Checks that the token is owned by the same person who set the sale price. * @param _originContract address of the contract storing the token. * @param _tokenId uint256 id of the. */ function _priceSetterStillOwnsTheToken( address _originContract, uint256 _tokenId ) internal view returns (bool) { IERC721 erc721 = IERC721(_originContract); return erc721.ownerOf(_tokenId) == tokenPrices[_originContract][_tokenId].seller; } ///////////////////////////////////////////////////////////////////////// // _resetTokenPrice ///////////////////////////////////////////////////////////////////////// /** * @dev Internal function to set token price to 0 for a given contract. * @param _originContract address of ERC721 contract. * @param _tokenId uin256 id of the token. */ function _resetTokenPrice(address _originContract, uint256 _tokenId) internal { tokenPrices[_originContract][_tokenId] = SalePrice(address(0), 0); } ///////////////////////////////////////////////////////////////////////// // _addressHasBidOnToken ///////////////////////////////////////////////////////////////////////// /** * @dev Internal function see if the given address has an existing bid on a token. * @param _bidder address that may have a current bid. * @param _originContract address of ERC721 contract. * @param _tokenId uin256 id of the token. */ function _addressHasBidOnToken( address _bidder, address _originContract, uint256 _tokenId ) internal view returns (bool) { return tokenCurrentBids[_originContract][_tokenId].bidder == _bidder; } ///////////////////////////////////////////////////////////////////////// // _tokenHasBid ///////////////////////////////////////////////////////////////////////// /** * @dev Internal function see if the token has an existing bid. * @param _originContract address of ERC721 contract. * @param _tokenId uin256 id of the token. */ function _tokenHasBid(address _originContract, uint256 _tokenId) internal view returns (bool) { return tokenCurrentBids[_originContract][_tokenId].bidder != address(0); } ///////////////////////////////////////////////////////////////////////// // _refundBid ///////////////////////////////////////////////////////////////////////// /** * @dev Internal function to return an existing bid on a token to the * bidder and reset bid. * @param _originContract address of ERC721 contract. * @param _tokenId uin256 id of the token. */ function _refundBid(address _originContract, uint256 _tokenId) internal { ActiveBid memory currentBid = tokenCurrentBids[_originContract][_tokenId]; if (currentBid.bidder == address(0)) { return; } _resetBid(_originContract, _tokenId); Payments.refund( currentBid.marketplaceFee, currentBid.bidder, currentBid.amount ); } ///////////////////////////////////////////////////////////////////////// // _resetBid ///////////////////////////////////////////////////////////////////////// /** * @dev Internal function to reset bid by setting bidder and bid to 0. * @param _originContract address of ERC721 contract. * @param _tokenId uin256 id of the token. */ function _resetBid(address _originContract, uint256 _tokenId) internal { tokenCurrentBids[_originContract][_tokenId] = ActiveBid( address(0), 0, 0 ); } ///////////////////////////////////////////////////////////////////////// // _setBid ///////////////////////////////////////////////////////////////////////// /** * @dev Internal function to set a bid. * @param _amount uint256 value in wei to bid. Does not include marketplace fee. * @param _bidder address of the bidder. * @param _originContract address of ERC721 contract. * @param _tokenId uin256 id of the token. */ function _setBid( uint256 _amount, address payable _bidder, address _originContract, uint256 _tokenId ) internal { // Check bidder not 0 address. require(_bidder != address(0), "Bidder cannot be 0 address."); // Set bid. tokenCurrentBids[_originContract][_tokenId] = ActiveBid( _bidder, 0, _amount ); } ///////////////////////////////////////////////////////////////////////// // _makePayable ///////////////////////////////////////////////////////////////////////// /** * @dev Internal function to set a bid. * @param _address non-payable address * @return payable address */ function _makePayable(address _address) internal pure returns (address payable) { return address(uint160(_address)); } function changeRougeeToken (address Rougee) public onlyOwner returns (address){ rougeeToken = IERC20(Rougee); return address(rougeeToken); } }
Called by the payer to store the sent amount as credit to be pulled. Funds sent in this way are stored in an intermediate {Escrow} contract, so there is no danger of them being spent before withdrawal. dest The destination address of the funds. amount The amount to transfer./
function _asyncTransfer(address dest, uint256 amount) internal virtual { } uint256[49] private __gap;
6,620,233
/* ==================================================================== */ /* Copyright (c) 2018 The ether.online Project. All rights reserved. /* /* https://ether.online The first RPG game of blockchain /* ==================================================================== */ pragma solidity ^0.4.20; /// @title ERC-165 Standard Interface Detection /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md contract ERC721 is ERC165 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) external view returns (uint256); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function approve(address _approved, uint256 _tokenId) external; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard interface ERC721TokenReceiver { function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension interface ERC721Metadata /* is ERC721 */ { function name() external pure returns (string _name); function symbol() external pure returns (string _symbol); function tokenURI(uint256 _tokenId) external view returns (string); } /// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension interface ERC721Enumerable /* is ERC721 */ { function totalSupply() external view returns (uint256); function tokenByIndex(uint256 _index) external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } contract AccessAdmin { bool public isPaused = false; address public addrAdmin; event AdminTransferred(address indexed preAdmin, address indexed newAdmin); function AccessAdmin() public { addrAdmin = msg.sender; } modifier onlyAdmin() { require(msg.sender == addrAdmin); _; } modifier whenNotPaused() { require(!isPaused); _; } modifier whenPaused { require(isPaused); _; } function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); AdminTransferred(addrAdmin, _newAdmin); addrAdmin = _newAdmin; } function doPause() external onlyAdmin whenNotPaused { isPaused = true; } function doUnpause() external onlyAdmin whenPaused { isPaused = false; } } contract AccessService is AccessAdmin { address public addrService; address public addrFinance; modifier onlyService() { require(msg.sender == addrService); _; } modifier onlyFinance() { require(msg.sender == addrFinance); _; } function setService(address _newService) external { require(msg.sender == addrService || msg.sender == addrAdmin); require(_newService != address(0)); addrService = _newService; } function setFinance(address _newFinance) external { require(msg.sender == addrFinance || msg.sender == addrAdmin); require(_newFinance != address(0)); addrFinance = _newFinance; } } contract WarToken is ERC721, AccessAdmin { /// @dev The equipment info struct Fashion { uint16 protoId; // 0 Equipment ID uint16 quality; // 1 Rarity: 1 Coarse/2 Good/3 Rare/4 Epic/5 Legendary uint16 pos; // 2 Slots: 1 Weapon/2 Hat/3 Cloth/4 Pant/5 Shoes/9 Pets uint16 health; // 3 Health uint16 atkMin; // 4 Min attack uint16 atkMax; // 5 Max attack uint16 defence; // 6 Defennse uint16 crit; // 7 Critical rate uint16 attrExt1; // 8 future stat 1 uint16 attrExt2; // 9 future stat 2 uint16 attrExt3; // 10 future stat 3 uint16 attrExt4; // 11 future stat 4 } /// @dev All equipments tokenArray (not exceeding 2^32-1) Fashion[] public fashionArray; /// @dev Amount of tokens destroyed uint256 destroyFashionCount; /// @dev Equipment token ID vs owner address mapping (uint256 => address) fashionIdToOwner; /// @dev Equipments owner by the owner (array) mapping (address => uint256[]) ownerToFashionArray; /// @dev Equipment token ID search in owner array mapping (uint256 => uint256) fashionIdToOwnerIndex; /// @dev The authorized address for each WAR mapping (uint256 => address) fashionIdToApprovals; /// @dev The authorized operators for each address mapping (address => mapping (address => bool)) operatorToApprovals; /// @dev Trust contract mapping (address => bool) actionContracts; function setActionContract(address _actionAddr, bool _useful) external onlyAdmin { actionContracts[_actionAddr] = _useful; } function getActionContract(address _actionAddr) external view onlyAdmin returns(bool) { return actionContracts[_actionAddr]; } /// @dev This emits when the approved address for an WAR is changed or reaffirmed. event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @dev This emits when the equipment ownership changed event Transfer(address indexed from, address indexed to, uint256 tokenId); /// @dev This emits when the equipment created event CreateFashion(address indexed owner, uint256 tokenId, uint16 protoId, uint16 quality, uint16 pos, uint16 createType); /// @dev This emits when the equipment&#39;s attributes changed event ChangeFashion(address indexed owner, uint256 tokenId, uint16 changeType); /// @dev This emits when the equipment destroyed event DeleteFashion(address indexed owner, uint256 tokenId, uint16 deleteType); function WarToken() public { addrAdmin = msg.sender; fashionArray.length += 1; } // modifier /// @dev Check if token ID is valid modifier isValidToken(uint256 _tokenId) { require(_tokenId >= 1 && _tokenId <= fashionArray.length); require(fashionIdToOwner[_tokenId] != address(0)); _; } modifier canTransfer(uint256 _tokenId) { address owner = fashionIdToOwner[_tokenId]; require(msg.sender == owner || msg.sender == fashionIdToApprovals[_tokenId] || operatorToApprovals[owner][msg.sender]); _; } // ERC721 function supportsInterface(bytes4 _interfaceId) external view returns(bool) { // ERC165 || ERC721 || ERC165^ERC721 return (_interfaceId == 0x01ffc9a7 || _interfaceId == 0x80ac58cd || _interfaceId == 0x8153916a) && (_interfaceId != 0xffffffff); } function name() public pure returns(string) { return "WAR Token"; } function symbol() public pure returns(string) { return "WAR"; } /// @dev Search for token quantity address /// @param _owner Address that needs to be searched /// @return Returns token quantity function balanceOf(address _owner) external view returns(uint256) { require(_owner != address(0)); return ownerToFashionArray[_owner].length; } /// @dev Find the owner of an WAR /// @param _tokenId The tokenId of WAR /// @return Give The address of the owner of this WAR function ownerOf(uint256 _tokenId) external view /*isValidToken(_tokenId)*/ returns (address owner) { return fashionIdToOwner[_tokenId]; } /// @dev Transfers the ownership of an WAR from one address to another address /// @param _from The current owner of the WAR /// @param _to The new owner /// @param _tokenId The WAR to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external whenNotPaused { _safeTransferFrom(_from, _to, _tokenId, data); } /// @dev Transfers the ownership of an WAR from one address to another address /// @param _from The current owner of the WAR /// @param _to The new owner /// @param _tokenId The WAR to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { _safeTransferFrom(_from, _to, _tokenId, ""); } /// @dev Transfer ownership of an WAR, &#39;_to&#39; must be a vaild address, or the WAR will lost /// @param _from The current owner of the WAR /// @param _to The new owner /// @param _tokenId The WAR to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused isValidToken(_tokenId) canTransfer(_tokenId) { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner == _from); _transfer(_from, _to, _tokenId); } /// @dev Set or reaffirm the approved address for an WAR /// @param _approved The new approved WAR controller /// @param _tokenId The WAR to approve function approve(address _approved, uint256 _tokenId) external whenNotPaused { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(msg.sender == owner || operatorToApprovals[owner][msg.sender]); fashionIdToApprovals[_tokenId] = _approved; Approval(owner, _approved, _tokenId); } /// @dev Enable or disable approval for a third party ("operator") to manage all your asset. /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operators is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external whenNotPaused { operatorToApprovals[msg.sender][_operator] = _approved; ApprovalForAll(msg.sender, _operator, _approved); } /// @dev Get the approved address for a single WAR /// @param _tokenId The WAR to find the approved address for /// @return The approved address for this WAR, or the zero address if there is none function getApproved(uint256 _tokenId) external view isValidToken(_tokenId) returns (address) { return fashionIdToApprovals[_tokenId]; } /// @dev Query if an address is an authorized operator for another address /// @param _owner The address that owns the WARs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return operatorToApprovals[_owner][_operator]; } /// @dev Count WARs tracked by this contract /// @return A count of valid WARs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256) { return fashionArray.length - destroyFashionCount - 1; } /// @dev Do the real transfer with out any condition checking /// @param _from The old owner of this WAR(If created: 0x0) /// @param _to The new owner of this WAR /// @param _tokenId The tokenId of the WAR function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_from != address(0)) { uint256 indexFrom = fashionIdToOwnerIndex[_tokenId]; uint256[] storage fsArray = ownerToFashionArray[_from]; require(fsArray[indexFrom] == _tokenId); // If the WAR is not the element of array, change it to with the last if (indexFrom != fsArray.length - 1) { uint256 lastTokenId = fsArray[fsArray.length - 1]; fsArray[indexFrom] = lastTokenId; fashionIdToOwnerIndex[lastTokenId] = indexFrom; } fsArray.length -= 1; if (fashionIdToApprovals[_tokenId] != address(0)) { delete fashionIdToApprovals[_tokenId]; } } // Give the WAR to &#39;_to&#39; fashionIdToOwner[_tokenId] = _to; ownerToFashionArray[_to].push(_tokenId); fashionIdToOwnerIndex[_tokenId] = ownerToFashionArray[_to].length - 1; Transfer(_from != address(0) ? _from : this, _to, _tokenId); } /// @dev Actually perform the safeTransferFrom function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) internal isValidToken(_tokenId) canTransfer(_tokenId) { address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner == _from); _transfer(_from, _to, _tokenId); // Do the callback after everything is done to avoid reentrancy attack uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; } bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data); // bytes4(keccak256("onERC721Received(address,uint256,bytes)")) = 0xf0b9e5ba; require(retval == 0xf0b9e5ba); } //---------------------------------------------------------------------------------------------------------- /// @dev Equipment creation /// @param _owner Owner of the equipment created /// @param _attrs Attributes of the equipment created /// @return Token ID of the equipment created function createFashion(address _owner, uint16[9] _attrs) external whenNotPaused returns(uint256) { require(actionContracts[msg.sender]); require(_owner != address(0)); uint256 newFashionId = fashionArray.length; require(newFashionId < 4294967296); fashionArray.length += 1; Fashion storage fs = fashionArray[newFashionId]; fs.protoId = _attrs[0]; fs.quality = _attrs[1]; fs.pos = _attrs[2]; if (_attrs[3] != 0) { fs.health = _attrs[3]; } if (_attrs[4] != 0) { fs.atkMin = _attrs[4]; fs.atkMax = _attrs[5]; } if (_attrs[6] != 0) { fs.defence = _attrs[6]; } if (_attrs[7] != 0) { fs.crit = _attrs[7]; } _transfer(0, _owner, newFashionId); CreateFashion(_owner, newFashionId, _attrs[0], _attrs[1], _attrs[2], _attrs[8]); return newFashionId; } /// @dev One specific attribute of the equipment modified function _changeAttrByIndex(Fashion storage _fs, uint16 _index, uint16 _val) internal { if (_index == 3) { _fs.health = _val; } else if(_index == 4) { _fs.atkMin = _val; } else if(_index == 5) { _fs.atkMax = _val; } else if(_index == 6) { _fs.defence = _val; } else if(_index == 7) { _fs.crit = _val; } else if(_index == 8) { _fs.attrExt1 = _val; } else if(_index == 9) { _fs.attrExt2 = _val; } else if(_index == 10) { _fs.attrExt3 = _val; } else { _fs.attrExt4 = _val; } } /// @dev Equiment attributes modified (max 4 stats modified) /// @param _tokenId Equipment Token ID /// @param _idxArray Stats order that must be modified /// @param _params Stat value that must be modified /// @param _changeType Modification type such as enhance, socket, etc. function changeFashionAttr(uint256 _tokenId, uint16[4] _idxArray, uint16[4] _params, uint16 _changeType) external whenNotPaused isValidToken(_tokenId) { require(actionContracts[msg.sender]); Fashion storage fs = fashionArray[_tokenId]; if (_idxArray[0] > 0) { _changeAttrByIndex(fs, _idxArray[0], _params[0]); } if (_idxArray[1] > 0) { _changeAttrByIndex(fs, _idxArray[1], _params[1]); } if (_idxArray[2] > 0) { _changeAttrByIndex(fs, _idxArray[2], _params[2]); } if (_idxArray[3] > 0) { _changeAttrByIndex(fs, _idxArray[3], _params[3]); } ChangeFashion(fashionIdToOwner[_tokenId], _tokenId, _changeType); } /// @dev Equipment destruction /// @param _tokenId Equipment Token ID /// @param _deleteType Destruction type, such as craft function destroyFashion(uint256 _tokenId, uint16 _deleteType) external whenNotPaused isValidToken(_tokenId) { require(actionContracts[msg.sender]); address _from = fashionIdToOwner[_tokenId]; uint256 indexFrom = fashionIdToOwnerIndex[_tokenId]; uint256[] storage fsArray = ownerToFashionArray[_from]; require(fsArray[indexFrom] == _tokenId); if (indexFrom != fsArray.length - 1) { uint256 lastTokenId = fsArray[fsArray.length - 1]; fsArray[indexFrom] = lastTokenId; fashionIdToOwnerIndex[lastTokenId] = indexFrom; } fsArray.length -= 1; fashionIdToOwner[_tokenId] = address(0); delete fashionIdToOwnerIndex[_tokenId]; destroyFashionCount += 1; Transfer(_from, 0, _tokenId); DeleteFashion(_from, _tokenId, _deleteType); } /// @dev Safe transfer by trust contracts function safeTransferByContract(uint256 _tokenId, address _to) external whenNotPaused { require(actionContracts[msg.sender]); require(_tokenId >= 1 && _tokenId <= fashionArray.length); address owner = fashionIdToOwner[_tokenId]; require(owner != address(0)); require(_to != address(0)); require(owner != _to); _transfer(owner, _to, _tokenId); } //---------------------------------------------------------------------------------------------------------- /// @dev Get fashion attrs by tokenId function getFashion(uint256 _tokenId) external view isValidToken(_tokenId) returns (uint16[12] datas) { Fashion storage fs = fashionArray[_tokenId]; datas[0] = fs.protoId; datas[1] = fs.quality; datas[2] = fs.pos; datas[3] = fs.health; datas[4] = fs.atkMin; datas[5] = fs.atkMax; datas[6] = fs.defence; datas[7] = fs.crit; datas[8] = fs.attrExt1; datas[9] = fs.attrExt2; datas[10] = fs.attrExt3; datas[11] = fs.attrExt4; } /// @dev Get tokenIds and flags by owner function getOwnFashions(address _owner) external view returns(uint256[] tokens, uint32[] flags) { require(_owner != address(0)); uint256[] storage fsArray = ownerToFashionArray[_owner]; uint256 length = fsArray.length; tokens = new uint256[](length); flags = new uint32[](length); for (uint256 i = 0; i < length; ++i) { tokens[i] = fsArray[i]; Fashion storage fs = fashionArray[fsArray[i]]; flags[i] = uint32(uint32(fs.protoId) * 100 + uint32(fs.quality) * 10 + fs.pos); } } /// @dev WAR token info returned based on Token ID transfered (64 at most) function getFashionsAttrs(uint256[] _tokens) external view returns(uint16[] attrs) { uint256 length = _tokens.length; require(length <= 64); attrs = new uint16[](length * 11); uint256 tokenId; uint256 index; for (uint256 i = 0; i < length; ++i) { tokenId = _tokens[i]; if (fashionIdToOwner[tokenId] != address(0)) { index = i * 11; Fashion storage fs = fashionArray[tokenId]; attrs[index] = fs.health; attrs[index + 1] = fs.atkMin; attrs[index + 2] = fs.atkMax; attrs[index + 3] = fs.defence; attrs[index + 4] = fs.crit; attrs[index + 5] = fs.attrExt1; attrs[index + 6] = fs.attrExt2; attrs[index + 7] = fs.attrExt3; attrs[index + 8] = fs.attrExt4; } } } } contract ActionPresell is AccessService { WarToken tokenContract; mapping (uint16 => uint16) petPresellCounter; mapping (address => uint16[]) presellLimit; event PetPreSelled(address indexed buyer, uint16 protoId); function ActionPresell(address _nftAddr) public { addrAdmin = msg.sender; addrService = msg.sender; addrFinance = msg.sender; tokenContract = WarToken(_nftAddr); petPresellCounter[10001] = 50; petPresellCounter[10002] = 30; petPresellCounter[10003] = 50; petPresellCounter[10004] = 30; petPresellCounter[10005] = 30; } function() external payable { } function setWarTokenAddr(address _nftAddr) external onlyAdmin { tokenContract = WarToken(_nftAddr); } function petPresell(uint16 _protoId) external payable whenNotPaused { uint16 curSupply = petPresellCounter[_protoId]; require(curSupply > 0); uint16[] storage buyArray = presellLimit[msg.sender]; uint256 curBuyCnt = buyArray.length; require(curBuyCnt < 10); uint256 payBack = 0; if (_protoId == 10001) { require(msg.value >= 0.66 ether); payBack = (msg.value - 0.66 ether); uint16[9] memory param1 = [10001, 5, 9, 400, 0, 0, 0, 0, 1]; // hp +400 tokenContract.createFashion(msg.sender, param1); buyArray.push(10001); } else if(_protoId == 10002) { require(msg.value >= 0.99 ether); payBack = (msg.value - 0.99 ether); uint16[9] memory param2 = [10002, 5, 9, 0, 60, 60, 0, 0, 1]; // atk +60 tokenContract.createFashion(msg.sender, param2); buyArray.push(10002); } else if(_protoId == 10003) { require(msg.value >= 0.66 ether); payBack = (msg.value - 0.66 ether); uint16[9] memory param3 = [10003, 5, 9, 0, 0, 0, 40, 0, 1]; // def +40 tokenContract.createFashion(msg.sender, param3); buyArray.push(10003); } else if(_protoId == 10004) { require(msg.value >= 0.99 ether); payBack = (msg.value - 0.99 ether); uint16[9] memory param4 = [10004, 5, 9, 0, 0, 0, 0, 3, 1]; // crit +3 tokenContract.createFashion(msg.sender, param4); buyArray.push(10004); } else { require(msg.value >= 0.99 ether); payBack = (msg.value - 0.99 ether); uint16[9] memory param5 = [10005, 5, 9, 200, 20, 20, 20, 0, 1]; // hp +200, atk +20, def +20 tokenContract.createFashion(msg.sender, param5); buyArray.push(10005); } petPresellCounter[_protoId] = (curSupply - 1); PetPreSelled(msg.sender, _protoId); addrFinance.transfer(msg.value - payBack); // need 2300 gas -_-! if (payBack > 0) { msg.sender.transfer(payBack); } } function withdraw() external { require(msg.sender == addrFinance || msg.sender == addrAdmin); addrFinance.transfer(this.balance); } function getPetCanPresellCount() external view returns (uint16[5] cntArray) { cntArray[0] = petPresellCounter[10001]; cntArray[1] = petPresellCounter[10002]; cntArray[2] = petPresellCounter[10003]; cntArray[3] = petPresellCounter[10004]; cntArray[4] = petPresellCounter[10005]; } function getBuyCount(address _owner) external view returns (uint32) { return uint32(presellLimit[_owner].length); } function getBuyArray(address _owner) external view returns (uint16[]) { uint16[] storage buyArray = presellLimit[_owner]; return buyArray; } }
WAR token info returned based on Token ID transfered (64 at most)
function getFashionsAttrs(uint256[] _tokens) external view returns(uint16[] attrs) { uint256 length = _tokens.length; require(length <= 64); attrs = new uint16[](length * 11); uint256 tokenId; uint256 index; for (uint256 i = 0; i < length; ++i) { tokenId = _tokens[i]; if (fashionIdToOwner[tokenId] != address(0)) { index = i * 11; Fashion storage fs = fashionArray[tokenId]; attrs[index] = fs.health; attrs[index + 1] = fs.atkMin; attrs[index + 2] = fs.atkMax; attrs[index + 3] = fs.defence; attrs[index + 4] = fs.crit; attrs[index + 5] = fs.attrExt1; attrs[index + 6] = fs.attrExt2; attrs[index + 7] = fs.attrExt3; attrs[index + 8] = fs.attrExt4; } } }
2,331,066
/* * * $DEWO Token - The Native Token In DecentraWorld's Ecosystem * DecentraWorld - Increasing Privacy Standards In DeFi * * Documentation: http://docs.decentraworld.co/ * GitHub: https://github.com/decentraworldDEWO * DecentraWorld: https://DecentraWorld.co/ * DAO: https://dao.decentraworld.co/ * Governance: https://gov.decentraworld.co/ * DecentraMix: https://decentramix.io/ * *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *░░██████╗░███████╗░█████╗░███████╗███╗░░██╗████████╗██████╗░░█████╗░░░ *░░██╔══██╗██╔════╝██╔══██╗██╔════╝████╗░██║╚══██╔══╝██╔══██╗██╔══██╗░░ *░░██║░░██║█████╗░░██║░░╚═╝█████╗░░██╔██╗██║░░░██║░░░██████╔╝███████║░░ *░░██║░░██║██╔══╝░░██║░░██╗██╔══╝░░██║╚████║░░░██║░░░██╔══██╗██╔══██║░░ *░░██████╔╝███████╗╚█████╔╝███████╗██║░╚███║░░░██║░░░██║░░██║██║░░██║░░ *░░╚═════╝░╚══════╝░╚════╝░╚══════╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝░░ *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *░░░░░░░░░░░░░██╗░░░░░░░██╗░█████╗░██████╗░██╗░░░░░██████╗░░░░░░░░░░░░░ *░░░░░░░░░░░░░██║░░██╗░░██║██╔══██╗██╔══██╗██║░░░░░██╔══██╗░░░░░░░░░░░░ *░░░░░░░░░░░░░╚██╗████╗██╔╝██║░░██║██████╔╝██║░░░░░██║░░██║░░░░░░░░░░░░ *░░░░░░░░░░░░░░████╔═████║░██║░░██║██╔══██╗██║░░░░░██║░░██║░░░░░░░░░░░░ *░░░░░░░░░░░░░░╚██╔╝░╚██╔╝░╚█████╔╝██║░░██║███████╗██████╔╝░░░░░░░░░░░░ *░░░░░░░░░░░░░░░╚═╝░░░╚═╝░░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░░░░░░░░░░░░░ *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * */ // SPDX-License-Identifier: MIT // File: @OpenZeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @OpenZeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @OpenZeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/DecentraWorld_Multichain.sol /* * * $DEWO Token - The Native Token In DecentraWorld's Ecosystem * DecentraWorld - Increasing Privacy Standards In DeFi * * Documentation: http://docs.decentraworld.co/ * GitHub: https://github.com/decentraworldDEWO * DecentraWorld: https://DecentraWorld.co/ * DAO: https://dao.decentraworld.co/ * Governance: https://gov.decentraworld.co/ * DecentraMix: https://decentramix.io/ * *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *░░██████╗░███████╗░█████╗░███████╗███╗░░██╗████████╗██████╗░░█████╗░░░ *░░██╔══██╗██╔════╝██╔══██╗██╔════╝████╗░██║╚══██╔══╝██╔══██╗██╔══██╗░░ *░░██║░░██║█████╗░░██║░░╚═╝█████╗░░██╔██╗██║░░░██║░░░██████╔╝███████║░░ *░░██║░░██║██╔══╝░░██║░░██╗██╔══╝░░██║╚████║░░░██║░░░██╔══██╗██╔══██║░░ *░░██████╔╝███████╗╚█████╔╝███████╗██║░╚███║░░░██║░░░██║░░██║██║░░██║░░ *░░╚═════╝░╚══════╝░╚════╝░╚══════╝╚═╝░░╚══╝░░░╚═╝░░░╚═╝░░╚═╝╚═╝░░╚═╝░░ *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *░░░░░░░░░░░░░██╗░░░░░░░██╗░█████╗░██████╗░██╗░░░░░██████╗░░░░░░░░░░░░░ *░░░░░░░░░░░░░██║░░██╗░░██║██╔══██╗██╔══██╗██║░░░░░██╔══██╗░░░░░░░░░░░░ *░░░░░░░░░░░░░╚██╗████╗██╔╝██║░░██║██████╔╝██║░░░░░██║░░██║░░░░░░░░░░░░ *░░░░░░░░░░░░░░████╔═████║░██║░░██║██╔══██╗██║░░░░░██║░░██║░░░░░░░░░░░░ *░░░░░░░░░░░░░░╚██╔╝░╚██╔╝░╚█████╔╝██║░░██║███████╗██████╔╝░░░░░░░░░░░░ *░░░░░░░░░░░░░░░╚═╝░░░╚═╝░░░╚════╝░╚═╝░░╚═╝╚══════╝╚═════╝░░░░░░░░░░░░░ *░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * */ pragma solidity ^0.8.7; /** * @dev Interfaces */ interface IDEXFactory { 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 IDEXRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IPancakeswapV2Pair { 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; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address to, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); } contract DecentraWorld_Multichain is Context, IERC20, IERC20Metadata, Ownable { using SafeMath for uint256; // DecentraWorld - $DEWO uint256 _totalSupply; string private _name; string private _symbol; uint8 private _decimals; // Mapping mapping (string => uint) txTaxes; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping (address => bool) public excludeFromTax; mapping (address => bool) public exclueFromMaxTx; // Addresses Of Tax Receivers address public daoandfarmingAddress; address public marketingAddress; address public developmentAddress; address public coreteamAddress; // Address of the bridge controling the mint/burn of the cross-chain address public MPC; // taxes for differnet levels struct TaxLevels { uint taxDiscount; uint amount; } struct DEWOTokenTax { uint forMarketing; uint forCoreTeam; uint forDevelopment; uint forDAOAndFarming; } struct TxLimit { uint buyMaxTx; uint sellMaxTx; uint txcooldown; mapping(address => uint) buys; mapping(address => uint) sells; mapping(address => uint) lastTx; } mapping (uint => TaxLevels) taxTiers; TxLimit txSettings; IDEXRouter public router; address public pair; constructor() { _name = "DecentraWorld"; _symbol = "$DEWO"; _decimals = 18; //Temporary Tax Receivers daoandfarmingAddress = msg.sender; marketingAddress = 0x5d5a0368b8C383c45c625a7241473A1a4F61eA4E; developmentAddress = 0xdA9f5e831b7D18c35CA7778eD271b4d4f3bE183E; coreteamAddress = 0x797BD28BaE691B21e235E953043337F4794Ff9DB; // Exclude From Taxes By Default excludeFromTax[msg.sender] = true; excludeFromTax[daoandfarmingAddress] = true; excludeFromTax[marketingAddress] = true; excludeFromTax[developmentAddress] = true; excludeFromTax[coreteamAddress] = true; // Exclude From MaxTx By Default exclueFromMaxTx[msg.sender] = true; exclueFromMaxTx[daoandfarmingAddress] = true; exclueFromMaxTx[marketingAddress] = true; exclueFromMaxTx[developmentAddress] = true; exclueFromMaxTx[coreteamAddress] = true; // Cross-Chain Bridge Temp Settings MPC = msg.sender; // Transaction taxes apply solely on swaps (buys/sells) // Tier 1 - Default Buy Fee [6% Total] // Tier 2 - Buy Fee [3% Total] // Tier 3 - Buy Fee [0% Total] // // Automatically set the default transactions taxes // [Tier 1: 6% Buy Fee] txTaxes["marketingBuyTax"] = 3; // [3%] DAO, Governance, Farming Pools txTaxes["developmentBuyTax"] = 1; // [1%] Marketing Fee txTaxes["coreteamBuyTax"] = 1; // [1%] Development Fee txTaxes["daoandfarmingBuyTax"] = 1; // [1%] DecentraWorld's Core-Team // [Tier 1: 10% Sell Fee] txTaxes["marketingSellTax"] = 4; // 4% DAO, Governance, Farming Pools txTaxes["developmentSellTax"] = 3; // 3% Marketing Fee txTaxes["coreteamSellTax"] = 1; // 1% Development Fee txTaxes["daoandfarmingSellTax"] = 2; // 2% DecentraWorld's Core-Team /* Buy Transaction Tax - 3 tiers: *** Must buy these amounts to qualify Tier 1: 6%/10% (0+ $DEWO balance) Tier 2: 3%/8% (100K+ $DEWO balance) Tier 3: 0%/6% (400K+ $DEWO balance) Sell Transaction Tax - 3 tiers: *** Must hold these amounts to qualify Tier 1: 6%/10% (0+ $DEWO balance) Tier 2: 3%/8% (150K+ $DEWO balance) Tier 3: 0%/6% (300K+ $DEWO balance) Tax Re-distribution Buys (6%/3%/0%): DAO Fund/Farming: 3% | 1% | 0% Marketing Budget: 1% | 1% | 0% Development Fund: 1% | 0% | 0% Core-Team: 1% | 1% | 0% Tax Re-distribution Sells (10%/8%/6%): DAO Fund/Farming: 4% | 3% | 3% Marketing Budget: 3% | 2% | 1% Development Fund: 1% | 1% | 1% Core-Team: 2% | 2% | 1% The community can disable the holder rewards fee and migrate that fee to the rewards/staking pool. This can be done via the Governance portal. */ // Default Tax Tiers & Discounts // Get a 50% discount on purchase tax taxes taxTiers[0].taxDiscount = 50; // When buying over 0.1% of total supply (100,000 $DEWO) taxTiers[0].amount = 100000 * (10 ** decimals()); // Get a 100% discount on purchase tax taxes taxTiers[1].taxDiscount = 99; // When buying over 0.4% of total supply (400,000 $DEWO) taxTiers[1].amount = 400000 * (10 ** decimals()); // Get a 20% discount on sell tax taxes taxTiers[2].taxDiscount = 20; // When holding over 0.15% of total supply (150,000 $DEWO) taxTiers[2].amount = 150000 * (10 ** decimals()); // Get a 40% discount on sell tax taxes taxTiers[3].taxDiscount = 40; // When holding over 0.3% of total supply (300,000 $DEWO) taxTiers[3].amount = 300000 * (10 ** decimals()); // Default txcooldown limit in minutes txSettings.txcooldown = 30 minutes; // Default buy limit: 1.25% of total supply txSettings.buyMaxTx = _totalSupply.div(80); // Default sell limit: 0.25% of total supply txSettings.sellMaxTx = _totalSupply.div(800); /** Removed from the cross-chain $DEWO token, the pair settings were replaced with a function, and the mint function of 100,000,000 $DEWO to deployer was replaced with 0. Since this token is a cross-chain token and not the native EVM chain where $DEWO was deployed (BSC) then there's no need in any additional supply. The Multichain.org bridge will call burn/mint functions accordingly. --- // Create a PancakeSwap (DEX) Pair For $DEWO // This will be used to track the price of $DEWO & charge taxes to all pool buys/sells address WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; // Wrapped BNB on Binance Smart Chain address _router = 0x10ED43C718714eb63d5aA57B78B54704E256024E; // PancakeSwap Router (ChainID: 56 = BSC) router = IDEXRouter(_router); pair = IDEXFactory(router.factory()).createPair(WBNB, address(this)); _allowances[address(this)][address(router)] = _totalSupply; approve(_router, _totalSupply); // Send 100,000,000 $DEWO tokens to the dev (one time only) _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); */ } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } // onlyAuth = allow MPC contract address to call certain functions // The MPC = Multichain bridge contract of each chain modifier onlyAuth() { require(msg.sender == mmpc(), "DecentraWorld: FORBIDDEN"); _; } function mmpc() public view returns (address) { return MPC; } // This can only be done once by the deployer, once the MPC is set only the MPC can call this function again. function setMPC(address _setmpc) external onlyAuth { MPC = _setmpc; } // Mint will be used when individuals cross-chain $DEWO from one chain to another function mint(address to, uint256 amount) external onlyAuth returns (bool) { _mint(to, amount); return true; } // The burn function will be used to burn tokens that were cross-chained into another EVM chain function burn(address from, uint256 amount) external onlyAuth returns (bool) { require(from != address(0), "DecentraWorld: address(0x0)"); _burn(from, amount); return true; } function Swapin(bytes32 txhash, address account, uint256 amount) public onlyAuth returns (bool) { _mint(account, amount); emit LogSwapin(txhash, account, amount); return true; } function Swapout(uint256 amount, address bindaddr) public returns (bool) { require(bindaddr != address(0), "DecentraWorld: address(0x0)"); _burn(msg.sender, amount); emit LogSwapout(msg.sender, bindaddr, amount); return true; } event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount); event LogSwapout(address indexed account, address indexed bindaddr, uint amount); // Set the router & native token of each chain to tax the correct LP POOL of $DEWO // This will always be the most popular DEX on the chain + its native token. function setDEXPAIR(address _nativetoken, address _nativerouter) external onlyOwner { // Create a DEX Pair For $DEWO // This will be used to track the price of $DEWO & charge taxes to all pool buys/sells router = IDEXRouter(_nativerouter); pair = IDEXFactory(router.factory()).createPair(_nativetoken, address(this)); _allowances[address(this)][address(router)] = _totalSupply; approve(_nativerouter, _totalSupply); } // Set Buy Taxes event BuyTaxes( uint _daoandfarmingBuyTax, uint _coreteamBuyTax, uint _developmentBuyTax, uint _marketingBuyTax ); function setBuyTaxes( uint _daoandfarmingBuyTax, uint _coreteamBuyTax, uint _developmentBuyTax, uint _marketingBuyTax // Hardcoded limitation to the maximum tax fee per address // Maximum tax for each buys/sells: 6% max tax per tax receiver, 24% max tax total ) external onlyOwner { require(_daoandfarmingBuyTax <= 6, "DAO & Farming tax is above 6%!"); require(_coreteamBuyTax <= 6, "Core-Team Buy tax is above 6%!"); require(_developmentBuyTax <= 6, "Development Fund tax is above 6%!"); require(_marketingBuyTax <= 6, "Marketing tax is above 6%!"); txTaxes["daoandfarmingBuyTax"] = _daoandfarmingBuyTax; txTaxes["coreteamBuyTax"] = _coreteamBuyTax; txTaxes["developmentBuyTax"] = _developmentBuyTax; txTaxes["marketingBuyTax"] = _marketingBuyTax; emit BuyTaxes( _daoandfarmingBuyTax, _coreteamBuyTax, _developmentBuyTax, _marketingBuyTax ); } // Set Sell Taxes event SellTaxes( uint _daoandfarmingSellTax, uint _coreteamSellTax, uint _developmentSellTax, uint _marketingSellTax ); function setSellTaxes( uint _daoandfarmingSellTax, uint _coreteamSellTax, uint _developmentSellTax, uint _marketingSellTax // Hardcoded limitation to the maximum tax fee per address // Maximum tax for buys/sells: 6% max tax per tax receiver, 24% max tax total ) external onlyOwner { require(_daoandfarmingSellTax <= 6, "DAO & Farming tax is above 6%!"); require(_coreteamSellTax <= 6, "Core-team tax is above 6%!"); require(_developmentSellTax <= 6, "Development tax is above 6%!"); require(_marketingSellTax <= 6, "Marketing tax is above 6%!"); txTaxes["daoandfarmingSellTax"] = _daoandfarmingSellTax; txTaxes["coreteamSellTax"] = _coreteamSellTax; txTaxes["developmentSellTax"] = _developmentSellTax; txTaxes["marketingSellTax"] = _marketingSellTax; emit SellTaxes( _daoandfarmingSellTax, _coreteamSellTax, _developmentSellTax, _marketingSellTax ); } // Displays a list of all current taxes function getSellTaxes() public view returns( uint marketingSellTax, uint developmentSellTax, uint coreteamSellTax, uint daoandfarmingSellTax ) { return ( txTaxes["marketingSellTax"], txTaxes["developmentSellTax"], txTaxes["coreteamSellTax"], txTaxes["daoandfarmingSellTax"] ); } // Displays a list of all current taxes function getBuyTaxes() public view returns( uint marketingBuyTax, uint developmentBuyTax, uint coreteamBuyTax, uint daoandfarmingBuyTax ) { return ( txTaxes["marketingBuyTax"], txTaxes["developmentBuyTax"], txTaxes["coreteamBuyTax"], txTaxes["daoandfarmingBuyTax"] ); } // Set the DAO and Farming Tax Receiver Address (daoandfarmingAddress) function setDAOandFarmingAddress(address _daoandfarmingAddress) external onlyOwner { daoandfarmingAddress = _daoandfarmingAddress; } // Set the Marketing Tax Receiver Address (marketingAddress) function setMarketingAddress(address _marketingAddress) external onlyOwner { marketingAddress = _marketingAddress; } // Set the Development Tax Receiver Address (developmentAddress) function setDevelopmentAddress(address _developmentAddress) external onlyOwner { developmentAddress = _developmentAddress; } // Set the Core-Team Tax Receiver Address (coreteamAddress) function setCoreTeamAddress(address _coreteamAddress) external onlyOwner { coreteamAddress = _coreteamAddress; } // Exclude an address from tax function setExcludeFromTax(address _address, bool _value) external onlyOwner { excludeFromTax[_address] = _value; } // Exclude an address from maximum transaction limit function setExclueFromMaxTx(address _address, bool _value) external onlyOwner { exclueFromMaxTx[_address] = _value; } // Set Buy Tax Tiers function setBuyTaxTiers(uint _discount1, uint _amount1, uint _discount2, uint _amount2) external onlyOwner { require(_discount1 > 0 && _discount1 < 100 && _discount2 > 0 && _discount2 < 100 && _amount1 > 0 && _amount2 > 0, "Values have to be bigger than zero!"); taxTiers[0].taxDiscount = _discount1; taxTiers[0].amount = _amount1; taxTiers[1].taxDiscount = _discount2; taxTiers[1].amount = _amount2; } // Set Sell Tax Tiers function setSellTaxTiers(uint _discount3, uint _amount3, uint _discount4, uint _amount4) external onlyOwner { require(_discount3 > 0 && _discount3 < 100 && _discount4 > 0 && _discount4 < 100 && _amount3 > 0 && _amount4 > 0, "Values have to be bigger than zero!"); taxTiers[2].taxDiscount = _discount3; taxTiers[2].amount = _amount3; taxTiers[3].taxDiscount = _discount4; taxTiers[3].amount = _amount4; } // Get Buy Tax Tiers function getBuyTaxTiers() public view returns(uint discount1, uint amount1, uint discount2, uint amount2) { return (taxTiers[0].taxDiscount, taxTiers[0].amount, taxTiers[1].taxDiscount, taxTiers[1].amount); } // Get Sell Tax Tiers function getSellTaxTiers() public view returns(uint discount3, uint amount3, uint discount4, uint amount4) { return (taxTiers[2].taxDiscount, taxTiers[2].amount, taxTiers[3].taxDiscount, taxTiers[3].amount); } // Set Transaction Settings: Max Buy Limit, Max Sell Limit, Cooldown Limit. function setTxSettings(uint _buyMaxTx, uint _sellMaxTx, uint _txcooldown) external onlyOwner { require(_buyMaxTx >= _totalSupply.div(200), "Buy transaction limit is too low!"); // 0.5% require(_sellMaxTx >= _totalSupply.div(400), "Sell transaction limit is too low!"); // 0.25% require(_txcooldown <= 4 minutes, "Cooldown should be 4 minutes or less!"); txSettings.buyMaxTx = _buyMaxTx; txSettings.sellMaxTx = _sellMaxTx; txSettings.txcooldown = _txcooldown; } // Get Max Transaction Settings: Max Buy, Max Sell, Cooldown Limit. function getTxSettings() public view returns(uint buyMaxTx, uint sellMaxTx, uint txcooldown) { return (txSettings.buyMaxTx, txSettings.sellMaxTx, txSettings.txcooldown); } // Check Buy Limit During A Cooldown (used in _transfer) function checkBuyTxLimit(address _sender, uint256 _amount) internal view { require( exclueFromMaxTx[_sender] == true || txSettings.buys[_sender].add(_amount) < txSettings.buyMaxTx, "Buy transaction limit reached!" ); } // Check Sell Limit During A Cooldown (used in _transfer) function checkSellTxLimit(address _sender, uint256 _amount) internal view { require( exclueFromMaxTx[_sender] == true || txSettings.sells[_sender].add(_amount) < txSettings.sellMaxTx, "Sell transaction limit reached!" ); } // Saves the recent buys & sells during a cooldown (used in _transfer) function setRecentTx(bool _isSell, address _sender, uint _amount) internal { if(txSettings.lastTx[_sender].add(txSettings.txcooldown) < block.timestamp) { _isSell ? txSettings.sells[_sender] = _amount : txSettings.buys[_sender] = _amount; } else { _isSell ? txSettings.sells[_sender] += _amount : txSettings.buys[_sender] += _amount; } txSettings.lastTx[_sender] = block.timestamp; } // Get the recent buys, sells, and the last transaction function getRecentTx(address _address) public view returns(uint buys, uint sells, uint lastTx) { return (txSettings.buys[_address], txSettings.sells[_address], txSettings.lastTx[_address]); } // Get $DEWO Token Price In BNB function getTokenPrice(uint _amount) public view returns(uint) { IPancakeswapV2Pair pcsPair = IPancakeswapV2Pair(pair); IERC20 token1 = IERC20(pcsPair.token1()); (uint Res0, uint Res1,) = pcsPair.getReserves(); uint res0 = Res0*(10**token1.decimals()); return((_amount.mul(res0)).div(Res1)); } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] -= amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token taxes, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); uint marketingFee; uint developmentFee; uint coreteamFee; uint daoandfarmingFee; uint taxDiscount; bool hasTaxes = true; // Buys from PancakeSwap's $DEWO pool if(from == pair) { checkBuyTxLimit(to, amount); setRecentTx(false, to, amount); marketingFee = txTaxes["marketingBuyTax"]; developmentFee = txTaxes["developmentBuyTax"]; coreteamFee = txTaxes["coreteamBuyTax"]; daoandfarmingFee = txTaxes["daoandfarmingBuyTax"]; // Transaction Tax Tiers 2 & 3 - Discounted Rate if(amount >= taxTiers[0].amount && amount < taxTiers[1].amount) { taxDiscount = taxTiers[0].taxDiscount; } else if(amount >= taxTiers[1].amount) { taxDiscount = taxTiers[1].taxDiscount; } } // Sells from PancakeSwap's $DEWO pool else if(to == pair) { checkSellTxLimit(from, amount); setRecentTx(true, from, amount); marketingFee = txTaxes["marketingSellTax"]; developmentFee = txTaxes["developmentSellTax"]; coreteamFee = txTaxes["coreteamSellTax"]; daoandfarmingFee = txTaxes["daoandfarmingSellTax"]; // Calculate the balance after this transaction uint newBalanceAmount = fromBalance.sub(amount); // Transaction Tax Tiers 2 & 3 - Discounted Rate if(newBalanceAmount >= taxTiers[2].amount && newBalanceAmount < taxTiers[3].amount) { taxDiscount = taxTiers[2].taxDiscount; } else if(newBalanceAmount >= taxTiers[3].amount) { taxDiscount = taxTiers[3].taxDiscount; } } unchecked { _balances[from] = fromBalance - amount; } if(excludeFromTax[to] || excludeFromTax[from]) { hasTaxes = false; } // Calculate taxes if this wallet is not excluded and buys/sells from $DEWO's PCS pair pool if(hasTaxes && (to == pair || from == pair)) { DEWOTokenTax memory DEWOTokenTaxes; DEWOTokenTaxes.forDAOAndFarming = amount.mul(daoandfarmingFee).mul(100 - taxDiscount).div(10000); DEWOTokenTaxes.forDevelopment = amount.mul(developmentFee).mul(100 - taxDiscount).div(10000); DEWOTokenTaxes.forCoreTeam = amount.mul(coreteamFee).mul(100 - taxDiscount).div(10000); DEWOTokenTaxes.forMarketing = amount.mul(marketingFee).mul(100 - taxDiscount).div(10000); // Calculate total taxes and deduct from the transfered amount uint totalTaxes = DEWOTokenTaxes.forDAOAndFarming .add(DEWOTokenTaxes.forDevelopment) .add(DEWOTokenTaxes.forCoreTeam) .add(DEWOTokenTaxes.forMarketing); amount = amount.sub(totalTaxes); // Pay DAO And Farming Taxes _balances[daoandfarmingAddress] += DEWOTokenTaxes.forDAOAndFarming; emit Transfer(from, daoandfarmingAddress, DEWOTokenTaxes.forDAOAndFarming); // Pay Development Fund Taxes _balances[developmentAddress] += DEWOTokenTaxes.forDevelopment; emit Transfer(from, developmentAddress, DEWOTokenTaxes.forDevelopment); // Pay Core-Team Taxes _balances[coreteamAddress] += DEWOTokenTaxes.forCoreTeam; emit Transfer(from, coreteamAddress, DEWOTokenTaxes.forCoreTeam); // Pay Marketing Taxes _balances[marketingAddress] += DEWOTokenTaxes.forMarketing; emit Transfer(from, marketingAddress, DEWOTokenTaxes.forMarketing); } _balances[to] += amount; emit Transfer(from, to, 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 Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } }
Exclude an address from maximum transaction limit
function setExclueFromMaxTx(address _address, bool _value) external onlyOwner { exclueFromMaxTx[_address] = _value; }
14,413,859
//Address: 0x7DCDE80B9E6eAaC35Cd5E0225F17cf8a418314cc //Contract name: KelevinKoin //Balance: 0 Ether //Verification Date: 2/22/2018 //Transacion Count: 2 // CODE STARTS HERE pragma solidity ^0.4.16; contract Owned { address public owner; mapping(address => bool) public owners; function Owned() public { owner = msg.sender; owners[msg.sender] = true; } modifier onlyOwners{ address sen = msg.sender; require(owners[msg.sender] == true); _; } modifier onlyOwner{ require(msg.sender == owner); _; } modifier onlyOwnerOrigin{ require(tx.origin == owner); _; } function addOwner(address newOwner) public onlyOwners{ owners[newOwner] = true; } function removeOwner() public onlyOwners{ owners[msg.sender] = false; } function removeOwner(address newOwner) public onlyOwner{ owners[newOwner] = false; } function isOwner(address o) public view returns(bool){ return owners[o] == true; } } //Can be used by other contracts to get approval to spend tokens interface TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 is Owned { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; 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); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Burn(address indexed from, uint256 value); function TokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 dec) public { // totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount totalSupply = initialSupply; // Update total supply with the decimal amount balanceOf[this] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = dec; } function transfer(address _from, address _to, uint _value) 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]); // 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); } function transfer(address _to, uint256 _value) public { transfer(msg.sender, _to, _value); } 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; } function approve(address _spender, uint256 _value) public returns(bool success){ allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } 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; } } function burn(uint256 _value) public returns(bool success){ require(balanceOf[msg.sender] >= _value); // 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) public returns(bool success){ require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } } contract MifflinToken is Owned, TokenERC20 { uint8 public tokenId; uint256 ethDolRate = 1000; uint256 weiRate = 1000000000000000000; address exchange; uint256 public buyPrice; uint256 public totalContribution = 0; uint256 public highestContribution = 0; uint256 public lowestContribution = 2 ** 256 - 1; uint256 public totalBought = 0; mapping(address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); function MifflinToken(address exad, uint8 tid, uint256 issue, string tokenName, string tokenSymbol, uint8 dec) TokenERC20(issue * 10 ** uint256(dec), tokenName, tokenSymbol, dec) public { tokenId = tid; MifflinMarket e = MifflinMarket(exad); e.setToken(tokenId,this); exchange = exad; addOwner(exchange); } function buy(uint _value) internal { transfer(this, msg.sender, _value); totalBought += _value; } function transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require(balanceOf[_from] >= _value); // Check if the sender has enough require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient Transfer(_from, _to, _value); } // public methods to give and take that only owners can call function give(address _to, uint256 _value) public onlyOwners returns(bool success){ transfer(this, _to, _value); return true; } function take(address _from, uint256 _value) public onlyOwners returns(bool success){ transfer(_from, this, _value); return true; } // / @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) public onlyOwners{ frozenAccount[target] = freeze; FrozenFunds(target, freeze); } // / @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth // / @param newBuyPrice Price users can buy from the contract function setBuyPrice(uint256 newBuyPrice) public onlyOwners{ buyPrice = newBuyPrice; } // RULE we always lower the price any time there is a new high contribution! function contribution(uint256 amount)internal returns(int highlow){ owner.transfer(msg.value); totalContribution += msg.value; if (amount > highestContribution) { uint256 oneper = buyPrice * 99 / 100; // lower by 1%* uint256 fullper = buyPrice * highestContribution / amount; // lower by how much you beat the prior contribution if(fullper > oneper) buyPrice = fullper; else buyPrice = oneper; highestContribution = amount; // give reward MifflinMarket(exchange).highContributionAward(msg.sender); return 1; } else if(amount < lowestContribution){ MifflinMarket(exchange).lowContributionAward(msg.sender); lowestContribution = amount; return -1; } else return 0; } // sell tokens back to sender using owners ether function sell(uint256 amount) public { transfer(msg.sender, this, amount); // makes the transfers } } /******************************************/ /* CUSTOM MIFFLIN TOKENS */ /******************************************/ contract BeetBuck is Owned, MifflinToken { function BeetBuck(address exchange)MifflinToken(exchange, 2, 2000000, "Beet Buck", "BEET", 8) public { buyPrice = weiRate / ethDolRate / uint(10) ** decimals; // 1d } function () payable public { contribution(msg.value); uint256 amountToGive = 0; uint256 price = buyPrice; if (totalBought < 10000) { price -= price * 15 / 100; } else if (totalBought < 50000) { price -= price / 10; } else if (totalBought < 100000) { price -= price / 20; } else if (totalBought < 200000) { price -= price / 100; } amountToGive += msg.value / price; buy(amountToGive); } } contract NapNickel is Owned, MifflinToken { function NapNickel(address exchange) MifflinToken(exchange, 3, 1000000000, "Nap Nickel", "NAPP", 8) public { buyPrice = weiRate / ethDolRate / uint(10) ** decimals / 20; // 5c } function () payable public { contribution(msg.value); uint256 price = buyPrice; uint256 estTime = block.timestamp - 5 * 60 * 60; uint8 month; uint8 day; uint8 hour; uint8 weekday; (, month,day,hour,,,weekday) = parseTimestampParts(estTime); if (month == 4 && day == 26) { // its pretzel day price += buyPrice / 5; } else if (weekday == 0 || weekday == 6) { // buying during weekend, get off my property price += buyPrice * 15 / 100; } else if (hour < 9 || hour >= 17) { // buying outside of work hours, im in my hot tub price += buyPrice / 10; } else if (hour > 12 && hour < 13) { // buying during lunch, leave me alone dammit price += buyPrice / 20; } uint256 amountToGive = 0; amountToGive += msg.value / price; buy(amountToGive); } struct _DateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) public pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) public pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestampParts(uint timestamp) public pure returns (uint16 year,uint8 month,uint8 day, uint8 hour,uint8 minute,uint8 second,uint8 weekday) { _DateTime memory dt = parseTimestamp(timestamp); return (dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second,dt.weekday); } function parseTimestamp(uint timestamp) internal pure returns (_DateTime dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } // Hour dt.hour = getHour(timestamp); // Minute dt.minute = getMinute(timestamp); // Second dt.second = getSecond(timestamp); // Day of week. dt.weekday = getWeekday(timestamp); } function getYear(uint timestamp) public pure returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).day; } function getHour(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getMinute(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60) % 60); } function getSecond(uint timestamp) public pure returns (uint8) { return uint8(timestamp % 60); } function getWeekday(uint timestamp) public pure returns (uint8) { return uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } } contract QuabityQuarter is Owned, MifflinToken { uint lastContributionTime = 0; function QuabityQuarter(address exchange) MifflinToken(exchange, 4, 420000000, "Quabity Quarter", "QUAB", 8) public { buyPrice = weiRate / ethDolRate / uint(10) ** decimals / 4; // 25c } function () payable public { contribution(msg.value); uint256 amountToGive = 0; amountToGive += msg.value / buyPrice; uint256 time = block.timestamp; uint256 diff = time - lastContributionTime / 60 / 60; uint256 chance = 0; if (diff > 96) chance = 50; if (diff > 48) chance = 40; else if (diff > 24) chance = 30; else if (diff > 12) chance = 20; else if (diff > 1) chance = 10; else chance = 5; if (chance > 0) { uint256 lastBlockHash = uint256(keccak256(block.blockhash(block.number - 1), uint8(0))); if (lastBlockHash % 100 < chance) { // stole 10% extra! amountToGive += amountToGive / 10; }} buy(amountToGive); } } contract KelevinKoin is Owned, MifflinToken { function KelevinKoin(address exchange) MifflinToken(exchange, 5, 69000000, "Kelevin Koin", "KLEV", 8) public { buyPrice = weiRate / ethDolRate / uint(10) ** decimals / 50; // 2c } function () payable public { contribution(msg.value); // have to balance the books! uint256 lastBlockHash = uint256(keccak256(block.blockhash(block.number - 1), uint8(0))); uint256 newPrice = buyPrice + ((lastBlockHash % (buyPrice * 69 / 1000)) - (buyPrice * 69 * 2 / 1000)); buyPrice = newPrice; uint256 amountToGive = msg.value / buyPrice; if (buyPrice % msg.value == 0) amountToGive += amountToGive * 69 / 1000; // add 6.9% buy(amountToGive); } } contract NnexNote is Owned, MifflinToken { function NnexNote(address exchange) MifflinToken(exchange, 6, 666000000, "Nnex Note", "NNEX", 8) public { buyPrice = weiRate / ethDolRate / uint(10) ** decimals / 100; // 1c } // Do you really want a Nnex Note? function () payable public { // this is the only place I have human contact, so the more the better contribution(msg.value); // you can get up to a 50% discount uint maxDiscountRange = buyPrice * 100; uint discountPercent; if(msg.value >= maxDiscountRange) discountPercent = 100; else discountPercent = msg.value / maxDiscountRange * 100; uint price = buyPrice - (buyPrice / 2) * (discountPercent / 100); uint amountToGive = msg.value / price; buy(amountToGive); } } contract DundieDollar is Owned, MifflinToken { mapping(uint8 => string) public awards; uint8 public awardsCount; mapping(address => mapping(uint8 => uint256)) public awardsOf; function DundieDollar(address exchange) MifflinToken(exchange, 1, 1725000000, "Dundie Dollar", "DUND", 0) public { buyPrice = weiRate / ethDolRate * 10; // 10d awards[0] = "Best Dad Award"; awards[1] = "Best Mom Award"; awards[2] = "Hottest in the Office Award"; awards[3] = "Diabetes Award"; awards[4] = "Promising Assistant Manager Award"; awards[5] = "Cutest Redhead in the Office Award"; awards[6] = "Best Host Award"; awards[7] = "Doobie Doobie Pothead Stoner of the Year Award"; awards[8] = "Extreme Repulsiveness Award"; awards[9] = "Redefining Beauty Award"; awards[10] = "Kind of A Bitch Award"; awards[11] = "Moving On Up Award"; awards[12] = "Worst Salesman of the Year"; awards[13] = "Busiest Beaver Award"; awards[14] = "Tight-Ass Award"; awards[15] = "Spicy Curry Award"; awards[16] = "Don't Go in There After Me"; awards[17] = "Fine Work Award"; awards[18] = "Whitest Sneakers Award"; awards[19] = "Great Work Award"; awards[20] = "Longest Engagement Award"; awards[21] = "Show Me the Money Award"; awards[22] = "Best Boss Award"; awards[23] = "Grace Under Fire Award"; awardsCount = 24; } function addAward(string name) public onlyOwners{ awards[awardsCount] = name; awardsCount++; } function () payable public { contribution(msg.value); uint256 amountToGive = msg.value / buyPrice; buy(amountToGive); } function transfer(address _from, address _to, uint _value) internal { super.transfer(_from,_to,_value); transferAwards(_from,_to,_value); } //This should only be called from the above function function transferAwards(address _from, address _to, uint _value) internal { uint256 lastBlockHash = uint256(keccak256(block.blockhash(block.number - 1), uint8(0))) + _value; uint8 award = uint8(lastBlockHash % awardsCount); if(_from == address(this)) { //dont need to loop through awards transferAwards(_from,_to,award,_value); } else { // only take awards that they have uint left = _value; for (uint8 i = 0; i < awardsCount; i++) { uint256 bal = awardBalanceOf(_from,award); if(bal > 0){ if(bal < left) { transferAwards(_from,_to,award,bal); left -= bal; } else { transferAwards(_from,_to,award,left); left = 0; } } if(left == 0) break; award ++; if(award == awardsCount - 1) award = 0; // reset } } } function transferAwards(address from, address to, uint8 award , uint value) internal { //dont try to take specific awards from the contract if(from != address(this)) { require(awardBalanceOf(from,award) >= value ); awardsOf[from][award] -= value; } //dont try to send specific awards to the contract if(to != address(this)) awardsOf[to][award] += value; } function awardBalanceOf(address addy,uint8 award) view public returns(uint){ return awardsOf[addy][award]; } function awardName(uint8 id) view public returns(string) { return awards[id]; } } contract MifflinMarket is Owned { mapping(uint8 => address) public tokenIds; //mapping(uint8 => mapping(uint8 => uint256)) exchangeRates; mapping(uint8 => mapping(uint8 => int256)) public totalExchanged; uint8 rewardTokenId = 1; bool active; function MifflinMarket() public { active = true; } modifier onlyTokens { MifflinToken mt = MifflinToken(msg.sender); // make sure sender is a token contract require(tokenIds[mt.tokenId()] == msg.sender); _; } function setToken(uint8 tid,address addy) public onlyOwnerOrigin { // Only add tokens that were created by exchange owner tokenIds[tid] = addy; } function removeToken(uint8 id) public onlyOwner { // Only add tokens that were created by owner tokenIds[id] = 0; } function setActive(bool act) public onlyOwner { active = act; } function getRewardToken() public view returns(MifflinToken){ return getTokenById(rewardTokenId); } function getTokenById(uint8 id) public view returns(MifflinToken){ require(tokenIds[id] > 0); return MifflinToken(tokenIds[id]); } function getTokenByAddress(address addy) public view returns(MifflinToken){ MifflinToken token = MifflinToken(addy); uint8 tokenId = token.tokenId(); require(tokenIds[tokenId] == addy); return token; } function exchangeTokensByAddress(uint256 fromAmount, address from, address to) public { require(active); uint256 takeAmount = fromAmount; MifflinToken fromToken = getTokenByAddress(from); MifflinToken toToken = getTokenByAddress(to); uint8 fromId = fromToken.tokenId(); uint8 toId = toToken.tokenId(); uint256 fromPrice = fromToken.buyPrice(); uint256 toPrice = toToken.buyPrice(); uint256 toAmount = fromAmount * fromPrice / toPrice; takeAmount = toAmount * toPrice / fromPrice; // take fromTokens back to contract fromToken.take(msg.sender, takeAmount); // give toTokens out from contract toToken.give(msg.sender, toAmount); // update some stats totalExchanged[fromId][toId] += int(toAmount); totalExchanged[toId][fromId] -= int(takeAmount); } // most basic exchange - just calculates price ratio function exchangeTokensById(uint256 fromAmount, uint8 from, uint8 to) public { address fromAddress = tokenIds[from]; address toAddress = tokenIds[to]; exchangeTokensByAddress(fromAmount,fromAddress,toAddress); //adjust price? } function highContributionAward(address to) public onlyTokens { MifflinToken reward = getRewardToken(); //dont throw an error if there are no more tokens if(reward.balanceOf(reward) > 0){ reward.give(to, 1); } } function lowContributionAward(address to) public onlyTokens { MifflinToken reward = getRewardToken(); //dont throw an error here since this is just sugar if(reward.balanceOf(to) > 0){ reward.take(to, 1); } } }
/ Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth / newBuyPrice Price users can buy from the contract
function setBuyPrice(uint256 newBuyPrice) public onlyOwners{ buyPrice = newBuyPrice; }
12,620,287
pragma solidity ^0.4.24; contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } 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 ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract HEARTToken is ERC20Interface, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ constructor() public { symbol = "HEART"; name = "allHeart"; decimals = 18; _totalSupply = 1000000000000000000000000000000000; balances[0x028e6F5dCd0914977095425C94F96B943CB7AC90] = _totalSupply; emit Transfer(address(0), 0x028e6F5dCd0914977095425C94F96B943CB7AC90, _totalSupply); } // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ function () public payable { revert(); } }
------------------------------------------------------------------------
function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; }
5,806,207
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface iuniswap2 { //inject NONSTANDARD NAMING // To convert DAI to ETH function SWAPEXACTTOKENSFORETH53(uint AMOUNTIN88, uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING // To convert ETH to YELD and burn it function SWAPEXACTETHFORTOKENS6(uint AMOUNTOUTMIN99, address[] calldata PATH78, address TO76, uint DEADLINE33) external payable returns (uint[] memory AMOUNTS56); //inject NONSTANDARD NAMING } interface ierc2093 { //inject NONSTANDARD NAMING function TOTALSUPPLY70() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF25(address ACCOUNT45) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE65(address OWNER26, address SPENDER52) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE3(address SPENDER52, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER22(address indexed FROM88, address indexed TO76, uint256 VALUE83); //inject NONSTANDARD NAMING event APPROVAL93(address indexed OWNER26, address indexed SPENDER52, uint256 VALUE83); //inject NONSTANDARD NAMING } contract context61 { //inject NONSTANDARD NAMING constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER82() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA79() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ownable93 is context61 { //inject NONSTANDARD NAMING address payable private _OWNER43; //inject NONSTANDARD NAMING event OWNERSHIPTRANSFERRED63(address indexed PREVIOUSOWNER24, address indexed NEWOWNER52); //inject NONSTANDARD NAMING constructor () internal { _OWNER43 = _MSGSENDER82(); emit OWNERSHIPTRANSFERRED63(address(0), _OWNER43); } function OWNER99() public view returns (address payable) { //inject NONSTANDARD NAMING return _OWNER43; } modifier ONLYOWNER61() { //inject NONSTANDARD NAMING require(ISOWNER2(), "Ownable: caller is not the owner"); _; } function ISOWNER2() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER82() == _OWNER43; } function RENOUNCEOWNERSHIP13() public ONLYOWNER61 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED63(_OWNER43, address(0)); _OWNER43 = address(0); } function TRANSFEROWNERSHIP7(address payable NEWOWNER52) public ONLYOWNER61 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP60(NEWOWNER52); } function _TRANSFEROWNERSHIP60(address payable NEWOWNER52) internal { //inject NONSTANDARD NAMING require(NEWOWNER52 != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED63(_OWNER43, NEWOWNER52); _OWNER43 = NEWOWNER52; } } contract erc2030 is context61, ierc2093 { //inject NONSTANDARD NAMING using safemath13 for uint256; mapping (address => uint256) _BALANCES15; //inject NONSTANDARD NAMING mapping (address => mapping (address => uint256)) private _ALLOWANCES69; //inject NONSTANDARD NAMING uint256 _TOTALSUPPLY32; //inject NONSTANDARD NAMING function TOTALSUPPLY70() public view returns (uint256) { //inject NONSTANDARD NAMING return _TOTALSUPPLY32; } function BALANCEOF25(address ACCOUNT45) public view returns (uint256) { //inject NONSTANDARD NAMING return _BALANCES15[ACCOUNT45]; } function TRANSFER37(address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER95(_MSGSENDER82(), RECIPIENT39, AMOUNT4); return true; } function ALLOWANCE65(address OWNER26, address SPENDER52) public view returns (uint256) { //inject NONSTANDARD NAMING return _ALLOWANCES69[OWNER26][SPENDER52]; } function APPROVE3(address SPENDER52, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, AMOUNT4); return true; } function TRANSFERFROM19(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER95(SENDER75, RECIPIENT39, AMOUNT4); _APPROVE30(SENDER75, _MSGSENDER82(), _ALLOWANCES69[SENDER75][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE47(address SPENDER52, uint256 ADDEDVALUE76) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].ADD27(ADDEDVALUE76)); return true; } function DECREASEALLOWANCE20(address SPENDER52, uint256 SUBTRACTEDVALUE75) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE30(_MSGSENDER82(), SPENDER52, _ALLOWANCES69[_MSGSENDER82()][SPENDER52].SUB57(SUBTRACTEDVALUE75, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER95(address SENDER75, address RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(SENDER75 != address(0), "ERC20: transfer from the zero address"); require(RECIPIENT39 != address(0), "ERC20: transfer to the zero address"); _BALANCES15[SENDER75] = _BALANCES15[SENDER75].SUB57(AMOUNT4, "ERC20: transfer amount exceeds balance"); _BALANCES15[RECIPIENT39] = _BALANCES15[RECIPIENT39].ADD27(AMOUNT4); emit TRANSFER22(SENDER75, RECIPIENT39, AMOUNT4); } function _MINT79(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(ACCOUNT45 != address(0), "ERC20: mint to the zero address"); _TOTALSUPPLY32 = _TOTALSUPPLY32.ADD27(AMOUNT4); _BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].ADD27(AMOUNT4); emit TRANSFER22(address(0), ACCOUNT45, AMOUNT4); } function _BURN68(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(ACCOUNT45 != address(0), "ERC20: burn from the zero address"); _BALANCES15[ACCOUNT45] = _BALANCES15[ACCOUNT45].SUB57(AMOUNT4, "ERC20: burn amount exceeds balance"); _TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(AMOUNT4); emit TRANSFER22(ACCOUNT45, address(0), AMOUNT4); } function _APPROVE30(address OWNER26, address SPENDER52, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(OWNER26 != address(0), "ERC20: approve from the zero address"); require(SPENDER52 != address(0), "ERC20: approve to the zero address"); _ALLOWANCES69[OWNER26][SPENDER52] = AMOUNT4; emit APPROVAL93(OWNER26, SPENDER52, AMOUNT4); } function _BURNFROM66(address ACCOUNT45, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING _BURN68(ACCOUNT45, AMOUNT4); _APPROVE30(ACCOUNT45, _MSGSENDER82(), _ALLOWANCES69[ACCOUNT45][_MSGSENDER82()].SUB57(AMOUNT4, "ERC20: burn amount exceeds allowance")); } } contract erc20detailed21 is ierc2093 { //inject NONSTANDARD NAMING string private _NAME42; //inject NONSTANDARD NAMING string private _SYMBOL85; //inject NONSTANDARD NAMING uint8 private _DECIMALS78; //inject NONSTANDARD NAMING constructor (string memory NAME99, string memory SYMBOL38, uint8 DECIMALS96) public { //inject NONSTANDARD NAMING _NAME42 = NAME99; _SYMBOL85 = SYMBOL38; _DECIMALS78 = DECIMALS96; } function NAME45() public view returns (string memory) { //inject NONSTANDARD NAMING return _NAME42; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _SYMBOL85; } function DECIMALS63() public view returns (uint8) { //inject NONSTANDARD NAMING return _DECIMALS78; } } contract reentrancyguard94 { //inject NONSTANDARD NAMING uint256 private _GUARDCOUNTER38; //inject NONSTANDARD NAMING constructor () internal { _GUARDCOUNTER38 = 1; } modifier NONREENTRANT47() { //inject NONSTANDARD NAMING _GUARDCOUNTER38 += 1; uint256 LOCALCOUNTER54 = _GUARDCOUNTER38; //inject NONSTANDARD NAMING _; require(LOCALCOUNTER54 == _GUARDCOUNTER38, "ReentrancyGuard: reentrant call"); } } library safemath13 { //inject NONSTANDARD NAMING function ADD27(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 C51 = A32 + B30; //inject NONSTANDARD NAMING require(C51 >= A32, "SafeMath: addition overflow"); return C51; } function SUB57(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB57(A32, B30, "SafeMath: subtraction overflow"); } function SUB57(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B30 <= A32, ERRORMESSAGE15); uint256 C51 = A32 - B30; //inject NONSTANDARD NAMING return C51; } function MUL24(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (A32 == 0) { return 0; } uint256 C51 = A32 * B30; //inject NONSTANDARD NAMING require(C51 / A32 == B30, "SafeMath: multiplication overflow"); return C51; } function DIV26(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV26(A32, B30, "SafeMath: division by zero"); } function DIV26(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(B30 > 0, ERRORMESSAGE15); uint256 C51 = A32 / B30; //inject NONSTANDARD NAMING return C51; } function MOD76(uint256 A32, uint256 B30) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD76(A32, B30, "SafeMath: modulo by zero"); } function MOD76(uint256 A32, uint256 B30, string memory ERRORMESSAGE15) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(B30 != 0, ERRORMESSAGE15); return A32 % B30; } } library address92 { //inject NONSTANDARD NAMING function ISCONTRACT77(address ACCOUNT45) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 CODEHASH48; //inject NONSTANDARD NAMING bytes32 ACCOUNTHASH81 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING // solhint-disable-next-line no-inline-assembly assembly { CODEHASH48 := extcodehash(ACCOUNT45) } return (CODEHASH48 != 0x0 && CODEHASH48 != ACCOUNTHASH81); } function TOPAYABLE47(address ACCOUNT45) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(ACCOUNT45)); } function SENDVALUE65(address payable RECIPIENT39, uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING require(address(this).balance >= AMOUNT4, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool SUCCESS17, ) = RECIPIENT39.call.value(AMOUNT4)(""); //inject NONSTANDARD NAMING require(SUCCESS17, "Address: unable to send value, recipient may have reverted"); } } library safeerc2059 { //inject NONSTANDARD NAMING using safemath13 for uint256; using address92 for address; function SAFETRANSFER30(ierc2093 TOKEN25, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFER37.selector, TO76, VALUE83)); } function SAFETRANSFERFROM76(ierc2093 TOKEN25, address FROM88, address TO76, uint256 VALUE83) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.TRANSFERFROM19.selector, FROM88, TO76, VALUE83)); } function SAFEAPPROVE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING require((VALUE83 == 0) || (TOKEN25.ALLOWANCE65(address(this), SPENDER52) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, VALUE83)); } function SAFEINCREASEALLOWANCE32(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).ADD27(VALUE83); //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45)); } function SAFEDECREASEALLOWANCE48(ierc2093 TOKEN25, address SPENDER52, uint256 VALUE83) internal { //inject NONSTANDARD NAMING uint256 NEWALLOWANCE45 = TOKEN25.ALLOWANCE65(address(this), SPENDER52).SUB57(VALUE83, "SafeERC20: decreased allowance below zero"); //inject NONSTANDARD NAMING CALLOPTIONALRETURN90(TOKEN25, abi.encodeWithSelector(TOKEN25.APPROVE3.selector, SPENDER52, NEWALLOWANCE45)); } function CALLOPTIONALRETURN90(ierc2093 TOKEN25, bytes memory DATA85) private { //inject NONSTANDARD NAMING require(address(TOKEN25).ISCONTRACT77(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool SUCCESS17, bytes memory RETURNDATA42) = address(TOKEN25).call(DATA85); //inject NONSTANDARD NAMING require(SUCCESS17, "SafeERC20: low-level call failed"); if (RETURNDATA42.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(RETURNDATA42, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface compound17 { //inject NONSTANDARD NAMING function MINT37 ( uint256 MINTAMOUNT46 ) external returns ( uint256 ); //inject NONSTANDARD NAMING function REDEEM71(uint256 REDEEMTOKENS65) external returns (uint256); //inject NONSTANDARD NAMING function EXCHANGERATESTORED22() external view returns (uint); //inject NONSTANDARD NAMING } interface fulcrum27 { //inject NONSTANDARD NAMING function MINT37(address RECEIVER66, uint256 AMOUNT4) external payable returns (uint256 MINTAMOUNT46); //inject NONSTANDARD NAMING function BURN1(address RECEIVER66, uint256 BURNAMOUNT5) external returns (uint256 LOANAMOUNTPAID4); //inject NONSTANDARD NAMING function ASSETBALANCEOF38(address _OWNER43) external view returns (uint256 BALANCE2); //inject NONSTANDARD NAMING } interface ilendingpooladdressesprovider93 { //inject NONSTANDARD NAMING function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING } interface aave60 { //inject NONSTANDARD NAMING function DEPOSIT43(address _RESERVE54, uint256 _AMOUNT50, uint16 _REFERRALCODE69) external; //inject NONSTANDARD NAMING } interface atoken49 { //inject NONSTANDARD NAMING function REDEEM71(uint256 AMOUNT4) external; //inject NONSTANDARD NAMING } interface iiearnmanager83 { //inject NONSTANDARD NAMING function RECOMMEND99(address _TOKEN3) external view returns ( //inject NONSTANDARD NAMING string memory CHOICE41, //inject NONSTANDARD NAMING uint256 CAPR5, //inject NONSTANDARD NAMING uint256 IAPR100, //inject NONSTANDARD NAMING uint256 AAPR96, //inject NONSTANDARD NAMING uint256 DAPR97 //inject NONSTANDARD NAMING ); } contract structs50 { //inject NONSTANDARD NAMING struct Val { uint256 VALUE83; //inject NONSTANDARD NAMING } enum ActionType { Deposit, // supply tokens Withdraw // borrow tokens } enum AssetDenomination { Wei // the amount is denominated in wei } enum AssetReference { Delta // the amount is given as a delta from the current value } struct AssetAmount { bool SIGN32; // true if positive //inject NONSTANDARD NAMING AssetDenomination DENOMINATION0; //inject NONSTANDARD NAMING AssetReference REF97; //inject NONSTANDARD NAMING uint256 VALUE83; //inject NONSTANDARD NAMING } struct ActionArgs { ActionType ACTIONTYPE60; //inject NONSTANDARD NAMING uint256 ACCOUNTID6; //inject NONSTANDARD NAMING AssetAmount AMOUNT4; //inject NONSTANDARD NAMING uint256 PRIMARYMARKETID93; //inject NONSTANDARD NAMING uint256 SECONDARYMARKETID1; //inject NONSTANDARD NAMING address OTHERADDRESS81; //inject NONSTANDARD NAMING uint256 OTHERACCOUNTID93; //inject NONSTANDARD NAMING bytes DATA85; //inject NONSTANDARD NAMING } struct Info { address OWNER26; // The address that owns the account //inject NONSTANDARD NAMING uint256 NUMBER25; // A nonce that allows a single address to control many accounts //inject NONSTANDARD NAMING } struct Wei { bool SIGN32; // true if positive //inject NONSTANDARD NAMING uint256 VALUE83; //inject NONSTANDARD NAMING } } contract dydx100 is structs50 { //inject NONSTANDARD NAMING function GETACCOUNTWEI65(Info memory ACCOUNT45, uint256 MARKETID4) public view returns (Wei memory); //inject NONSTANDARD NAMING function OPERATE53(Info[] memory, ActionArgs[] memory) public; //inject NONSTANDARD NAMING } interface lendingpooladdressesprovider85 { //inject NONSTANDARD NAMING function GETLENDINGPOOL88() external view returns (address); //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE37() external view returns (address); //inject NONSTANDARD NAMING } contract yusdc19 is erc2030, erc20detailed21, reentrancyguard94, structs50, ownable93 { //inject NONSTANDARD NAMING using safeerc2059 for ierc2093; using address92 for address; using safemath13 for uint256; struct Deposit { uint256 AMOUNT4; //inject NONSTANDARD NAMING uint256 START33; // Block when it started //inject NONSTANDARD NAMING } uint256 public POOL37; //inject NONSTANDARD NAMING address public TOKEN25; //inject NONSTANDARD NAMING address public COMPOUND53; //inject NONSTANDARD NAMING address public FULCRUM19; //inject NONSTANDARD NAMING address public AAVE10; //inject NONSTANDARD NAMING address public AAVEPOOL17; //inject NONSTANDARD NAMING address public AAVETOKEN8; //inject NONSTANDARD NAMING address public DYDX62; //inject NONSTANDARD NAMING uint256 public DTOKEN6; //inject NONSTANDARD NAMING address public APR50; //inject NONSTANDARD NAMING address public CHAI29; //inject NONSTANDARD NAMING // Add other tokens if implemented for another stablecoin address public UNISWAPROUTER94 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //inject NONSTANDARD NAMING address public USDC51 = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; //inject NONSTANDARD NAMING address public WETH0 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //inject NONSTANDARD NAMING address payable public RETIREMENTYELDTREASURY39; //inject NONSTANDARD NAMING ierc2093 public YELDTOKEN43; //inject NONSTANDARD NAMING uint256 public MAXIMUMTOKENSTOBURN49 = 50000 * 1e18; //inject NONSTANDARD NAMING uint256 public constant minimumeffectamount5 = 5 * 10 ** 18; //inject NONSTANDARD NAMING // When you stake say 1000 USDC for a day that will be your maximum // if you stake the next time 300 USDC your maximum will stay the same // if you stake 2000 at once it will increase to 2000 USDC mapping(bytes32 => uint256) public NUMBEROFPARTICIPANTS77; //inject NONSTANDARD NAMING mapping(address => Deposit) public DEPOSITS12; //inject NONSTANDARD NAMING uint256 public constant onedayinblocks19 = 6500; //inject NONSTANDARD NAMING uint256 public YELDTOREWARDPERDAY12 = 100e18; // 100 YELD per day per 1 million stablecoins padded with 18 zeroes to have that flexibility //inject NONSTANDARD NAMING uint256 public constant onemillion14 = 1e6; //inject NONSTANDARD NAMING enum Lender { NONE, DYDX, COMPOUND, AAVE, FULCRUM } Lender public PROVIDER42 = Lender.NONE; //inject NONSTANDARD NAMING constructor (address _YELDTOKEN72, address payable _RETIREMENTYELDTREASURY14) public payable erc20detailed21("yearn USDC", "yUSDC", 18) { //inject NONSTANDARD NAMING TOKEN25 = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); APR50 = address(0xdD6d648C991f7d47454354f4Ef326b04025a48A8); DYDX62 = address(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e); AAVE10 = address(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); AAVEPOOL17 = address(0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3); FULCRUM19 = address(0x493C57C4763932315A328269E1ADaD09653B9081); AAVETOKEN8 = address(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d); COMPOUND53 = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); CHAI29 = address(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); DTOKEN6 = 3; YELDTOKEN43 = ierc2093(_YELDTOKEN72); RETIREMENTYELDTREASURY39 = _RETIREMENTYELDTREASURY14; APPROVETOKEN12(); } // To receive ETH after converting it from USDC function () external payable {} function SETRETIREMENTYELDTREASURY49(address payable _TREASURY6) public ONLYOWNER61 { //inject NONSTANDARD NAMING RETIREMENTYELDTREASURY39 = _TREASURY6; } // In case a new uniswap router version is released function SETUNISWAPROUTER20(address _UNISWAPROUTER42) public ONLYOWNER61 { //inject NONSTANDARD NAMING UNISWAPROUTER94 = _UNISWAPROUTER42; } function EXTRACTTOKENSIFSTUCK53(address _TOKEN3, uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING ierc2093(_TOKEN3).TRANSFER37(msg.sender, _AMOUNT50); } function EXTRACTETHIFSTUCK0() public ONLYOWNER61 { //inject NONSTANDARD NAMING OWNER99().transfer(address(this).balance); } function CHANGEYELDTOREWARDPERDAY13(uint256 _AMOUNT50) public ONLYOWNER61 { //inject NONSTANDARD NAMING YELDTOREWARDPERDAY12 = _AMOUNT50; } function GETGENERATEDYELDS73() public view returns(uint256) { //inject NONSTANDARD NAMING uint256 BLOCKSPASSED1; //inject NONSTANDARD NAMING if (DEPOSITS12[msg.sender].START33 > 0) { BLOCKSPASSED1 = block.number.SUB57(DEPOSITS12[msg.sender].START33); } else { BLOCKSPASSED1 = 0; } // This will work because amount is a token with 18 decimals // Take the deposit, reduce it by 1 million (by removing 6 zeroes) so you get 1 // That 1 means get 1 YELD per day (in blocks). Now multiply that 1 by 100 to get 100 YELD per day // your deposits in dai div by 1 million * by yeld to reward / 1e18 since yeldToReward is in 18 decimals to be able to provide a smaller price since // we can't go below 1 in a variable. You can't make the price 0.00001 that's why we need that 1e18 padding uint256 GENERATEDYELDS87 = DEPOSITS12[msg.sender].AMOUNT4.DIV26(onemillion14).MUL24(YELDTOREWARDPERDAY12.DIV26(1e18)).MUL24(BLOCKSPASSED1).DIV26(onedayinblocks19); //inject NONSTANDARD NAMING return GENERATEDYELDS87; } function EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99() public { //inject NONSTANDARD NAMING require(DEPOSITS12[msg.sender].START33 > 0 && DEPOSITS12[msg.sender].AMOUNT4 > 0, 'Must have deposited stablecoins beforehand'); uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4, block.number); YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87); } function DEPOSIT43(uint256 _AMOUNT50) //inject NONSTANDARD NAMING external NONREENTRANT47 { require(_AMOUNT50 > 0, "deposit must be greater than 0"); POOL37 = CALCPOOLVALUEINTOKEN17(); ierc2093(TOKEN25).SAFETRANSFERFROM76(msg.sender, address(this), _AMOUNT50); // Yeld if (GETGENERATEDYELDS73() > 0) EXTRACTYELDEARNINGSWHILEKEEPINGDEPOSIT99(); DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.ADD27(_AMOUNT50), block.number); // Yeld // Calculate pool shares uint256 SHARES22 = 0; //inject NONSTANDARD NAMING if (POOL37 == 0) { SHARES22 = _AMOUNT50; POOL37 = _AMOUNT50; } else { SHARES22 = (_AMOUNT50.MUL24(_TOTALSUPPLY32)).DIV26(POOL37); } POOL37 = CALCPOOLVALUEINTOKEN17(); _MINT79(msg.sender, SHARES22); } // Converts USDC to ETH and returns how much ETH has been received from Uniswap function USDCTOETH25(uint256 _AMOUNT50) internal returns(uint256) { //inject NONSTANDARD NAMING ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, 0); ierc2093(USDC51).SAFEAPPROVE32(UNISWAPROUTER94, _AMOUNT50); address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING PATH78[0] = USDC51; PATH78[1] = WETH0; // swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) // 'amounts' is an array where [0] is input USDC amount and [1] is the resulting ETH after the conversion // even tho we've specified the WETH address, we'll receive ETH since that's how it works on uniswap // https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensforeth uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTTOKENSFORETH53(_AMOUNT50, uint(0), PATH78, address(this), now.ADD27(1800)); //inject NONSTANDARD NAMING return AMOUNTS56[1]; } // Buys YELD tokens paying in ETH on Uniswap and removes them from circulation // Returns how many YELD tokens have been burned function BUYNBURN98(uint256 _ETHTOSWAP66) internal returns(uint256) { //inject NONSTANDARD NAMING address[] memory PATH78 = new address[](2); //inject NONSTANDARD NAMING PATH78[0] = WETH0; PATH78[1] = address(YELDTOKEN43); // Burns the tokens by taking them out of circulation, sending them to the 0x0 address uint[] memory AMOUNTS56 = iuniswap2(UNISWAPROUTER94).SWAPEXACTETHFORTOKENS6.value(_ETHTOSWAP66)(uint(0), PATH78, address(0), now.ADD27(1800)); //inject NONSTANDARD NAMING return AMOUNTS56[1]; } // No rebalance implementation for lower fees and faster swaps function WITHDRAW27(uint256 _SHARES43) //inject NONSTANDARD NAMING external NONREENTRANT47 { require(_SHARES43 > 0, "withdraw must be greater than 0"); uint256 IBALANCE43 = BALANCEOF25(msg.sender); //inject NONSTANDARD NAMING require(_SHARES43 <= IBALANCE43, "insufficient balance"); POOL37 = CALCPOOLVALUEINTOKEN17(); uint256 R82 = (POOL37.MUL24(_SHARES43)).DIV26(_TOTALSUPPLY32); //inject NONSTANDARD NAMING _BALANCES15[msg.sender] = _BALANCES15[msg.sender].SUB57(_SHARES43, "redeem amount exceeds balance"); _TOTALSUPPLY32 = _TOTALSUPPLY32.SUB57(_SHARES43); emit TRANSFER22(msg.sender, address(0), _SHARES43); uint256 B30 = ierc2093(TOKEN25).BALANCEOF25(address(this)); //inject NONSTANDARD NAMING if (B30 < R82) { _WITHDRAWSOME38(R82.SUB57(B30)); } // Yeld uint256 GENERATEDYELDS87 = GETGENERATEDYELDS73(); //inject NONSTANDARD NAMING uint256 HALFPROFITS96 = (R82.SUB57(DEPOSITS12[msg.sender].AMOUNT4, '#3 Half profits sub error')).DIV26(2); //inject NONSTANDARD NAMING DEPOSITS12[msg.sender] = Deposit(DEPOSITS12[msg.sender].AMOUNT4.SUB57(_SHARES43), block.number); YELDTOKEN43.TRANSFER37(msg.sender, GENERATEDYELDS87); // Take a portion of the profits for the buy and burn and retirement yeld // Convert half the USDC earned into ETH for the protocol algorithms if (HALFPROFITS96 > minimumeffectamount5) { uint256 STAKINGPROFITS48 = USDCTOETH25(HALFPROFITS96); //inject NONSTANDARD NAMING uint256 TOKENSALREADYBURNED29 = YELDTOKEN43.BALANCEOF25(address(0)); //inject NONSTANDARD NAMING if (TOKENSALREADYBURNED29 < MAXIMUMTOKENSTOBURN49) { // 98% is the 49% doubled since we already took the 50% uint256 ETHTOSWAP53 = STAKINGPROFITS48.MUL24(98).DIV26(100); //inject NONSTANDARD NAMING // Buy and burn only applies up to 50k tokens burned BUYNBURN98(ETHTOSWAP53); // 1% for the Retirement Yield uint256 RETIREMENTYELD83 = STAKINGPROFITS48.MUL24(2).DIV26(100); //inject NONSTANDARD NAMING // Send to the treasury RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83); } else { // If we've reached the maximum burn point, send half the profits to the treasury to reward holders uint256 RETIREMENTYELD83 = STAKINGPROFITS48; //inject NONSTANDARD NAMING // Send to the treasury RETIREMENTYELDTREASURY39.transfer(RETIREMENTYELD83); } } // Yeld ierc2093(TOKEN25).SAFETRANSFER30(msg.sender, R82); POOL37 = CALCPOOLVALUEINTOKEN17(); } function RECOMMEND99() public view returns (Lender) { //inject NONSTANDARD NAMING (,uint256 CAPR5,uint256 IAPR100,uint256 AAPR96,uint256 DAPR97) = iiearnmanager83(APR50).RECOMMEND99(TOKEN25); //inject NONSTANDARD NAMING uint256 MAX28 = 0; //inject NONSTANDARD NAMING if (CAPR5 > MAX28) { MAX28 = CAPR5; } if (IAPR100 > MAX28) { MAX28 = IAPR100; } if (AAPR96 > MAX28) { MAX28 = AAPR96; } if (DAPR97 > MAX28) { MAX28 = DAPR97; } Lender NEWPROVIDER38 = Lender.NONE; //inject NONSTANDARD NAMING if (MAX28 == CAPR5) { NEWPROVIDER38 = Lender.COMPOUND; } else if (MAX28 == IAPR100) { NEWPROVIDER38 = Lender.FULCRUM; } else if (MAX28 == AAPR96) { NEWPROVIDER38 = Lender.AAVE; } else if (MAX28 == DAPR97) { NEWPROVIDER38 = Lender.DYDX; } return NEWPROVIDER38; } function GETAAVE86() public view returns (address) { //inject NONSTANDARD NAMING return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOL88(); } function GETAAVECORE62() public view returns (address) { //inject NONSTANDARD NAMING return lendingpooladdressesprovider85(AAVE10).GETLENDINGPOOLCORE37(); } function APPROVETOKEN12() public { //inject NONSTANDARD NAMING ierc2093(TOKEN25).SAFEAPPROVE32(COMPOUND53, uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(DYDX62, uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(GETAAVECORE62(), uint(-1)); ierc2093(TOKEN25).SAFEAPPROVE32(FULCRUM19, uint(-1)); } function BALANCE62() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(address(this)); } function BALANCEDYDXAVAILABLE58() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(DYDX62); } function BALANCEDYDX47() public view returns (uint256) { //inject NONSTANDARD NAMING Wei memory BAL85 = dydx100(DYDX62).GETACCOUNTWEI65(Info(address(this), 0), DTOKEN6); //inject NONSTANDARD NAMING return BAL85.VALUE83; } function BALANCECOMPOUND27() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(COMPOUND53).BALANCEOF25(address(this)); } function BALANCECOMPOUNDINTOKEN38() public view returns (uint256) { //inject NONSTANDARD NAMING // Mantisa 1e18 to decimals uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (B30 > 0) { B30 = B30.MUL24(compound17(COMPOUND53).EXCHANGERATESTORED22()).DIV26(1e18); } return B30; } function BALANCEFULCRUMAVAILABLE62() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(CHAI29).BALANCEOF25(FULCRUM19); } function BALANCEFULCRUMINTOKEN93() public view returns (uint256) { //inject NONSTANDARD NAMING uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING if (B30 > 0) { B30 = fulcrum27(FULCRUM19).ASSETBALANCEOF38(address(this)); } return B30; } function BALANCEFULCRUM60() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(FULCRUM19).BALANCEOF25(address(this)); } function BALANCEAAVEAVAILABLE0() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(TOKEN25).BALANCEOF25(AAVEPOOL17); } function BALANCEAAVE23() public view returns (uint256) { //inject NONSTANDARD NAMING return ierc2093(AAVETOKEN8).BALANCEOF25(address(this)); } function REBALANCE91() public { //inject NONSTANDARD NAMING Lender NEWPROVIDER38 = RECOMMEND99(); //inject NONSTANDARD NAMING if (NEWPROVIDER38 != PROVIDER42) { _WITHDRAWALL34(); } if (BALANCE62() > 0) { if (NEWPROVIDER38 == Lender.DYDX) { _SUPPLYDYDX52(BALANCE62()); } else if (NEWPROVIDER38 == Lender.FULCRUM) { _SUPPLYFULCRUM48(BALANCE62()); } else if (NEWPROVIDER38 == Lender.COMPOUND) { _SUPPLYCOMPOUND47(BALANCE62()); } else if (NEWPROVIDER38 == Lender.AAVE) { _SUPPLYAAVE98(BALANCE62()); } } PROVIDER42 = NEWPROVIDER38; } function _WITHDRAWALL34() internal { //inject NONSTANDARD NAMING uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (AMOUNT4 > 0) { _WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1)); } AMOUNT4 = BALANCEDYDX47(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEDYDXAVAILABLE58()) { AMOUNT4 = BALANCEDYDXAVAILABLE58(); } _WITHDRAWDYDX0(AMOUNT4); } AMOUNT4 = BALANCEFULCRUM60(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) { AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1); } _WITHDRAWSOMEFULCRUM68(AMOUNT4); } AMOUNT4 = BALANCEAAVE23(); if (AMOUNT4 > 0) { if (AMOUNT4 > BALANCEAAVEAVAILABLE0()) { AMOUNT4 = BALANCEAAVEAVAILABLE0(); } _WITHDRAWAAVE10(AMOUNT4); } } function _WITHDRAWSOMECOMPOUND30(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING uint256 B30 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING uint256 BT79 = BALANCECOMPOUNDINTOKEN38(); //inject NONSTANDARD NAMING require(BT79 >= _AMOUNT50, "insufficient funds"); // can have unintentional rounding errors uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING _WITHDRAWCOMPOUND82(AMOUNT4); } function _WITHDRAWSOMEFULCRUM68(uint256 _AMOUNT50) internal { //inject NONSTANDARD NAMING uint256 B30 = BALANCEFULCRUM60(); //inject NONSTANDARD NAMING uint256 BT79 = BALANCEFULCRUMINTOKEN93(); //inject NONSTANDARD NAMING require(BT79 >= _AMOUNT50, "insufficient funds"); // can have unintentional rounding errors uint256 AMOUNT4 = (B30.MUL24(_AMOUNT50)).DIV26(BT79).ADD27(1); //inject NONSTANDARD NAMING _WITHDRAWFULCRUM65(AMOUNT4); } function _WITHDRAWSOME38(uint256 _AMOUNT50) internal returns (bool) { //inject NONSTANDARD NAMING uint256 ORIGAMOUNT32 = _AMOUNT50; //inject NONSTANDARD NAMING uint256 AMOUNT4 = BALANCECOMPOUND27(); //inject NONSTANDARD NAMING if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCECOMPOUNDINTOKEN38().SUB57(1)) { _WITHDRAWSOMECOMPOUND30(BALANCECOMPOUNDINTOKEN38().SUB57(1)); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWSOMECOMPOUND30(_AMOUNT50); return true; } } AMOUNT4 = BALANCEDYDX47(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEDYDXAVAILABLE58()) { _WITHDRAWDYDX0(BALANCEDYDXAVAILABLE58()); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWDYDX0(_AMOUNT50); return true; } } AMOUNT4 = BALANCEFULCRUM60(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEFULCRUMAVAILABLE62().SUB57(1)) { AMOUNT4 = BALANCEFULCRUMAVAILABLE62().SUB57(1); _WITHDRAWSOMEFULCRUM68(BALANCEFULCRUMAVAILABLE62().SUB57(1)); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWSOMEFULCRUM68(AMOUNT4); return true; } } AMOUNT4 = BALANCEAAVE23(); if (AMOUNT4 > 0) { if (_AMOUNT50 > BALANCEAAVEAVAILABLE0()) { _WITHDRAWAAVE10(BALANCEAAVEAVAILABLE0()); _AMOUNT50 = ORIGAMOUNT32.SUB57(ierc2093(TOKEN25).BALANCEOF25(address(this))); } else { _WITHDRAWAAVE10(_AMOUNT50); return true; } } return true; } function _SUPPLYDYDX52(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING INFOS35[0] = Info(address(this), 0); AssetAmount memory AMT17 = AssetAmount(true, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING ActionArgs memory ACT61; //inject NONSTANDARD NAMING ACT61.ACTIONTYPE60 = ActionType.Deposit; ACT61.ACCOUNTID6 = 0; ACT61.AMOUNT4 = AMT17; ACT61.PRIMARYMARKETID93 = DTOKEN6; ACT61.OTHERADDRESS81 = address(this); ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING ARGS40[0] = ACT61; dydx100(DYDX62).OPERATE53(INFOS35, ARGS40); } function _SUPPLYAAVE98(uint AMOUNT4) internal { //inject NONSTANDARD NAMING aave60(GETAAVE86()).DEPOSIT43(TOKEN25, AMOUNT4, 0); } function _SUPPLYFULCRUM48(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(fulcrum27(FULCRUM19).MINT37(address(this), AMOUNT4) > 0, "FULCRUM: supply failed"); } function _SUPPLYCOMPOUND47(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(compound17(COMPOUND53).MINT37(AMOUNT4) == 0, "COMPOUND: supply failed"); } function _WITHDRAWAAVE10(uint AMOUNT4) internal { //inject NONSTANDARD NAMING atoken49(AAVETOKEN8).REDEEM71(AMOUNT4); } function _WITHDRAWFULCRUM65(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(fulcrum27(FULCRUM19).BURN1(address(this), AMOUNT4) > 0, "FULCRUM: withdraw failed"); } function _WITHDRAWCOMPOUND82(uint AMOUNT4) internal { //inject NONSTANDARD NAMING require(compound17(COMPOUND53).REDEEM71(AMOUNT4) == 0, "COMPOUND: withdraw failed"); } function _WITHDRAWDYDX0(uint256 AMOUNT4) internal { //inject NONSTANDARD NAMING Info[] memory INFOS35 = new Info[](1); //inject NONSTANDARD NAMING INFOS35[0] = Info(address(this), 0); AssetAmount memory AMT17 = AssetAmount(false, AssetDenomination.Wei, AssetReference.Delta, AMOUNT4); //inject NONSTANDARD NAMING ActionArgs memory ACT61; //inject NONSTANDARD NAMING ACT61.ACTIONTYPE60 = ActionType.Withdraw; ACT61.ACCOUNTID6 = 0; ACT61.AMOUNT4 = AMT17; ACT61.PRIMARYMARKETID93 = DTOKEN6; ACT61.OTHERADDRESS81 = address(this); ActionArgs[] memory ARGS40 = new ActionArgs[](1); //inject NONSTANDARD NAMING ARGS40[0] = ACT61; dydx100(DYDX62).OPERATE53(INFOS35, ARGS40); } function CALCPOOLVALUEINTOKEN17() public view returns (uint) { //inject NONSTANDARD NAMING return BALANCECOMPOUNDINTOKEN38() .ADD27(BALANCEFULCRUMINTOKEN93()) .ADD27(BALANCEDYDX47()) .ADD27(BALANCEAAVE23()) .ADD27(BALANCE62()); } function GETPRICEPERFULLSHARE16() public view returns (uint) { //inject NONSTANDARD NAMING uint _POOL79 = CALCPOOLVALUEINTOKEN17(); //inject NONSTANDARD NAMING return _POOL79.MUL24(1e18).DIV26(_TOTALSUPPLY32); } }
inject NONSTANDARD NAMING
function INCREASEALLOWANCE47(address SPENDER52, uint256 ADDEDVALUE76) public returns (bool) {
7,220,345
./partial_match/1/0x3e9a668D590B92256bb8D926b147f310791b2B1E/sources/TimeCapsuleFactory.sol
Recovers the address of the signer of a arbitrary length message. _message the signed message _signature signature/
function _recoverSignerAddress( string memory _message, bytes memory _signature ) private pure returns (address signerAddress) { if (_signature.length != 65) return address(0); bytes32 _messageHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n", Strings.toString(bytes(_message).length), bytes(_message) ) ); (bytes32 r, bytes32 s, uint8 v) = _splitSignature(_signature); signerAddress = ecrecover(_messageHash, v, r, s); }
3,576,051
pragma solidity ^0.4.21; import "contracts/Library/ClaimLib.sol"; import "contracts/Library/ExecutionLib.sol"; import "contracts/Library/PaymentLib.sol"; import "contracts/Library/RequestMetaLib.sol"; import "contracts/Library/RequestScheduleLib.sol"; import "contracts/Library/MathLib.sol"; import "contracts/zeppelin/SafeMath.sol"; library RequestLib { using ClaimLib for ClaimLib.ClaimData; using ExecutionLib for ExecutionLib.ExecutionData; using PaymentLib for PaymentLib.PaymentData; using RequestMetaLib for RequestMetaLib.RequestMeta; using RequestScheduleLib for RequestScheduleLib.ExecutionWindow; using SafeMath for uint; /* * This struct exists to circumvent an issue with returning multiple * values from a library function. I found through experimentation that I * could not return more than 4 things from a library function, even if I * put them in arrays. - Piper */ struct SerializedRequest { address[6] addressValues; bool[3] boolValues; uint[15] uintValues; uint8[1] uint8Values; } struct Request { ExecutionLib.ExecutionData txnData; RequestMetaLib.RequestMeta meta; PaymentLib.PaymentData paymentData; ClaimLib.ClaimData claimData; RequestScheduleLib.ExecutionWindow schedule; SerializedRequest serializedValues; } enum AbortReason { WasCancelled, //0 AlreadyCalled, //1 BeforeCallWindow, //2 AfterCallWindow, //3 ReservedForClaimer, //4 InsufficientGas, //5 MismatchGasPrice //6 } event Aborted(uint8 reason); event Cancelled(uint rewardPayment, uint measuredGasConsumption); event Claimed(); event Executed(uint bounty, uint fee, uint measuredGasConsumption); /** * @dev Validate the initialization parameters of a transaction request. */ function validate( address[4] _addressArgs, uint[12] _uintArgs, bytes _callData, uint _endowment ) public view returns (bool[6] isValid) { Request memory request; // callData is special. request.txnData.callData = _callData; // Address values request.claimData.claimedBy = 0x0; request.meta.createdBy = _addressArgs[0]; request.meta.owner = _addressArgs[1]; request.paymentData.feeRecipient = _addressArgs[2]; request.paymentData.bountyBenefactor = 0x0; request.txnData.toAddress = _addressArgs[3]; // Boolean values request.meta.isCancelled = false; request.meta.wasCalled = false; request.meta.wasSuccessful = false; // UInt values request.claimData.claimDeposit = 0; request.paymentData.fee = _uintArgs[0]; request.paymentData.bounty = _uintArgs[1]; request.paymentData.feeOwed = 0; request.paymentData.bountyOwed = 0; request.schedule.claimWindowSize = _uintArgs[2]; request.schedule.freezePeriod = _uintArgs[3]; request.schedule.reservedWindowSize = _uintArgs[4]; // This must be capped at 1 or it throws an exception. request.schedule.temporalUnit = RequestScheduleLib.TemporalUnit(MathLib.min(_uintArgs[5], 2)); request.schedule.windowSize = _uintArgs[6]; request.schedule.windowStart = _uintArgs[7]; request.txnData.callGas = _uintArgs[8]; request.txnData.callValue = _uintArgs[9]; request.txnData.gasPrice = _uintArgs[10]; request.claimData.requiredDeposit = _uintArgs[11]; // Uint8 values request.claimData.paymentModifier = 0; // The order of these errors matters as it determines which // ValidationError event codes are logged when validation fails. isValid[0] = PaymentLib.validateEndowment( _endowment, request.paymentData.bounty, request.paymentData.fee, request.txnData.callGas, request.txnData.callValue, request.txnData.gasPrice, _EXECUTION_GAS_OVERHEAD ); isValid[1] = RequestScheduleLib.validateReservedWindowSize( request.schedule.reservedWindowSize, request.schedule.windowSize ); isValid[2] = RequestScheduleLib.validateTemporalUnit(_uintArgs[5]); isValid[3] = RequestScheduleLib.validateWindowStart( request.schedule.temporalUnit, request.schedule.freezePeriod, request.schedule.windowStart ); isValid[4] = ExecutionLib.validateCallGas( request.txnData.callGas, _EXECUTION_GAS_OVERHEAD ); isValid[5] = ExecutionLib.validateToAddress(request.txnData.toAddress); return isValid; } /** * @dev Initialize a new Request. */ function initialize( Request storage self, address[4] _addressArgs, uint[12] _uintArgs, bytes _callData ) public returns (bool initialized) { address[6] memory addressValues = [ 0x0, // self.claimData.claimedBy _addressArgs[0], // self.meta.createdBy _addressArgs[1], // self.meta.owner _addressArgs[2], // self.paymentData.feeRecipient 0x0, // self.paymentData.bountyBenefactor _addressArgs[3] // self.txnData.toAddress ]; bool[3] memory boolValues = [false, false, false]; uint[15] memory uintValues = [ 0, // self.claimData.claimDeposit _uintArgs[0], // self.paymentData.fee 0, // self.paymentData.feeOwed _uintArgs[1], // self.paymentData.bounty 0, // self.paymentData.bountyOwed _uintArgs[2], // self.schedule.claimWindowSize _uintArgs[3], // self.schedule.freezePeriod _uintArgs[4], // self.schedule.reservedWindowSize _uintArgs[5], // self.schedule.temporalUnit _uintArgs[6], // self.schedule.windowSize _uintArgs[7], // self.schedule.windowStart _uintArgs[8], // self.txnData.callGas _uintArgs[9], // self.txnData.callValue _uintArgs[10], // self.txnData.gasPrice _uintArgs[11] // self.claimData.requiredDeposit ]; uint8[1] memory uint8Values = [ 0 ]; require(deserialize(self, addressValues, boolValues, uintValues, uint8Values, _callData)); return true; } /* * Returns the entire data structure of the Request in a *serialized* * format. This will be missing the `callData` which must be requested * separately * * Parameter order is alphabetical by type, then namespace, then name * * NOTE: This exists because of an issue I ran into related to returning * multiple values from a library function. I found through * experimentation that I was unable to return more than 4 things, even if * I used the trick of returning arrays of items. */ function serialize(Request storage self) internal returns (bool serialized) { // Address values self.serializedValues.addressValues[0] = self.claimData.claimedBy; self.serializedValues.addressValues[1] = self.meta.createdBy; self.serializedValues.addressValues[2] = self.meta.owner; self.serializedValues.addressValues[3] = self.paymentData.feeRecipient; self.serializedValues.addressValues[4] = self.paymentData.bountyBenefactor; self.serializedValues.addressValues[5] = self.txnData.toAddress; // Boolean values self.serializedValues.boolValues[0] = self.meta.isCancelled; self.serializedValues.boolValues[1] = self.meta.wasCalled; self.serializedValues.boolValues[2] = self.meta.wasSuccessful; // UInt256 values self.serializedValues.uintValues[0] = self.claimData.claimDeposit; self.serializedValues.uintValues[1] = self.paymentData.fee; self.serializedValues.uintValues[2] = self.paymentData.feeOwed; self.serializedValues.uintValues[3] = self.paymentData.bounty; self.serializedValues.uintValues[4] = self.paymentData.bountyOwed; self.serializedValues.uintValues[5] = self.schedule.claimWindowSize; self.serializedValues.uintValues[6] = self.schedule.freezePeriod; self.serializedValues.uintValues[7] = self.schedule.reservedWindowSize; self.serializedValues.uintValues[8] = uint(self.schedule.temporalUnit); self.serializedValues.uintValues[9] = self.schedule.windowSize; self.serializedValues.uintValues[10] = self.schedule.windowStart; self.serializedValues.uintValues[11] = self.txnData.callGas; self.serializedValues.uintValues[12] = self.txnData.callValue; self.serializedValues.uintValues[13] = self.txnData.gasPrice; self.serializedValues.uintValues[14] = self.claimData.requiredDeposit; // Uint8 values self.serializedValues.uint8Values[0] = self.claimData.paymentModifier; return true; } /** * @dev Populates a Request object from the full output of `serialize`. * * Parameter order is alphabetical by type, then namespace, then name. */ function deserialize( Request storage self, address[6] _addressValues, bool[3] _boolValues, uint[15] _uintValues, uint8[1] _uint8Values, bytes _callData ) internal returns (bool deserialized) { // callData is special. self.txnData.callData = _callData; // Address values self.claimData.claimedBy = _addressValues[0]; self.meta.createdBy = _addressValues[1]; self.meta.owner = _addressValues[2]; self.paymentData.feeRecipient = _addressValues[3]; self.paymentData.bountyBenefactor = _addressValues[4]; self.txnData.toAddress = _addressValues[5]; // Boolean values self.meta.isCancelled = _boolValues[0]; self.meta.wasCalled = _boolValues[1]; self.meta.wasSuccessful = _boolValues[2]; // UInt values self.claimData.claimDeposit = _uintValues[0]; self.paymentData.fee = _uintValues[1]; self.paymentData.feeOwed = _uintValues[2]; self.paymentData.bounty = _uintValues[3]; self.paymentData.bountyOwed = _uintValues[4]; self.schedule.claimWindowSize = _uintValues[5]; self.schedule.freezePeriod = _uintValues[6]; self.schedule.reservedWindowSize = _uintValues[7]; self.schedule.temporalUnit = RequestScheduleLib.TemporalUnit(_uintValues[8]); self.schedule.windowSize = _uintValues[9]; self.schedule.windowStart = _uintValues[10]; self.txnData.callGas = _uintValues[11]; self.txnData.callValue = _uintValues[12]; self.txnData.gasPrice = _uintValues[13]; self.claimData.requiredDeposit = _uintValues[14]; // Uint8 values self.claimData.paymentModifier = _uint8Values[0]; deserialized = true; } function execute(Request storage self) internal returns (bool) { /* * Execute the TransactionRequest * * +---------------------+ * | Phase 1: Validation | * +---------------------+ * * Must pass all of the following checks: * * 1. Not already called. * 2. Not cancelled. * 3. Not before the execution window. * 4. Not after the execution window. * 5. if (claimedBy == 0x0 or msg.sender == claimedBy): * - windowStart <= block.number * - block.number <= windowStart + windowSize * else if (msg.sender != claimedBy): * - windowStart + reservedWindowSize <= block.number * - block.number <= windowStart + windowSize * else: * - throw (should be impossible) * * 6. gasleft() == callGas * * +--------------------+ * | Phase 2: Execution | * +--------------------+ * * 1. Mark as called (must be before actual execution to prevent * re-entrance) * 2. Send Transaction and record success or failure. * * +---------------------+ * | Phase 3: Accounting | * +---------------------+ * * 1. Calculate and send fee amount. * 2. Calculate and send bounty amount. * 3. Send remaining ether back to owner. * */ // Record the gas at the beginning of the transaction so we can // calculate how much has been used later. uint startGas = gasleft(); // +----------------------+ // | Begin: Authorization | // +----------------------+ if (gasleft() < requiredExecutionGas(self).sub(_PRE_EXECUTION_GAS)) { emit Aborted(uint8(AbortReason.InsufficientGas)); return false; } else if (self.meta.wasCalled) { emit Aborted(uint8(AbortReason.AlreadyCalled)); return false; } else if (self.meta.isCancelled) { emit Aborted(uint8(AbortReason.WasCancelled)); return false; } else if (self.schedule.isBeforeWindow()) { emit Aborted(uint8(AbortReason.BeforeCallWindow)); return false; } else if (self.schedule.isAfterWindow()) { emit Aborted(uint8(AbortReason.AfterCallWindow)); return false; } else if (self.claimData.isClaimed() && msg.sender != self.claimData.claimedBy && self.schedule.inReservedWindow()) { emit Aborted(uint8(AbortReason.ReservedForClaimer)); return false; } else if (self.txnData.gasPrice != tx.gasprice) { emit Aborted(uint8(AbortReason.MismatchGasPrice)); return false; } // +--------------------+ // | End: Authorization | // +--------------------+ // +------------------+ // | Begin: Execution | // +------------------+ // Mark as being called before sending transaction to prevent re-entrance. self.meta.wasCalled = true; // Send the transaction... // The transaction is allowed to fail and the executing agent will still get the bounty. // `.sendTransaction()` will return false on a failed exeuction. self.meta.wasSuccessful = self.txnData.sendTransaction(); // +----------------+ // | End: Execution | // +----------------+ // +-------------------+ // | Begin: Accounting | // +-------------------+ // Compute the fee amount if (self.paymentData.hasFeeRecipient()) { self.paymentData.feeOwed = self.paymentData.getFee() .add(self.paymentData.feeOwed); } // Record this locally so that we can log it later. // `.sendFee()` below will change `self.paymentData.feeOwed` to 0 to prevent re-entrance. uint totalFeePayment = self.paymentData.feeOwed; // Send the fee. This transaction may also fail but can be called again after // execution. self.paymentData.sendFee(); // Compute the bounty amount. self.paymentData.bountyBenefactor = msg.sender; if (self.claimData.isClaimed()) { // If the transaction request was claimed, we add the deposit to the bounty whether // or not the same agent who claimed is executing. self.paymentData.bountyOwed = self.claimData.claimDeposit .add(self.paymentData.bountyOwed); // To prevent re-entrance we zero out the claim deposit since it is now accounted for // in the bounty value. self.claimData.claimDeposit = 0; // Depending on when the transaction request was claimed, we apply the modifier to the // bounty payment and add it to the bounty already owed. self.paymentData.bountyOwed = self.paymentData.getBountyWithModifier(self.claimData.paymentModifier) .add(self.paymentData.bountyOwed); } else { // Not claimed. Just add the full bounty. self.paymentData.bountyOwed = self.paymentData.getBounty().add(self.paymentData.bountyOwed); } // Take down the amount of gas used so far in execution to compensate the executing agent. uint measuredGasConsumption = startGas.sub(gasleft()).add(_EXECUTE_EXTRA_GAS); // // +----------------------------------------------------------------------+ // // | NOTE: All code after this must be accounted for by EXECUTE_EXTRA_GAS | // // +----------------------------------------------------------------------+ // Add the gas reimbursment amount to the bounty. self.paymentData.bountyOwed = measuredGasConsumption .mul(tx.gasprice) .add(self.paymentData.bountyOwed); // Log the bounty and fee. Otherwise it is non-trivial to figure // out how much was payed. emit Executed(self.paymentData.bountyOwed, totalFeePayment, measuredGasConsumption); // Attempt to send the bounty. as with `.sendFee()` it may fail and need to be caled after execution. self.paymentData.sendBounty(); // If any ether is left, send it back to the owner of the transaction request. _sendOwnerEther(self); // +-----------------+ // | End: Accounting | // +-----------------+ // Successful return true; } // This is the amount of gas that it takes to enter from the // `TransactionRequest.execute()` contract into the `RequestLib.execute()` // method at the point where the gas check happens. uint private constant _PRE_EXECUTION_GAS = 25000; // TODO is this number still accurate? function PRE_EXECUTION_GAS() public pure returns (uint) { return _PRE_EXECUTION_GAS; } function requiredExecutionGas(Request storage self) public view returns (uint requiredGas) { requiredGas = self.txnData.callGas.add(_EXECUTION_GAS_OVERHEAD); } /* * The amount of gas needed to complete the execute method after * the transaction has been sent. */ uint private constant _EXECUTION_GAS_OVERHEAD = 180000; // TODO check accuracy of this number function EXECUTION_GAS_OVERHEAD() public pure returns (uint) { return _EXECUTION_GAS_OVERHEAD; } /* * The amount of gas used by the portion of the `execute` function * that cannot be accounted for via gas tracking. */ uint private constant _EXECUTE_EXTRA_GAS = 90000; // again, check for accuracy... Doubled this from Piper's original - Logan function EXECUTE_EXTRA_GAS() public pure returns (uint) { return _EXECUTE_EXTRA_GAS; } /* * @dev Performs the checks to see if a request can be cancelled. * Must satisfy the following conditions. * * 1. Not Cancelled * 2. either: * * not wasCalled && afterExecutionWindow * * not claimed && beforeFreezeWindow && msg.sender == owner */ function isCancellable(Request storage self) internal view returns (bool) { if (self.meta.isCancelled) { // already cancelled! return false; } else if (!self.meta.wasCalled && self.schedule.isAfterWindow()) { // not called but after the window return true; } else if (!self.claimData.isClaimed() && self.schedule.isBeforeFreeze() && msg.sender == self.meta.owner) { // not claimed and before freezePeriod and owner is cancelling return true; } else { // otherwise cannot cancel return false; } } /* * Constant value to account for the gas usage that cannot be accounted * for using gas-tracking within the `cancel` function. */ uint private constant _CANCEL_EXTRA_GAS = 85000; // Check accuracy function CANCEL_EXTRA_GAS() public pure returns (uint) { return _CANCEL_EXTRA_GAS; } /* * Cancel the transaction request, attempting to send all appropriate * refunds. To incentivise cancellation by other parties, a small reward * payment is issued to the party that cancels the request if they are not * the owner. */ function cancel(Request storage self) public returns (bool) { uint startGas = gasleft(); uint rewardPayment; uint measuredGasConsumption; // Checks if this transactionRequest can be cancelled. require(isCancellable(self)); // Set here to prevent re-entrance attacks. self.meta.isCancelled = true; // Refund the claim deposit (if there is one) require(self.claimData.refundDeposit()); // Send a reward to the cancelling agent if they are not the owner. // This is to incentivize the cancelling of expired transaction requests. // This also guarantees that it is being cancelled after the call window // since the `isCancellable()` function checks this. if (msg.sender != self.meta.owner) { // Create the rewardBenefactor address rewardBenefactor = msg.sender; // Create the rewardOwed variable, it is one-hundredth // of the bounty. uint rewardOwed = self.paymentData.bountyOwed .add(self.paymentData.bounty.div(100)); // Calculate the amount of gas cancelling agent used in this transaction. measuredGasConsumption = startGas .sub(gasleft()) .add(_CANCEL_EXTRA_GAS); // Add their gas fees to the reward.W rewardOwed = measuredGasConsumption .mul(tx.gasprice) .add(rewardOwed); // Take note of the rewardPayment to log it. rewardPayment = rewardOwed; // Transfers the rewardPayment. if (rewardOwed > 0) { self.paymentData.bountyOwed = 0; rewardBenefactor.transfer(rewardOwed); } } // Log it! emit Cancelled(rewardPayment, measuredGasConsumption); // Send the remaining ether to the owner. return sendOwnerEther(self); } /* * @dev Performs some checks to verify that a transaction request is claimable. * @param self The Request object. */ function isClaimable(Request storage self) internal view returns (bool) { // Require not claimed and not cancelled. require(!self.claimData.isClaimed()); require(!self.meta.isCancelled); // Require that it's in the claim window and the value sent is over the required deposit. require(self.schedule.inClaimWindow()); require(msg.value >= self.claimData.requiredDeposit); return true; } /* * @dev Claims the request. * @param self The Request object. * Payable because it requires the sender to send enough ether to cover the claimDeposit. */ function claim(Request storage self) internal returns (bool claimed) { require(isClaimable(self)); self.claimData.claim(self.schedule.computePaymentModifier()); emit Claimed(); claimed = true; } /* * @dev Refund claimer deposit. */ function refundClaimDeposit(Request storage self) public returns (bool) { require(self.meta.isCancelled || self.schedule.isAfterWindow()); return self.claimData.refundDeposit(); } /* * Send fee. Wrapper over the real function that perform an extra * check to see if it's after the execution window (and thus the first transaction failed) */ function sendFee(Request storage self) public returns (bool) { if (self.schedule.isAfterWindow()) { return self.paymentData.sendFee(); } return false; } /* * Send bounty. Wrapper over the real function that performs an extra * check to see if it's after execution window (and thus the first transaction failed) */ function sendBounty(Request storage self) public returns (bool) { /// check wasCalled if (self.schedule.isAfterWindow()) { return self.paymentData.sendBounty(); } return false; } /** * Send owner ether. Wrapper over the real function that performs an extra * check to see if it's after execution window (and thus the first transaction failed) */ function sendOwnerEther(Request storage self) public returns (bool) { if( self.meta.isCancelled || self.schedule.isAfterWindow() ) { return _sendOwnerEther(self); } return false; } function _sendOwnerEther(Request storage self) internal returns (bool) { // Note! This does not do any checks since it is used in the execute function. // The public version of the function should be used for checks and in the cancel function. uint ownerRefund = address(this).balance .sub(self.claimData.claimDeposit) .sub(self.paymentData.bountyOwed) .sub(self.paymentData.feeOwed); /* solium-disable security/no-send */ return self.meta.owner.send(ownerRefund); } }
Returns the entire data structure of the Request in a serialized format. This will be missing the `callData` which must be requested separately Parameter order is alphabetical by type, then namespace, then name NOTE: This exists because of an issue I ran into related to returning multiple values from a library function. I found through experimentation that I was unable to return more than 4 things, even if I used the trick of returning arrays of items./ Address values Boolean values UInt256 values Uint8 values
function serialize(Request storage self) internal returns (bool serialized) { self.serializedValues.addressValues[0] = self.claimData.claimedBy; self.serializedValues.addressValues[1] = self.meta.createdBy; self.serializedValues.addressValues[2] = self.meta.owner; self.serializedValues.addressValues[3] = self.paymentData.feeRecipient; self.serializedValues.addressValues[4] = self.paymentData.bountyBenefactor; self.serializedValues.addressValues[5] = self.txnData.toAddress; self.serializedValues.boolValues[0] = self.meta.isCancelled; self.serializedValues.boolValues[1] = self.meta.wasCalled; self.serializedValues.boolValues[2] = self.meta.wasSuccessful; self.serializedValues.uintValues[0] = self.claimData.claimDeposit; self.serializedValues.uintValues[1] = self.paymentData.fee; self.serializedValues.uintValues[2] = self.paymentData.feeOwed; self.serializedValues.uintValues[3] = self.paymentData.bounty; self.serializedValues.uintValues[4] = self.paymentData.bountyOwed; self.serializedValues.uintValues[5] = self.schedule.claimWindowSize; self.serializedValues.uintValues[6] = self.schedule.freezePeriod; self.serializedValues.uintValues[7] = self.schedule.reservedWindowSize; self.serializedValues.uintValues[8] = uint(self.schedule.temporalUnit); self.serializedValues.uintValues[9] = self.schedule.windowSize; self.serializedValues.uintValues[10] = self.schedule.windowStart; self.serializedValues.uintValues[11] = self.txnData.callGas; self.serializedValues.uintValues[12] = self.txnData.callValue; self.serializedValues.uintValues[13] = self.txnData.gasPrice; self.serializedValues.uintValues[14] = self.claimData.requiredDeposit; self.serializedValues.uint8Values[0] = self.claimData.paymentModifier; return true; }
12,776,663
./full_match/1/0x9101782f132Fb1232BdA742A24372cBBBA01F020/sources/browser/AAAAMint.sol
External function call This function adjust how many token will be produced by each block, eg: changeAmountPerBlock(100) will set the produce rate to 100/block.
function sync() public virtual returns (bool) { uint value = IConfig(config).getValue(ConfigNames.MINT_AMOUNT_PER_BLOCK); uint old = amountPerBlock; require(value != old, 'AMOUNT_PER_BLOCK_NO_CHANGE'); require(maxSupply > totalSupply, 'NO_BALANCE_TO_MINT'); _update(); amountPerBlock = value; emit InterestsPerBlockChanged(old, value); return true; }
3,143,387
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.8.0; import "../../interfaces/IGovernance.sol"; import "../../interfaces/IMemberRoles.sol"; import "../../interfaces/INXMMaster.sol"; import "../../interfaces/INXMToken.sol"; import "../../interfaces/ITokenController.sol"; contract VotePower { string constant public name = "NXM balance with delegations"; string constant public symbol = "NXMD"; uint8 constant public decimals = 18; INXMMaster immutable public master; enum Role {UnAssigned, AdvisoryBoard, Member} constructor(INXMMaster _master) { master = _master; } function totalSupply() public view returns (uint) { return INXMToken(master.tokenAddress()).totalSupply(); } function balanceOf(address member) public view returns (uint) { ITokenController tokenController = ITokenController(master.dAppLocker()); IMemberRoles memberRoles = IMemberRoles(master.getLatestAddress("MR")); IGovernance governance = IGovernance(master.getLatestAddress("GV")); if (!memberRoles.checkRole(member, uint(Role.Member))) { return 0; } uint delegationId = governance.followerDelegation(member); if (delegationId != 0) { (, address leader,) = governance.allDelegation(delegationId); if (leader != address(0)) { return 0; } } uint balance = tokenController.totalBalanceOf(member) + 1e18; uint[] memory delegationIds = governance.getFollowers(member); for (uint i = 0; i < delegationIds.length; i++) { (address follower, address leader,) = governance.allDelegation(delegationIds[i]); if ( leader != member || !memberRoles.checkRole(follower, uint(Role.Member)) ) { continue; } balance += tokenController.totalBalanceOf(follower) + 1e18; } return balance; } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface 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 ); struct DelegateVote { address follower; address leader; uint lastUpd; } /// @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 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) external view returns (uint closeValue); function allowedToCatgorize() external view returns (uint roleId); function removeDelegation(address _add) external; function getPendingReward(address _memberAddress) external view returns (uint pendingDAppReward); function getFollowers(address _add) external view returns (uint[] memory); function followerDelegation(address _add) external view returns (uint delegationId); function allDelegation(uint _delegationId) external view returns (address follower, address leader, uint lastUpd); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface IMemberRoles { enum Role {UnAssigned, AdvisoryBoard, Member, Owner} function payJoiningFee(address _userAddress) external payable; function switchMembership(address _newAddress) external; function switchMembershipAndAssets( address newAddress, uint[] calldata coverIds, address[] calldata stakingPools ) external; function switchMembershipOf(address member, address _newAddress) external; function swapOwner(address _newOwnerAddress) external; function addInitialABMembers(address[] calldata abArray) external; function kycVerdict(address payable _userAddress, bool verdict) external; function totalRoles() external view returns (uint256); function changeAuthorized(uint _roleId, address _newAuthorized) external; function members(uint _memberRoleId) external view returns (uint, address[] memory memberArray); function numberOfMembers(uint _memberRoleId) external view returns (uint); function authorized(uint _memberRoleId) external view returns (address); function roles(address _memberAddress) external view returns (uint[] memory); function checkRole(address _memberAddress, uint _roleId) external view returns (bool); function getMemberLengthForAllRoles() external view returns (uint[] memory totalMembers); function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool); function membersLength(uint _memberRoleId) external view returns (uint); event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription); event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface INXMMaster { function tokenAddress() external view returns (address); function owner() external view returns (address); function masterInitialized() external view returns (bool); function isInternal(address _add) external view returns (bool); function isPause() external view returns (bool check); function isOwner(address _add) external view returns (bool); function isMember(address _add) external view returns (bool); function checkIsAuthToGoverned(address _add) external view returns (bool); function dAppLocker() external view returns (address _add); function getLatestAddress(bytes2 _contractName) external view returns (address payable contractAddress); function contractAddresses(bytes2 code) external view returns (address payable); function upgradeMultipleContracts( bytes2[] calldata _contractCodes, address payable[] calldata newAddresses ) external; function removeContracts(bytes2[] calldata contractCodesToRemove) external; function addNewInternalContracts( bytes2[] calldata _contractCodes, address payable[] calldata newAddresses, uint[] calldata _types ) external; function updateOwnerParameters(bytes8 code, address payable val) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity >=0.5.0; interface INXMToken { function burn(uint256 amount) external returns (bool); function burnFrom(address from, uint256 value) external returns (bool); function operatorTransfer(address from, uint256 value) external returns (bool); function mint(address account, uint256 amount) external; function isLockedForMV(address member) external view returns (uint); function addToWhiteList(address _member) external returns (bool); function removeFromWhiteList(address _member) external returns (bool); function changeOperator(address _newOperator) external returns (bool); function lockForMemberVote(address _of, uint _days) external; /** * @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: GPL-3.0-only pragma solidity >=0.5.0; import "./INXMToken.sol"; interface ITokenController { struct CoverInfo { uint16 claimCount; bool hasOpenClaim; bool hasAcceptedClaim; // note: still 224 bits available here, can be used later } function coverInfo(uint id) external view returns (uint16 claimCount, bool hasOpenClaim, bool hasAcceptedClaim); function withdrawCoverNote( address _of, uint[] calldata _coverIds, uint[] calldata _indexes ) external; function changeOperator(address _newOperator) external; function operatorTransfer(address _from, address _to, uint _value) external returns (bool); function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) external returns (bool); function extendLockOf(address _of, bytes32 _reason, uint256 _time) external returns (bool); function burnFrom(address _of, uint amount) external returns (bool); function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) external; function reduceLock(address _of, bytes32 _reason, uint256 _time) external; function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) external; function addToWhitelist(address _member) external; function removeFromWhitelist(address _member) external; function mint(address _member, uint _amount) external; function lockForMemberVote(address _of, uint _days) external; function withdrawClaimAssessmentTokens(address _of) external; function getLockReasons(address _of) external view returns (bytes32[] memory reasons); function getLockedTokensValidity(address _of, bytes32 reason) external view returns (uint256 validity); function getUnlockableTokens(address _of) external view returns (uint256 unlockableTokens); function tokensLocked(address _of, bytes32 _reason) external view returns (uint256 amount); function tokensLockedWithValidity(address _of, bytes32 _reason) external view returns (uint256 amount, uint256 validity); function tokensUnlockable(address _of, bytes32 _reason) external view returns (uint256 amount); function totalSupply() external view returns (uint256); function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) external view returns (uint256 amount); function totalBalanceOf(address _of) external view returns (uint256 amount); function totalLockedBalance(address _of) external view returns (uint256 amount); function token() external view returns (INXMToken); }
note: still 224 bits available here, can be used later
function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external; function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; 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) external view returns (uint closeValue); function allowedToCatgorize() external view returns (uint roleId); function removeDelegation(address _add) external; function getPendingReward(address _memberAddress) external view returns (uint pendingDAppReward); function getFollowers(address _add) external view returns (uint[] memory); function followerDelegation(address _add) external view returns (uint delegationId); function allDelegation(uint _delegationId) external view returns (address follower, address leader, uint lastUpd); } pragma solidity >=0.5.0; } pragma solidity >=0.5.0; } pragma solidity >=0.5.0; } pragma solidity >=0.5.0; import "./INXMToken.sol"; struct CoverInfo { uint16 claimCount; bool hasOpenClaim; bool hasAcceptedClaim; }
6,326,151
pragma solidity ^0.5.16; // Inheritance import "./Owned.sol"; import "./MixinFuturesMarketSettings.sol"; // Internal references import "./interfaces/IFuturesMarketSettings.sol"; import "./interfaces/IFuturesMarketManager.sol"; import "./interfaces/IFuturesMarket.sol"; // https://docs.synthetix.io/contracts/source/contracts/FuturesMarketSettings contract FuturesMarketSettings is Owned, MixinFuturesMarketSettings, IFuturesMarketSettings { /* ========== CONSTANTS ========== */ /* ---------- Address Resolver Configuration ---------- */ bytes32 internal constant CONTRACT_FUTURES_MARKET_MANAGER = "FuturesMarketManager"; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, address _resolver) public Owned(_owner) MixinFuturesMarketSettings(_resolver) {} /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinFuturesMarketSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](1); newAddresses[0] = CONTRACT_FUTURES_MARKET_MANAGER; addresses = combineArrays(existingAddresses, newAddresses); } function _futuresMarketManager() internal view returns (IFuturesMarketManager) { return IFuturesMarketManager(requireAndGetAddress(CONTRACT_FUTURES_MARKET_MANAGER)); } /* ---------- Getters ---------- */ /* * The fee charged when opening a position on the heavy side of a futures market. */ function takerFee(bytes32 _marketKey) external view returns (uint) { return _takerFee(_marketKey); } /* * The fee charged when opening a position on the light side of a futures market. */ function makerFee(bytes32 _marketKey) public view returns (uint) { return _makerFee(_marketKey); } /* * The fee charged when opening a position on the heavy side of a futures market using next price mechanism. */ function takerFeeNextPrice(bytes32 _marketKey) external view returns (uint) { return _takerFeeNextPrice(_marketKey); } /* * The fee charged when opening a position on the light side of a futures market using next price mechanism. */ function makerFeeNextPrice(bytes32 _marketKey) public view returns (uint) { return _makerFeeNextPrice(_marketKey); } /* * The number of price update rounds during which confirming next-price is allowed */ function nextPriceConfirmWindow(bytes32 _marketKey) public view returns (uint) { return _nextPriceConfirmWindow(_marketKey); } /* * The maximum allowable leverage in a market. */ function maxLeverage(bytes32 _marketKey) public view returns (uint) { return _maxLeverage(_marketKey); } /* * The maximum allowable notional value on each side of a market. */ function maxMarketValueUSD(bytes32 _marketKey) public view returns (uint) { return _maxMarketValueUSD(_marketKey); } /* * The maximum theoretical funding rate per day charged by a market. */ function maxFundingRate(bytes32 _marketKey) public view returns (uint) { return _maxFundingRate(_marketKey); } /* * The skew level at which the max funding rate will be charged. */ function skewScaleUSD(bytes32 _marketKey) public view returns (uint) { return _skewScaleUSD(_marketKey); } function parameters(bytes32 _marketKey) external view returns ( uint takerFee, uint makerFee, uint takerFeeNextPrice, uint makerFeeNextPrice, uint nextPriceConfirmWindow, uint maxLeverage, uint maxMarketValueUSD, uint maxFundingRate, uint skewScaleUSD ) { takerFee = _takerFee(_marketKey); makerFee = _makerFee(_marketKey); takerFeeNextPrice = _takerFeeNextPrice(_marketKey); makerFeeNextPrice = _makerFeeNextPrice(_marketKey); nextPriceConfirmWindow = _nextPriceConfirmWindow(_marketKey); maxLeverage = _maxLeverage(_marketKey); maxMarketValueUSD = _maxMarketValueUSD(_marketKey); maxFundingRate = _maxFundingRate(_marketKey); skewScaleUSD = _skewScaleUSD(_marketKey); } /* * The minimum amount of sUSD paid to a liquidator when they successfully liquidate a position. * This quantity must be no greater than `minInitialMargin`. */ function minKeeperFee() external view returns (uint) { return _minKeeperFee(); } /* * Liquidation fee basis points paid to liquidator. * Use together with minKeeperFee() to calculate the actual fee paid. */ function liquidationFeeRatio() external view returns (uint) { return _liquidationFeeRatio(); } /* * Liquidation price buffer in basis points to prevent negative margin on liquidation. */ function liquidationBufferRatio() external view returns (uint) { return _liquidationBufferRatio(); } /* * The minimum margin required to open a position. * This quantity must be no less than `minKeeperFee`. */ function minInitialMargin() external view returns (uint) { return _minInitialMargin(); } /* ========== MUTATIVE FUNCTIONS ========== */ /* ---------- Setters --------- */ function _setParameter( bytes32 _marketKey, bytes32 key, uint value ) internal { _flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(_marketKey, key)), value); emit ParameterUpdated(_marketKey, key, value); } function setTakerFee(bytes32 _marketKey, uint _takerFee) public onlyOwner { require(_takerFee <= 1e18, "taker fee greater than 1"); _setParameter(_marketKey, PARAMETER_TAKER_FEE, _takerFee); } function setMakerFee(bytes32 _marketKey, uint _makerFee) public onlyOwner { require(_makerFee <= 1e18, "maker fee greater than 1"); _setParameter(_marketKey, PARAMETER_MAKER_FEE, _makerFee); } function setTakerFeeNextPrice(bytes32 _marketKey, uint _takerFeeNextPrice) public onlyOwner { require(_takerFeeNextPrice <= 1e18, "taker fee greater than 1"); _setParameter(_marketKey, PARAMETER_TAKER_FEE_NEXT_PRICE, _takerFeeNextPrice); } function setMakerFeeNextPrice(bytes32 _marketKey, uint _makerFeeNextPrice) public onlyOwner { require(_makerFeeNextPrice <= 1e18, "maker fee greater than 1"); _setParameter(_marketKey, PARAMETER_MAKER_FEE_NEXT_PRICE, _makerFeeNextPrice); } function setNextPriceConfirmWindow(bytes32 _marketKey, uint _nextPriceConfirmWindow) public onlyOwner { _setParameter(_marketKey, PARAMETER_NEXT_PRICE_CONFIRM_WINDOW, _nextPriceConfirmWindow); } function setMaxLeverage(bytes32 _marketKey, uint _maxLeverage) public onlyOwner { _setParameter(_marketKey, PARAMETER_MAX_LEVERAGE, _maxLeverage); } function setMaxMarketValueUSD(bytes32 _marketKey, uint _maxMarketValueUSD) public onlyOwner { _setParameter(_marketKey, PARAMETER_MAX_MARKET_VALUE, _maxMarketValueUSD); } // Before altering parameters relevant to funding rates, outstanding funding on the underlying market // must be recomputed, otherwise already-accrued but unrealised funding in the market can change. function _recomputeFunding(bytes32 _marketKey) internal { IFuturesMarket market = IFuturesMarket(_futuresMarketManager().marketForKey(_marketKey)); if (market.marketSize() > 0) { // only recompute funding when market has positions, this check is important for initial setup market.recomputeFunding(); } } function setMaxFundingRate(bytes32 _marketKey, uint _maxFundingRate) public onlyOwner { _recomputeFunding(_marketKey); _setParameter(_marketKey, PARAMETER_MAX_FUNDING_RATE, _maxFundingRate); } function setSkewScaleUSD(bytes32 _marketKey, uint _skewScaleUSD) public onlyOwner { require(_skewScaleUSD > 0, "cannot set skew scale 0"); _recomputeFunding(_marketKey); _setParameter(_marketKey, PARAMETER_MIN_SKEW_SCALE, _skewScaleUSD); } function setParameters( bytes32 _marketKey, uint _takerFee, uint _makerFee, uint _takerFeeNextPrice, uint _makerFeeNextPrice, uint _nextPriceConfirmWindow, uint _maxLeverage, uint _maxMarketValueUSD, uint _maxFundingRate, uint _skewScaleUSD ) external onlyOwner { _recomputeFunding(_marketKey); setTakerFee(_marketKey, _takerFee); setMakerFee(_marketKey, _makerFee); setTakerFeeNextPrice(_marketKey, _takerFeeNextPrice); setMakerFeeNextPrice(_marketKey, _makerFeeNextPrice); setNextPriceConfirmWindow(_marketKey, _nextPriceConfirmWindow); setMaxLeverage(_marketKey, _maxLeverage); setMaxMarketValueUSD(_marketKey, _maxMarketValueUSD); setMaxFundingRate(_marketKey, _maxFundingRate); setSkewScaleUSD(_marketKey, _skewScaleUSD); } function setMinKeeperFee(uint _sUSD) external onlyOwner { require(_sUSD <= _minInitialMargin(), "min margin < liquidation fee"); _flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_MIN_KEEPER_FEE, _sUSD); emit MinKeeperFeeUpdated(_sUSD); } function setLiquidationFeeRatio(uint _ratio) external onlyOwner { _flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_FEE_RATIO, _ratio); emit LiquidationFeeRatioUpdated(_ratio); } function setLiquidationBufferRatio(uint _ratio) external onlyOwner { _flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_BUFFER_RATIO, _ratio); emit LiquidationBufferRatioUpdated(_ratio); } function setMinInitialMargin(uint _minMargin) external onlyOwner { require(_minKeeperFee() <= _minMargin, "min margin < liquidation fee"); _flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_MIN_INITIAL_MARGIN, _minMargin); emit MinInitialMarginUpdated(_minMargin); } /* ========== EVENTS ========== */ event ParameterUpdated(bytes32 indexed marketKey, bytes32 indexed parameter, uint value); event MinKeeperFeeUpdated(uint sUSD); event LiquidationFeeRatioUpdated(uint bps); event LiquidationBufferRatioUpdated(uint bps); event MinInitialMarginUpdated(uint minMargin); }
The fee charged when opening a position on the heavy side of a futures market using next price mechanism./
function takerFeeNextPrice(bytes32 _marketKey) external view returns (uint) { return _takerFeeNextPrice(_marketKey); }
12,648,292
./full_match/1/0x278d1f7067F4dAbb9811F98A038803a9C84A6196/sources/HDAOToken.sol
Claims the caller's tokens that have been unlocked, sending them to `recipient`. recipient The account to transfer unlocked tokens to. amount The amount to transfer. If greater than the claimable amount, the maximum is transferred./
function claim(address recipient, uint256 amount) public { uint256 claimable = claimableBalance(msg.sender); if(amount > claimable) { amount = claimable; } claimedAmounts[msg.sender] += amount; TransferHelper.safeTransfer( address(token), recipient , amount); emit Claimed(msg.sender, recipient, amount); }
9,657,256
./partial_match/80001/0x636C4701Fdd1C46e47177cef7032b26402Bf7251/sources/minter1.sol
Returns the average of two signed numbers without overflow. The result is rounded towards zero./ Formula from the book "Hacker's Delight"
function average(int256 a, int256 b) internal pure returns (int256) { int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); }
8,818,574
// SPDX-License-Identifier: MIT pragma solidity >=0.8.5 <0.9.0; contract Hacker { address public hacker; modifier onlyHacker { require(msg.sender == hacker, "caller is not the hacker"); _; } constructor() { hacker = payable(msg.sender); } function attack(address _target) public payable onlyHacker { // Claim on the throne assembly { pop( // discard result call( gas(), // gas _target, // target address callvalue(), // wei sent together with the current call 0, // input location 0, // no input params 0, // output location 0 // no need to use output params ) ) } } fallback() external payable { // Refuse to receive any ether, the transactions made by new kings will fail. revert(); } }
Claim on the throne discard result
function attack(address _target) public payable onlyHacker { assembly { pop( call( ) ) } }
12,685,019
pragma solidity ^0.4.17; library SafeMath { function mul(uint a, uint b) internal pure returns(uint) { uint c = a * b; assert(a == 0 || c / a == b); 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 && c >= b); return c; } } contract ERC20 { uint public totalSupply; function balanceOf(address who) public view returns(uint); function allowance(address owner, address spender) public view returns(uint); function transfer(address to, uint value) public returns(bool ok); function transferFrom(address from, address to, uint value) public returns(bool ok); function approve(address spender, uint value) public returns(bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; Unpause(); } } /// @title Migration Agent interface contract MigrationAgent { function migrateFrom(address _from, uint256 _value) public; } // Crowdsale Smart Contract // This smart contract collects ETH and in return sends tokens to the Backers contract Crowdsale is Pausable { using SafeMath for uint; struct Backer { uint weiReceived; // amount of ETH contributed uint tokensSent; // amount of tokens sent bool refunded; // true if user has been refunded } Token public token; // Token contract reference address public multisig; // Multisig contract that will receive the ETH address public team; // Address to which the team tokens will be sent address public zen; // Address to which zen team tokens will be sent uint public ethReceived; // Number of ETH received uint public totalTokensSent; // Number of tokens sent to ETH contributors uint public startBlock; // Crowdsale start block uint public endBlock; // Crowdsale end block uint public maxCap; // Maximum number of tokens to sell uint public minCap; // Minimum number of tokens to sell bool public crowdsaleClosed; // Is crowdsale still in progress uint public refundCount; // number of refunds uint public totalRefunded; // total amount of refunds in wei uint public tokenPriceWei; // tokn price in wei uint public minInvestETH; // Minimum amount to invest uint public presaleTokens; uint public totalWhiteListed; uint public claimCount; uint public totalClaimed; uint public numOfBlocksInMinute; // number of blocks in one minute * 100. eg. // if one block takes 13.34 seconds, the number will be 60/13.34* 100= 449 mapping(address => Backer) public backers; //backer list address[] public backersIndex; // to be able to itarate through backers for verification. mapping(address => bool) public whiteList; // @notice to verify if action is not performed out of the campaing range modifier respectTimeFrame() { require(block.number >= startBlock && block.number <= endBlock); _; } // Events event LogReceivedETH(address backer, uint amount, uint tokenAmount); event LogRefundETH(address backer, uint amount); event LogWhiteListed(address user, uint whiteListedNum); event LogWhiteListedMultiple(uint whiteListedNum); // Crowdsale {constructor} // @notice fired when contract is crated. Initilizes all constant and initial variables. function Crowdsale() public { multisig = 0xE804Ad72e60503eD47d267351Bdd3441aC1ccb03; team = 0x86Ab6dB9932332e3350141c1D2E343C478157d04; zen = 0x3334f1fBf78e4f0CFE0f5025410326Fe0262ede9; presaleTokens = 4692000e8; //TODO: ensure that this is correct amount totalTokensSent = presaleTokens; minInvestETH = 1 ether/10; // 0.1 eth startBlock = 0; // ICO start block endBlock = 0; // ICO end block maxCap = 42000000e8; // takes into consideration zen team tokens and team tokens. minCap = 8442000e8; tokenPriceWei = 80000000000000; // Price is 0.00008 eth numOfBlocksInMinute = 400; // TODO: updte this value before deploying. E.g. 4.00 block/per minute wold be entered as 400 } // @notice to populate website with status of the sale function returnWebsiteData() external view returns(uint, uint, uint, uint, uint, uint, uint, uint, bool, bool) { return (startBlock, endBlock, numberOfBackers(), ethReceived, maxCap, minCap, totalTokensSent, tokenPriceWei, paused, crowdsaleClosed); } // @notice in case refunds are needed, money can be returned to the contract function fundContract() external payable onlyOwner() returns (bool) { return true; } function addToWhiteList(address _user) external onlyOwner() returns (bool) { if (whiteList[_user] != true) { whiteList[_user] = true; totalWhiteListed++; LogWhiteListed(_user, totalWhiteListed); } return true; } function addToWhiteListMultiple(address[] _users) external onlyOwner() returns (bool) { for (uint i = 0; i < _users.length; ++i) { if (whiteList[_users[i]] != true) { whiteList[_users[i]] = true; totalWhiteListed++; } } LogWhiteListedMultiple(totalWhiteListed); return true; } // @notice Move funds from pre ICO sale if needed. function transferPreICOFunds() external payable onlyOwner() returns (bool) { ethReceived = ethReceived.add(msg.value); return true; } // @notice Specify address of token contract // @param _tokenAddress {address} address of the token contract // @return res {bool} function updateTokenAddress(Token _tokenAddress) external onlyOwner() returns(bool res) { token = _tokenAddress; return true; } // {fallback function} // @notice It will call internal function which handels allocation of Ether and calculates amout of tokens. function () external payable { contribute(msg.sender); } // @notice It will be called by owner to start the sale function start(uint _block) external onlyOwner() { require(_block < (numOfBlocksInMinute * 60 * 24 * 60)/100); // allow max 60 days for campaign startBlock = block.number; endBlock = startBlock.add(_block); } // @notice Due to changing average of block time // this function will allow on adjusting duration of campaign closer to the end function adjustDuration(uint _block) external onlyOwner() { require(_block < (numOfBlocksInMinute * 60 * 24 * 80)/100); // allow for max of 80 days for campaign require(_block > block.number.sub(startBlock)); // ensure that endBlock is not set in the past endBlock = startBlock.add(_block); } // @notice This function will finalize the sale. // It will only execute if predetermined sale time passed or all tokens are sold. function finalize() external onlyOwner() { require(!crowdsaleClosed); // purchasing precise number of tokens might be impractical, //thus subtract 1000 tokens so finalizition is possible near the end require(block.number > endBlock || totalTokensSent >= maxCap - 1000); require(totalTokensSent >= minCap); // ensure that campaign was successful crowdsaleClosed = true; if (!token.transfer(team, 45000000e8 + presaleTokens)) revert(); if (!token.transfer(zen, 3000000e8)) revert(); token.unlock(); } // @notice // This function will allow to transfer unsold tokens to a new // contract/wallet address to start new ICO in the future function transferRemainingTokens(address _newAddress) external onlyOwner() returns (bool) { require(_newAddress != address(0)); // 180 days after ICO ends assert(block.number > endBlock + (numOfBlocksInMinute * 60 * 24 * 180)/100); if (!token.transfer(_newAddress, token.balanceOf(this))) revert(); // transfer tokens to admin account or multisig wallet return true; } // @notice Failsafe drain function drain() external onlyOwner() { multisig.transfer(this.balance); } // @notice it will allow contributors to get refund in case campaign failed function refund() external whenNotPaused returns (bool) { require(block.number > endBlock); // ensure that campaign is over require(totalTokensSent < minCap); // ensure that campaign failed require(this.balance > 0); // contract will hold 0 ether at the end of the campaign. // contract needs to be funded through fundContract() for this action Backer storage backer = backers[msg.sender]; require(backer.weiReceived > 0); require(!backer.refunded); backer.refunded = true; refundCount++; totalRefunded = totalRefunded + backer.weiReceived; if (!token.burn(msg.sender, backer.tokensSent)) revert(); msg.sender.transfer(backer.weiReceived); LogRefundETH(msg.sender, backer.weiReceived); return true; } // @notice return number of contributors // @return {uint} number of contributors function numberOfBackers() public view returns(uint) { return backersIndex.length; } // @notice It will be called by fallback function whenever ether is sent to it // @param _backer {address} address of beneficiary // @return res {bool} true if transaction was successful function contribute(address _backer) internal whenNotPaused respectTimeFrame returns(bool res) { require(msg.value >= minInvestETH); // stop when required minimum is not sent require(whiteList[_backer]); uint tokensToSend = calculateNoOfTokensToSend(); require(totalTokensSent.add(tokensToSend) <= maxCap); // Ensure that max cap hasn't been reached Backer storage backer = backers[_backer]; if (backer.weiReceived == 0) backersIndex.push(_backer); backer.tokensSent = backer.tokensSent.add(tokensToSend); backer.weiReceived = backer.weiReceived.add(msg.value); ethReceived = ethReceived.add(msg.value); // Update the total Ether recived totalTokensSent = totalTokensSent.add(tokensToSend); if (!token.transfer(_backer, tokensToSend)) revert(); // Transfer SOCX tokens multisig.transfer(msg.value); // send money to multisignature wallet LogReceivedETH(_backer, msg.value, tokensToSend); // Register event return true; } // @notice This function will return number of tokens based on time intervals in the campaign function calculateNoOfTokensToSend() internal constant returns (uint) { uint tokenAmount = msg.value.mul(1e8) / tokenPriceWei; if (block.number <= startBlock + (numOfBlocksInMinute * 60) / 100) // less then one hour return tokenAmount + (tokenAmount * 50) / 100; else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24) / 100) // less than one day return tokenAmount + (tokenAmount * 25) / 100; else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 2) / 100) // less than two days return tokenAmount + (tokenAmount * 10) / 100; else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 3) / 100) // less than three days return tokenAmount + (tokenAmount * 5) / 100; else // after 3 days return tokenAmount; } } // The SOCX token contract Token is ERC20, Ownable { using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint8 public decimals; // How many decimals to show. string public version = "v0.1"; uint public initialSupply; uint public totalSupply; bool public locked; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; address public migrationMaster; address public migrationAgent; address public crowdSaleAddress; uint256 public totalMigrated; // Lock transfer for contributors during the ICO modifier onlyUnlocked() { if (msg.sender != crowdSaleAddress && locked) revert(); _; } modifier onlyAuthorized() { if (msg.sender != owner && msg.sender != crowdSaleAddress) revert(); _; } // The SOCX Token created with the time at which the crowdsale ends function Token(address _crowdSaleAddress, address _migrationMaster) public { // Lock the transfCrowdsaleer function during the crowdsale locked = true; // Lock the transfer of tokens during the crowdsale initialSupply = 90000000e8; totalSupply = initialSupply; name = "SocialX"; // Set the name for display purposes symbol = "SOCX"; // Set the symbol for display purposes decimals = 8; // Amount of decimals for display purposes crowdSaleAddress = _crowdSaleAddress; balances[crowdSaleAddress] = totalSupply; migrationMaster = _migrationMaster; } function unlock() public onlyAuthorized { locked = false; } function lock() public onlyAuthorized { locked = true; } event Migrate(address indexed _from, address indexed _to, uint256 _value); // Token migration support: /// @notice Migrate tokens to the new token contract. /// @dev Required state: Operational Migration /// @param _value The amount of token to be migrated function migrate(uint256 _value) external onlyUnlocked() { // Abort if not in Operational Migration state. if (migrationAgent == 0) revert(); // Validate input value. if (_value == 0) revert(); if (_value > balances[msg.sender]) revert(); balances[msg.sender] -= _value; totalSupply -= _value; totalMigrated += _value; MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value); Migrate(msg.sender, migrationAgent, _value); } /// @notice Set address of migration target contract and enable migration /// process. /// @dev Required state: Operational Normal /// @dev State transition: -> Operational Migration /// @param _agent The address of the MigrationAgent contract function setMigrationAgent(address _agent) external onlyUnlocked() { // Abort if not in Operational Normal state. require(migrationAgent == 0); require(msg.sender == migrationMaster); migrationAgent = _agent; } function resetCrowdSaleAddress(address _newCrowdSaleAddress) external onlyAuthorized() { crowdSaleAddress = _newCrowdSaleAddress; } function setMigrationMaster(address _master) external { require(msg.sender == migrationMaster); require(_master != 0); migrationMaster = _master; } // @notice burn tokens in case campaign failed // @param _member {address} of member // @param _value {uint} amount of tokens to burn // @return {bool} true if successful function burn( address _member, uint256 _value) public onlyAuthorized returns(bool) { balances[_member] = balances[_member].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(_member, 0x0, _value); return true; } // @notice transfer tokens to given address // @param _to {address} address or recipient // @param _value {uint} amount to transfer // @return {bool} true if successful function transfer(address _to, uint _value) public onlyUnlocked returns(bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } // @notice transfer tokens from given address to another address // @param _from {address} from whom tokens are transferred // @param _to {address} to whom tokens are transferred // @parm _value {uint} amount of tokens to transfer // @return {bool} true if successful function transferFrom(address _from, address _to, uint256 _value) public onlyUnlocked returns(bool success) { require(balances[_from] >= _value); // Check if the sender has enough require(_value <= allowed[_from][msg.sender]); // Check if allowed is greater or equal balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } // @notice to query balance of account // @return _owner {address} address of user to query balance function balanceOf(address _owner) public view returns(uint balance) { return balances[_owner]; } /** * @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, uint _value) public returns(bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // @notice to query of allowance of one user to the other // @param _owner {address} of the owner of the account // @param _spender {address} of the spender of the account // @return remaining {uint} amount of remaining allowance function allowance(address _owner, address _spender) public view returns(uint remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
it will allow contributors to get refund in case campaign failed contract needs to be funded through fundContract() for this action
function refund() external whenNotPaused returns (bool) { Backer storage backer = backers[msg.sender]; require(backer.weiReceived > 0); require(!backer.refunded); backer.refunded = true; refundCount++; totalRefunded = totalRefunded + backer.weiReceived; if (!token.burn(msg.sender, backer.tokensSent)) revert(); msg.sender.transfer(backer.weiReceived); LogRefundETH(msg.sender, backer.weiReceived); return true; }
1,071,684
pragma solidity 0.6.12; // SPDX-License-Identifier: MIT import '@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/access/Ownable.sol'; import "./ArtichainToken.sol"; interface IMigratorArt { // Perform LP token migration from legacy PancakeSwap to ArtichainSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to PancakeSwap LP tokens. // ArtichainSwap must mint EXACTLY the same amount of PancakeSwap LP tokens or // else something bad will happen. Traditional PancakeSwap does not // do that so be careful! function migrate(IBEP20 token) external returns (IBEP20); } // MasterArt is the master of Ait. He can make Ait and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once AIT is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterArt is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of AITs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accAitPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accAitPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. AITs to distribute per block. uint256 lastRewardBlock; // Last block number that AITs distribution occurs. uint256 accAitPerShare; // Accumulated AITs per share, times 1e12. See below. uint16 depositFee; // Deposit fee in basis points } // Block reward plan struct BlockRewardInfo { uint256 firstBlock; // First block number uint256 lastBlock; // Last block number uint256 reward; // Block reward amount } // The Artichain TOKEN! ArtichainToken public ait; // Dev address. address public devAddr; // Fee address address public feeAddr; // Bonus muliplier for early ait makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorArt public migrator; // Info of each pool. PoolInfo[] public poolInfo; BlockRewardInfo[] public rewardInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when AIT mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetFeeAddress(address indexed user, address indexed newAddress); event SetDevAddress(address indexed user, address indexed newAddress); constructor( ArtichainToken _ait, address _devAddr, address _feeAddr, uint256 _startBlock ) public { ait = _ait; devAddr = _devAddr; feeAddr = _feeAddr; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _ait, allocPoint: 1000, lastRewardBlock: startBlock, accAitPerShare: 0, depositFee: 0 })); setRewardInfo(); totalAllocPoint = 1000; } function updateMultiplier(uint256 multiplierNumber) external onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFee, bool _withUpdate) external onlyOwner { require(_depositFee <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accAitPerShare: 0, depositFee: _depositFee })); updateStakingPool(); } // Update the given pool's AIT allocation point and deposit fee. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFee, bool _withUpdate) external onlyOwner { require(_depositFee <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFee = _depositFee; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Set the migrator contract. Can only be called by the owner. // function setMigrator(IMigratorArt _migrator) external onlyOwner { // migrator = _migrator; // } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. // function migrate(uint256 _pid) external { // require(address(migrator) != address(0), "migrate: no migrator"); // PoolInfo storage pool = poolInfo[_pid]; // IBEP20 lpToken = pool.lpToken; // uint256 bal = lpToken.balanceOf(address(this)); // lpToken.safeApprove(address(migrator), bal); // IBEP20 newLpToken = migrator.migrate(lpToken); // require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); // pool.lpToken = newLpToken; // } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // Returns reward for each block function getBlockReward() external view returns (uint256) { if(block.number < startBlock) return 0; for(uint i = 0; i < 3; i++) { if(block.number <= rewardInfo[i].lastBlock) { return rewardInfo[i].reward; } } return 0; } // Update reward table for 3 years // first year reward: 4000 // second year reward: 2000 // third year reward: 1000 function setRewardInfo() internal { if(rewardInfo.length == 0) { uint256 supply = 4000; for(uint i = 0; i < 3; i++) { uint256 perBlockReward = supply.mul(3 * 1e18).mul(100).div(110).div(365 days); rewardInfo.push(BlockRewardInfo({firstBlock: 0, lastBlock: 0, reward: perBlockReward})); supply = supply.div(2); } } uint256 _firstBlock = startBlock; for(uint i = 0; i < 3; i++) { rewardInfo[i].firstBlock = _firstBlock; rewardInfo[i].lastBlock = _firstBlock + (365 days) / 3; _firstBlock = _firstBlock + (365 days) / 3 + 1; } } function calcPoolReward(uint256 _pid) internal view returns (uint256){ PoolInfo storage pool = poolInfo[_pid]; if(block.number < startBlock) return 0; uint256 aitReward = 0; uint256 lastBlock = pool.lastRewardBlock; for(uint i = 0; i < 3; i++) { if(pool.lastRewardBlock > rewardInfo[i].lastBlock) continue; if(block.number <= rewardInfo[i].lastBlock) { uint256 multiplier = getMultiplier(lastBlock, block.number); uint256 _reward = multiplier.mul(rewardInfo[i].reward); aitReward = aitReward.add(_reward); break; } else { uint256 multiplier = getMultiplier(lastBlock, rewardInfo[i].lastBlock); uint256 _reward = multiplier.mul(rewardInfo[i].reward); aitReward = aitReward.add(_reward); } lastBlock = rewardInfo[i].lastBlock; } return aitReward.mul(pool.allocPoint).div(totalAllocPoint); } // View function to see pending AITs on frontend. function pendingAit(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAitPerShare = pool.accAitPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 aitReward = calcPoolReward(_pid); accAitPerShare = accAitPerShare.add(aitReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAitPerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 aitReward = calcPoolReward(_pid); ait.mint(devAddr, aitReward.div(10)); // 10% is dev reward ait.mint(address(this), aitReward); pool.accAitPerShare = pool.accAitPerShare.add(aitReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterArt for AIT allocation. function deposit(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accAitPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAitTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFee > 0) { uint256 depositFee = _amount.mul(pool.depositFee).div(10000); pool.lpToken.safeTransfer(feeAddr, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); } else { user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accAitPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterArt. function withdraw(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accAitPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeAitTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accAitPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe ait transfer function, just in case if rounding error causes pool to not have enough AITs. function safeAitTransfer(address _to, uint256 _amount) internal { uint256 aitBal = ait.balanceOf(address(this)); bool transferSuccess = false; if (_amount > aitBal) { transferSuccess = ait.transfer(_to, aitBal); } else { transferSuccess = ait.transfer(_to, _amount); } require(transferSuccess, "safeAitTransfer: transfer failed"); } // Update dev address by the previous dev. function dev(address _devAddr) external { require(msg.sender == devAddr, "dev: wut?"); devAddr = _devAddr; emit SetDevAddress(msg.sender, _devAddr); } // Update fee address by the previous fee manager. function setFeeAddress(address _feeAddr) external { require(msg.sender == feeAddr, "setFeeAddress: Forbidden"); feeAddr = _feeAddr; emit SetFeeAddress(msg.sender, _feeAddr); } function updateStartBlock(uint256 _startBlock) external onlyOwner { require(block.number < startBlock, "Staking was started already"); require(block.number < _startBlock); startBlock = _startBlock; setRewardInfo(); } }
Update dev address by the previous dev.
function dev(address _devAddr) external { require(msg.sender == devAddr, "dev: wut?"); devAddr = _devAddr; emit SetDevAddress(msg.sender, _devAddr); }
12,854,211
pragma solidity ^0.6.1; pragma experimental ABIEncoderV2; import "./ISellerAdmin.sol"; import "./IAddressRegistry.sol"; import "./IBusinessPartnerStorage.sol"; import "./IPurchasing.sol"; import "./IFunding.sol"; import "./Ownable.sol"; import "./Bindable.sol"; import "./StringConvertible.sol"; /// @title SellerAdmin contract SellerAdmin is ISellerAdmin, Ownable, Bindable, StringConvertible { // Global data (shared by all eShops) IBusinessPartnerStorage public businessPartnerStorageGlobal; // Local data (for this Seller) bytes32 public sellerId; bool public isConfigured; constructor (string memory sellerIdString) public { isConfigured = false; sellerId = stringToBytes32(sellerIdString); } modifier onlyConfigured { require(isConfigured == true, "Contract needs configured first"); _; } function configure(address businessPartnerStorageAddressGlobal) override external onlyOwner { businessPartnerStorageGlobal = IBusinessPartnerStorage(businessPartnerStorageAddressGlobal); // Check master data is correct IPoTypes.Seller memory seller = businessPartnerStorageGlobal.getSeller(sellerId); require(seller.sellerId.length > 0, "Seller has no master data"); require(seller.adminContractAddress != address(0), "Seller has no admin contract address"); require(seller.isActive == true, "Seller is inactive"); isConfigured = true; } // Purchasing /// @notice This function can only be called by the eShop (Purchasing.sol) for the given PO, which means: /// 1) SellerAdmin owner must have bound (whitelisted) the Purchasing.sol contract when they registered with the eShop /// 2) msg.sender must match the PO's eShop's purchasing contract address retrieved from global storage function emitEventForNewPo(IPoTypes.Po calldata po) override external onlyConfigured onlyRegisteredCaller { IPoTypes.Eshop memory eShop = getAndValidateEshop(po.eShopId); require(eShop.purchasingContractAddress == msg.sender, "Function can only be called by eShop"); emit QuoteConvertedToPoLog(po.eShopId, po.quoteId, po.buyerWalletAddress); } function getPo(string calldata eShopIdString, uint poNumber) override external view onlyConfigured returns (IPoTypes.Po memory po) { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); return purchasing.getPo(poNumber); } function getPoByEshopIdAndQuote(string calldata eShopIdString, uint quoteId) override external view onlyConfigured returns (IPoTypes.Po memory po) { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); return purchasing.getPoByQuote(quoteId); } function setPoItemAccepted(string calldata eShopIdString, uint poNumber, uint8 poItemNumber, bytes32 soNumber, bytes32 soItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemAccepted(poNumber, poItemNumber, soNumber, soItemNumber); } function setPoItemRejected(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemRejected(poNumber, poItemNumber); } function setPoItemReadyForGoodsIssue(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemReadyForGoodsIssue(poNumber, poItemNumber); } function setPoItemGoodsIssued(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemGoodsIssued(poNumber, poItemNumber); } function setPoItemGoodsReceived(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemGoodsReceivedSeller(poNumber, poItemNumber); } function setPoItemCompleted(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { // Get and validate eShop bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemCompleted(poNumber, poItemNumber); } function getAndValidateEshop(bytes32 eShopId) private view returns (IPoTypes.Eshop memory validShop) { IPoTypes.Eshop memory eShop = businessPartnerStorageGlobal.getEshop(eShopId); require(eShop.purchasingContractAddress != address(0), "eShop has no purchasing address"); require(eShop.quoteSignerCount > 0, "No quote signers found for eShop"); return eShop; } }
Get and validate eShop
function setPoItemGoodsReceived(string calldata eShopIdString, uint poNumber, uint8 poItemNumber) override external onlyConfigured onlyRegisteredCaller { bytes32 eShopId = stringToBytes32(eShopIdString); IPoTypes.Eshop memory eShop = getAndValidateEshop(eShopId); IPurchasing purchasing = IPurchasing(eShop.purchasingContractAddress); purchasing.setPoItemGoodsReceivedSeller(poNumber, poItemNumber); }
13,115,650
./full_match/1/0x56102B469d7B0650E92426611Eb2Ea84C0cA9b2A/sources/contracts/QuestFactory.sol
Create an erc20 quest rewardTokenAddress_ The contract address of the reward token endTime_ The end time of the quest startTime_ The start time of the quest totalParticipants_ The total amount of participants (accounts) the quest will have rewardAmount_ The reward amount for an erc20 quest questId_ The id of the quest return address the quest contract address
function createQuest( address rewardTokenAddress_, uint256 endTime_, uint256 startTime_, uint256 totalParticipants_, uint256 rewardAmount_, string memory questId_ ) external checkQuest(questId_, rewardTokenAddress_) returns (address) { address newQuest = createQuestInternal( rewardTokenAddress_, endTime_, startTime_, totalParticipants_, rewardAmount_, questId_, 0 ); QuestContract(newQuest).transferOwnership(msg.sender); return newQuest; }
3,008,727
./full_match/4/0x3B022a535b870eB5959F6F518f448Aa1c70Bd471/sources/contracts/BitPixelNFTs.sol
by a token by passing in the token's id check if the function caller is not an zero account address check if the token id of the token being bought exists or not get the token's owner token's owner should not be an zero address account the one who wants to buy the token should not be the token's owner get that token from all BitPixelNFTs mapping and create a memory of it defined as (struct => BitPixelNFT) price sent in to buy should be equal to or more than the token's price token should be for sale transfer the token from owner to the caller of the function (buyer) get owner of the token send token's worth of ethers to the owner update the token's previous owner update the token's current owner update the how many times this token was transfered set and update that token in the mapping
function buyToken(uint256 _tokenId) public payable { require(msg.sender != address(0)); require(_exists(_tokenId)); address tokenOwner = ownerOf(_tokenId); require(tokenOwner != address(0)); require(tokenOwner != msg.sender); BitPixelNFT memory BitPixelnft = allBitPixelNFTs[_tokenId]; require(msg.value >= BitPixelnft.price); require(BitPixelnft.forSale); _transfer(tokenOwner, msg.sender, _tokenId); address payable sendTo = BitPixelnft.currentOwner; sendTo.transfer(msg.value); BitPixelnft.previousOwner = BitPixelnft.currentOwner; BitPixelnft.currentOwner = msg.sender; BitPixelnft.numberOfTransfers += 1; allBitPixelNFTs[_tokenId] = BitPixelnft; }
12,338,819
// contracts/BadgeTokenFactory.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../node_modules/@openzeppelin/contracts/utils/Counters.sol"; import "./BadgeDefinitionFactory.sol"; import "./BadgeQueryOracle.sol"; /** * @title BadgeTokenFactory * @author Geoffrey Garcia * @notice Contract to use to mint and to transfer (if applicable based on associated BadgeDefinition) BadgeToken that are ERC721 tokens. * @dev The BadgeTokenFactory contract provides basic structures, functions & modifiers that allows to manage BadgeToken as ERC721 token. */ contract BadgeTokenFactory is BadgeFactory { using Counters for Counters.Counter; /** * @notice Event emitted to request for a query to be run. * @dev Event emitted to request for a query to be run for BadgeToken minting. * @param _requestID The ID of the query. * @param _indexer The service indexing the data (possible values: "thegraph, "covalent"). * @param _protocol The set/subgraph on the indexer to use (possible values: "uniswap", "compound" ,"aave" ,"ethereum"). * @param _query The query to run. */ event QueryRequest(bytes32 _requestID, string _indexer, string _protocol, string _query); /** * @notice Event emitted after the query and its result have been record into the blockchain. * @dev Event emitted fter the query and its result have been record into the blockchain for BadgeToken minting. * @param _requestID The ID of the query. * @param _queryResult The result of the query. */ event QueryResultReceived(bytes32 _requestID, string _queryResult); /** * @notice Event emitted when a BadgeToken is ready to be minted. * @dev Event emitted when a BadgeToken is ready to be minted. * @param _caller The Ethereum address which has requested for the right to mint the token. * @param _badgeDefinitionId The ID of BadgeDefinition associated to this BadgeToken. */ event BadgeTokenReady(address _caller, uint _badgeDefinitionId); /** * @notice Event emitted after a BadgeToken minting. * @dev Event emitted after a BadgeToken minting. * @param _badgeTokenId The ID of the BadgeToken. * @param _originalOwner The Ethereum address of the user that has minted the token. */ event NewBadgeToken(uint _badgeTokenId, address _originalOwner); // Badge token structure struct BadgeToken { uint badgeDefinitionId; // the ID of BadgeDefinition associated to this BadgeToken address originalOwner; // the Ethereum address of the user that has minted the token string[maxNumberOfAttributionConditions] specialValues; // the special value associated with this badge (optional) } // Pending minting structure struct PendingMinting { address caller; // the Ethereum address which has requested for the query result uint badgeDefinitionId; // the ID of BadgeDefinition associated to the BadgeToken the user want to mint uint numberOfConditions; // the number of conditions that have to be evaluated through as many queries mapping (uint => bytes32) _queryIndex; // the IDs of the queries mapping (bytes32 => bool) _pendingQueryStatus; // the current status of the queries (true if pending) mapping (bytes32 => string) _queryResult; // the results of the queries (usable only if associated _pendingQueryStatus value is false) mapping (bytes32 => string) _evaluationOperator; // the operator allowing to compare the query return mapping (bytes32 => string) _evaluationCondition; // the value to compare with the query result } // Storage of the badge tokens BadgeToken[] private _badgeTokens; // BadgeToken storage mapping(address => mapping(uint => uint)) private _ownedBadges; // List of BadgeToken IDs per owner per BadgeDefinition string badgeTokenSymbol = "BTO"; // Symbol of the ERC721 tokens of the BadgeToken // Storage of the badge minting Counters.Counter private _mintingNonce; // a nonce injected to build the ID of the condition group to mint the badge mapping(bytes32 => PendingMinting) private _pendingMintings; // the list of pending badge mintings mapping(address => mapping(uint => bytes32)) private _pendingMintingBadges; // List of pending badge mintings per owner per BadgeDefinition mapping(bytes32 => bytes32) private _pendingQueries; // the list of pending queriesn // Reference to the BadgeDefinitionFactory contract allowing to manage BadgeDefinition BadgeDefinitionFactory badgeDefinitionFactory; // Reference to the BadgeQueryOracle contract allowing to run query on off-chain ressources BadgeQueryOracle badgeQueryOracle; /** * @dev See {ERC721-constructor}. * @param _badgeDefinitionFactoryAddress The Ethereum address of the BadgeDefinitionFactory contract allowing to manage BadgeDefinition. */ constructor(address _badgeDefinitionFactoryAddress) BadgeFactory("BadgeToken", badgeTokenSymbol) { // Linking this contract with the already deployed one BadgeDefinitionFactory badgeDefinitionFactory = BadgeDefinitionFactory(_badgeDefinitionFactoryAddress); // Linking this contract with a freshly instantiated BadgeQueryOracle badgeQueryOracle = new BadgeQueryOracle(); } /** * @dev Throws if the badge is already owned. * @param _badgeDefinitionId The ID of BadgeDefinition associated to this BadgeToken. */ modifier notOwned(uint _badgeDefinitionId) { require(_ownedBadges[_msgSender()][_badgeDefinitionId] == 0, string(abi.encodePacked(badgeTokenSymbol, ": badge already owned"))); //TODO: check orignalOwner instead? _; } /** * @dev Throws if the badge minting process is already in progress. * @param _badgeDefinitionId The ID of BadgeDefinition associated to this BadgeToken. */ modifier isNotPendingMinting(uint _badgeDefinitionId) { require(_pendingMintingBadges[_msgSender()][_badgeDefinitionId] == 0, string(abi.encodePacked(badgeTokenSymbol, ": badge already in minting process"))); _; } /** * @dev Throws if the badge minting process is not in progress. * @param _badgeDefinitionId The ID of BadgeDefinition associated to this BadgeToken. */ modifier isPendingMinting(uint _badgeDefinitionId) { require(_pendingMintingBadges[_msgSender()][_badgeDefinitionId] != 0, string(abi.encodePacked(badgeTokenSymbol, ": badge not in minting process"))); _; } /** * @notice Function to mint a BadgeToken as ERC721 tokens. * @dev Creates & store a BadgeToken. * @param _badgeDefinitionId The ID of BadgeDefinition associated to this BadgeToken. */ function requestBadgeTokenMinting(uint _badgeDefinitionId) notOwned(_badgeDefinitionId) isNotPendingMinting(_badgeDefinitionId) public { // Creating for the penting minting _mintingNonce.increment(); bytes32 badgeConditionGroupID = keccak256(abi.encodePacked(block.timestamp, _msgSender(), _mintingNonce.current())); // Add the badge minting to the ones asked by the user _pendingMintingBadges[_msgSender()][_badgeDefinitionId] = badgeConditionGroupID; // Storing for the penting minting PendingMinting storage pendingMinting = _pendingMintings[badgeConditionGroupID]; pendingMinting.caller = _msgSender(); // Get the BadgeAttributionCondition list associated to this BadgeDefinition BadgeAttributionCondition[maxNumberOfAttributionConditions] memory badgeAttributionCondition; uint numberOfConditions = 0; (numberOfConditions, badgeAttributionCondition) = badgeDefinitionFactory.getBadgeDefinitionAttributionCondition(_badgeDefinitionId); pendingMinting.numberOfConditions = numberOfConditions; // Check for every condition in the list for(uint i=0; i < numberOfConditions; i++){ // Ask the Oracle to obtain the result of the query bytes32 requestID = badgeQueryOracle.runQuery(_msgSender(), badgeConditionGroupID, badgeAttributionCondition[i].indexer, badgeAttributionCondition[i].protocol, badgeAttributionCondition[i].query); // Asking for the query to be run emit QueryRequest(requestID, badgeAttributionCondition[i].indexer, badgeAttributionCondition[i].protocol, badgeAttributionCondition[i].query); // Store the references & status of the query _pendingQueries[requestID] = badgeConditionGroupID; pendingMinting._queryIndex[i] = requestID; pendingMinting._pendingQueryStatus[requestID] = true; pendingMinting._evaluationOperator[requestID] = badgeAttributionCondition[i].operator; pendingMinting._evaluationCondition[requestID] = badgeAttributionCondition[i].condition; } } /** * @notice Function to get the result of a query. * @dev Store the result of the query then ask for the Oracle to write it into the blockchain. * @param _requestID The ID of the query. * @param _queryResult The result of the query. */ function updateBadgeTokenMinting(bytes32 _requestID, string memory _queryResult) public { bytes32 badgeConditionGroupID = _pendingQueries[_requestID]; // string memory requestIDString = _bytes32ToString(_requestID); // require(badgeConditionGroupID != 0, string(abi.encodePacked(badgeTokenSymbol, ": wrong request ID(", requestIDString, ") badgeConditionGroupID:", badgeConditionGroupID))); require(badgeConditionGroupID != 0, string(abi.encodePacked(badgeTokenSymbol, ": wrong request ID(", _requestID, ")"))); // Storing the result PendingMinting storage pendingMinting = _pendingMintings[badgeConditionGroupID]; pendingMinting._pendingQueryStatus[_requestID] = false; pendingMinting._queryResult[_requestID] = _queryResult; // Sending the result to the Oracle badgeQueryOracle.recordQueryResult(pendingMinting.caller, badgeConditionGroupID, _requestID, _queryResult); // Telling the query has been recorded emit QueryResultReceived(_requestID, _queryResult); // Evaluating overall minting process status bool evaluationResult = false; for(uint i=0; (i < pendingMinting.numberOfConditions) && (evaluationResult == false); i++){ // Retrieving another query ID bytes32 requestID = pendingMinting._queryIndex[i]; // Evaluate if the condition is met evaluationResult = pendingMinting._pendingQueryStatus[requestID]; } // Emetting a signal if all the queries have been run if(evaluationResult == false){ emit BadgeTokenReady(pendingMinting.caller, pendingMinting.badgeDefinitionId); } } /** * @notice Function to mint a BadgeToken as ERC721 tokens. * @dev Creates & store a BadgeToken. * @param _badgeDefinitionId The ID of BadgeDefinition associated to this BadgeToken. * @return _badgeTokenId The ID of the new BadgeToken. */ function mintBadgeToken(uint _badgeDefinitionId) notOwned(_badgeDefinitionId) isPendingMinting(_badgeDefinitionId) public returns (uint _badgeTokenId) { // Identifying the badge the user want to mint bytes32 badgeConditionGroupID = _pendingMintingBadges[_msgSender()][_badgeDefinitionId]; PendingMinting storage pendingMinting = _pendingMintings[badgeConditionGroupID]; require(_msgSender() == pendingMinting.caller, string(abi.encodePacked(badgeTokenSymbol, ": not the user who has requested the token"))); string[maxNumberOfAttributionConditions] memory _specialValues; require(_assessAttributionCondition(pendingMinting, _specialValues), string(abi.encodePacked(badgeTokenSymbol, ": attempt to mint a token without fullfilling the attribution conditions to get it"))); // Storing the BadgeToken _badgeTokens.push(BadgeToken({ badgeDefinitionId: _badgeDefinitionId, originalOwner: _msgSender(), specialValues: _specialValues})); // Getting the ID of the new BadgeToken // uint badgeTokenId = _badgeTokens.length - 1; uint badgeTokenId = _badgeTokens.length; // Add the badge to the ones owned by the user _ownedBadges[_msgSender()][_badgeDefinitionId] = badgeTokenId; // Minting the BadgeToken _safeMint(_msgSender(), badgeTokenId); // Removing the stored pending badge minting for(uint i=0; i < pendingMinting.numberOfConditions; i++){ bytes32 requestID = pendingMinting._queryIndex[i]; delete _pendingQueries[requestID]; delete pendingMinting._pendingQueryStatus[requestID]; delete pendingMinting._queryResult[requestID]; delete pendingMinting._evaluationOperator[requestID]; delete pendingMinting._evaluationCondition[requestID]; delete pendingMinting._queryIndex[i]; } delete _pendingMintingBadges[_msgSender()][_badgeDefinitionId]; delete _pendingMintings[badgeConditionGroupID]; // Emit the appropriate event emit NewBadgeToken(badgeTokenId, _msgSender()); return badgeTokenId; } /** * @notice Function to test if the badge produced using a BadgeDefinition can be mint. * @dev Check if the conditions to mint the badge are met. * @param _pendingMinting The pending badge minting structure. * @param _specialValues The special values to be stored (optional). * @return _evaluationResult The result of the test. */ function _assessAttributionCondition(PendingMinting storage _pendingMinting, string[maxNumberOfAttributionConditions] memory _specialValues) private view returns (bool _evaluationResult) { _evaluationResult = true; // Check for every condition in the list for(uint i=0; (i < _pendingMinting.numberOfConditions) && (_evaluationResult == true); i++){ // Retrieving the query ID bytes32 requestID = _pendingMinting._queryIndex[i]; // Evaluate if the condition is met _evaluationResult = _evaluateCondition(_pendingMinting._queryResult[requestID], _pendingMinting._evaluationOperator[requestID], _pendingMinting._evaluationCondition[requestID], _specialValues[i]); } return _evaluationResult; } /** * @notice Function to evaluate a condition. * @dev Check if a condition to mint a badge is met. * @param _queryResult The result of the query. * @param _operator The operator allowing to compare the query return. * @param _condition The value to compare with the query result. * @param _specialValue The special value to be stored (optional). * @return _evaluationResult The result of the test. */ function _evaluateCondition(string memory _queryResult, string memory _operator, string memory _condition, string memory _specialValue) private pure returns (bool _evaluationResult) { _evaluationResult = false; bytes32 operatorHash = keccak256(bytes(_operator)); // Evaluate the query return if(operatorHash == keccak256(bytes("<"))){ _evaluationResult = _stringToUint(_queryResult) < _stringToUint(_condition); } else{ if(operatorHash == keccak256(bytes("<="))){ _evaluationResult = _stringToUint(_queryResult) <= _stringToUint(_condition); } else{ if(operatorHash == keccak256(bytes(">"))){ _evaluationResult = _stringToUint(_queryResult) > _stringToUint(_condition); } else{ if(operatorHash == keccak256(bytes(">="))){ _evaluationResult = _stringToUint(_queryResult) >= _stringToUint(_condition); // _evaluationResult = false; } else{ if(operatorHash == keccak256(bytes("=="))){ _evaluationResult = _stringToUint(_queryResult) == _stringToUint(_condition); } else{ if(operatorHash == keccak256(bytes("!="))){ _evaluationResult = _stringToUint(_queryResult) != _stringToUint(_condition); } else{ if(operatorHash == keccak256(bytes("special"))){ _evaluationResult = true; _specialValue = _queryResult; } else{ } } } } } } } return _evaluationResult; } /** * @notice Function to test if the badge produced using a BadgeDefinition can be mint. * @dev Check if the conditions to mint the badge are met. * @param _owner The Ethereum address of the user. * @param _badgeDefinitionId The ID of BadgeDefinition. * @return _evaluationResult The result of the test. */ function doesOwnBadgeFromGivenDefinition(address _owner, uint _badgeDefinitionId) public view returns (bool _evaluationResult) { _evaluationResult = true; // Check for a BadgeToken potentially owned by this user associated to the BadgeDefinition if(_ownedBadges[_owner][_badgeDefinitionId] == 0){ _evaluationResult = false; } return _evaluationResult; } /** * @notice Function to transfer a token (if applicable). * @dev Transfers `tokenId` from `from` to `to`. * @param from The Ethereum address of the user that own the token. * @param to The Ethereum address of the user that could receive the token. * @param tokenId The ID of the BadgeToken. */ function _transfer(address from, address to, uint256 tokenId) internal override { uint tokenIdex = tokenId - 1; // Check if the token can be transfered require(badgeDefinitionFactory.isBadgeTransferable(_badgeTokens[tokenIdex].badgeDefinitionId), string(abi.encodePacked(badgeTokenSymbol, ": this token is bind to its original owner", _badgeTokens[tokenIdex].originalOwner))); // Transfer the token (if applicable) super._transfer(from, to, tokenId); } /** * @notice Function to get the URI associated to a token. * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. * @param tokenId The ID of the BadgeToken. * @return The result URI associated to the token. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); uint tokenIdex = tokenId - 1; string memory URI = badgeDefinitionFactory.tokenURI(_badgeTokens[tokenIdex].badgeDefinitionId); return bytes(URI).length > 0 ? string(URI) : ''; } }
Function to test if the badge produced using a BadgeDefinition can be mint. Check if the conditions to mint the badge are met. _pendingMinting The pending badge minting structure. _specialValues The special values to be stored (optional). return _evaluationResult The result of the test./ Check for every condition in the list Retrieving the query ID Evaluate if the condition is met
function _assessAttributionCondition(PendingMinting storage _pendingMinting, string[maxNumberOfAttributionConditions] memory _specialValues) private view returns (bool _evaluationResult) { _evaluationResult = true; for(uint i=0; (i < _pendingMinting.numberOfConditions) && (_evaluationResult == true); i++){ bytes32 requestID = _pendingMinting._queryIndex[i]; _evaluationResult = _evaluateCondition(_pendingMinting._queryResult[requestID], _pendingMinting._evaluationOperator[requestID], _pendingMinting._evaluationCondition[requestID], _specialValues[i]); } return _evaluationResult; }
15,821,785
pragma solidity 0.4.26; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } 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); } 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 ); } library ArrayUtils { /** * Replace bytes in an array with bytes in another array, guarded by a bitmask * Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower) * * @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed. * @param array The original array * @param desired The target array * @param mask The mask specifying which bits can be changed * @return The updated byte array (the parameter will be modified inplace) */ function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask) internal pure { require(array.length == desired.length); require(array.length == mask.length); uint words = array.length / 0x20; uint index = words * 0x20; assert(index / 0x20 == words); uint i; for (i = 0; i < words; i++) { /* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */ assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } /* Deal with the last section of the byte array. */ if (words > 0) { /* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */ i = words; assembly { let commonIndex := mul(0x20, add(1, i)) let maskValue := mload(add(mask, commonIndex)) mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex))))) } } else { /* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise. (bounds checks could still probably be optimized away in assembly, but this is a rare case) */ for (i = index; i < array.length; i++) { array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]); } } } /** * Test if two arrays are equal * @param a First array * @param b Second array * @return Whether or not all bytes in the arrays are equal */ function arrayEq(bytes memory a, bytes memory b) internal pure returns (bool) { return keccak256(a) == keccak256(b); } /** * Unsafe write byte array into a memory location * * @param index Memory location * @param source Byte array to write * @return End memory index */ function unsafeWriteBytes(uint index, bytes source) internal pure returns (uint) { if (source.length > 0) { assembly { let length := mload(source) let end := add(source, add(0x20, length)) let arrIndex := add(source, 0x20) let tempIndex := index for { } eq(lt(arrIndex, end), 1) { arrIndex := add(arrIndex, 0x20) tempIndex := add(tempIndex, 0x20) } { mstore(tempIndex, mload(arrIndex)) } index := add(index, length) } } return index; } /** * Unsafe write address into a memory location * * @param index Memory location * @param source Address to write * @return End memory index */ function unsafeWriteAddress(uint index, address source) internal pure returns (uint) { uint conv = uint(source) << 0x60; assembly { mstore(index, conv) index := add(index, 0x14) } return index; } /** * Unsafe write address into a memory location using entire word * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteAddressWord(uint index, address source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write uint into a memory location * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteUint(uint index, uint source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write uint8 into a memory location * * @param index Memory location * @param source uint8 to write * @return End memory index */ function unsafeWriteUint8(uint index, uint8 source) internal pure returns (uint) { assembly { mstore8(index, source) index := add(index, 0x1) } return index; } /** * Unsafe write uint8 into a memory location using entire word * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteUint8Word(uint index, uint8 source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } /** * Unsafe write bytes32 into a memory location using entire word * * @param index Memory location * @param source uint to write * @return End memory index */ function unsafeWriteBytes32(uint index, bytes32 source) internal pure returns (uint) { assembly { mstore(index, source) index := add(index, 0x20) } return index; } } contract ReentrancyGuarded { bool reentrancyLock = false; /* Prevent a contract function from being reentrant-called. */ modifier reentrancyGuard { if (reentrancyLock) { revert(); } reentrancyLock = true; _; reentrancyLock = false; } } contract TokenRecipient { event ReceivedEther(address indexed sender, uint amount); event ReceivedTokens(address indexed from, uint256 value, address indexed token, bytes extraData); /** * @dev Receive tokens and generate a log event * @param from Address from which to transfer tokens * @param value Amount of tokens to transfer * @param token Address of token * @param extraData Additional data to log */ function receiveApproval(address from, uint256 value, address token, bytes extraData) public { ERC20 t = ERC20(token); require(t.transferFrom(from, this, value)); emit ReceivedTokens(from, value, token, extraData); } /** * @dev Receive Ether and generate a log event */ function () payable public { emit ReceivedEther(msg.sender, msg.value); } } contract ExchangeCore is ReentrancyGuarded, Ownable { string public constant name = "StarBlock Exchange Contract"; string public constant version = "1.0"; // NOTE: these hashes are derived and verified in the constructor. bytes32 private constant _EIP_712_DOMAIN_TYPEHASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f; bytes32 private constant _NAME_HASH = 0x908be1d09f2d17dd8812f5561d84e89cc7052e553487116c4cf73793bdba635d; bytes32 private constant _VERSION_HASH = 0xe6bbd6277e1bf288eed5e8d1780f9a50b239e86b153736bceebccf4ea79d90b3; bytes32 private constant _ORDER_TYPEHASH = 0xdba08a88a748f356e8faf8578488343eab21b1741728779c9dcfdc782bc800f8; bytes4 private constant _EIP_1271_MAGIC_VALUE = 0x1626ba7e; // // NOTE: chainId opcode is not supported in solidiy 0.4.x; here we hardcode as 1. // In order to protect against orders that are replayable across forked chains, // either the solidity version needs to be bumped up or it needs to be retrieved // from another contract. uint256 private constant _CHAIN_ID = 1; // Note: the domain separator is derived and verified in the constructor. */ bytes32 public constant DOMAIN_SEPARATOR = _deriveDomainSeparator(); /* The token used to pay exchange fees. */ ERC20 public exchangeToken; /* User registry. */ ProxyRegistry public registry; /* Token transfer proxy. */ TokenTransferProxy public tokenTransferProxy; /* Cancelled / finalized orders, by hash. */ mapping(bytes32 => bool) public cancelledOrFinalized; /* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */ /* Note that the maker's nonce at the time of approval **plus one** is stored in the mapping. */ mapping(bytes32 => uint256) private _approvedOrdersByNonce; /* Track per-maker nonces that can be incremented by the maker to cancel orders in bulk. */ // The current nonce for the maker represents the only valid nonce that can be signed by the maker // If a signature was signed with a nonce that's different from the one stored in nonces, it // will fail validation. mapping(address => uint256) public nonces; /* For split fee orders, minimum required protocol maker fee, in basis points. Paid to owner (who can change it). */ uint public minimumMakerProtocolFee = 0; /* For split fee orders, minimum required protocol taker fee, in basis points. Paid to owner (who can change it). */ uint public minimumTakerProtocolFee = 0; /* Recipient of protocol fees. */ address public protocolFeeRecipient; /* Fee method: protocol fee or split fee. */ enum FeeMethod { ProtocolFee, SplitFee } /* Inverse basis point. */ uint public constant INVERSE_BASIS_POINT = 10000; /* An ECDSA signature. */ struct Sig { /* v parameter */ uint8 v; /* r parameter */ bytes32 r; /* s parameter */ bytes32 s; } /* An order on the exchange. */ struct Order { /* Exchange address, intended as a versioning mechanism. */ address exchange; /* Order maker address. */ address maker; /* Order taker address, if specified. */ address taker; /* Maker relayer fee of the order, unused for taker order. */ uint makerRelayerFee; /* Taker relayer fee of the order, or maximum taker fee for a taker order. */ uint takerRelayerFee; /* Maker protocol fee of the order, unused for taker order. */ uint makerProtocolFee; /* Taker protocol fee of the order, or maximum taker fee for a taker order. */ uint takerProtocolFee; /* Order fee recipient or zero address for taker order. */ address feeRecipient; /* Fee method (protocol token or split fee). */ FeeMethod feeMethod; /* Side (buy/sell). */ SaleKindInterface.Side side; /* Kind of sale. */ SaleKindInterface.SaleKind saleKind; /* Target. */ address target; /* HowToCall. */ AuthenticatedProxy.HowToCall howToCall; /* Calldata. */ bytes calldata; /* Calldata replacement pattern, or an empty byte array for no replacement. */ bytes replacementPattern; /* Static call target, zero-address for no static call. */ address staticTarget; /* Static call extra data. */ bytes staticExtradata; /* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */ address paymentToken; /* Base price of the order (in paymentTokens). */ uint basePrice; /* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */ uint extra; /* Listing timestamp. */ uint listingTime; /* Expiration timestamp - 0 for no expiry. */ uint expirationTime; /* Order salt, used to prevent duplicate hashes. */ uint salt; /* NOTE: uint nonce is an additional component of the order but is read from storage */ } event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, uint makerProtocolFee, uint takerProtocolFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target); event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired); event OrderCancelled (bytes32 indexed hash); event OrdersMatched (bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint price, bytes32 indexed metadata); event NonceIncremented (address indexed maker, uint newNonce); constructor () public { require(keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") == _EIP_712_DOMAIN_TYPEHASH); require(keccak256(bytes(name)) == _NAME_HASH); require(keccak256(bytes(version)) == _VERSION_HASH); require(keccak256("Order(address exchange,address maker,address taker,uint256 makerRelayerFee,uint256 takerRelayerFee,uint256 makerProtocolFee,uint256 takerProtocolFee,address feeRecipient,uint8 feeMethod,uint8 side,uint8 saleKind,address target,uint8 howToCall,bytes calldata,bytes replacementPattern,address staticTarget,bytes staticExtradata,address paymentToken,uint256 basePrice,uint256 extra,uint256 listingTime,uint256 expirationTime,uint256 salt,uint256 nonce)") == _ORDER_TYPEHASH); } /** * @dev Derive the domain separator for EIP-712 signatures. * @return The domain separator. */ function _deriveDomainSeparator() private view returns (bytes32) { return keccak256( abi.encode( _EIP_712_DOMAIN_TYPEHASH, // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") _NAME_HASH, // keccak256("StarBlock Exchange Contract") _VERSION_HASH, // keccak256(bytes("1.0")) _CHAIN_ID, // NOTE: this is fixed, need to use solidity 0.5+ or make external call to support! address(this) ) ); } /** * Increment a particular maker's nonce, thereby invalidating all orders that were not signed * with the original nonce. */ function incrementNonce() external { uint newNonce = ++nonces[msg.sender]; emit NonceIncremented(msg.sender, newNonce); } function withdrawMoney() external onlyOwner reentrancyGuard { msg.sender.transfer(address(this).balance); } /** * @dev Change the minimum maker fee paid to the protocol (owner only) * @param newMinimumMakerProtocolFee New fee to set in basis points */ function changeMinimumMakerProtocolFee(uint newMinimumMakerProtocolFee) public onlyOwner { minimumMakerProtocolFee = newMinimumMakerProtocolFee; } /** * @dev Change the minimum taker fee paid to the protocol (owner only) * @param newMinimumTakerProtocolFee New fee to set in basis points */ function changeMinimumTakerProtocolFee(uint newMinimumTakerProtocolFee) public onlyOwner { minimumTakerProtocolFee = newMinimumTakerProtocolFee; } /** * @dev Change the protocol fee recipient (owner only) * @param newProtocolFeeRecipient New protocol fee recipient address */ function changeProtocolFeeRecipient(address newProtocolFeeRecipient) public onlyOwner { protocolFeeRecipient = newProtocolFeeRecipient; } /** * @dev Change exchangeToken (owner only) * @param newExchangeToken New exchangeToken */ function changeExchangeToken(ERC20 newExchangeToken) public onlyOwner { exchangeToken = newExchangeToken; } /** * @dev Transfer tokens * @param token Token to transfer * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function transferTokens(address token, address from, address to, uint amount) internal { if (amount > 0) { require(tokenTransferProxy.transferFrom(token, from, to, amount)); } } /** * @dev Charge a fee in protocol tokens * @param from Address to charge fees * @param to Address to receive fees * @param amount Amount of protocol tokens to charge */ function chargeProtocolFee(address from, address to, uint amount) internal { transferTokens(exchangeToken, from, to, amount); } /** * @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call) * @param target Contract to call * @param calldata Calldata (appended to extradata) * @param extradata Base data for STATICCALL (probably function selector and argument encoding) * @return The result of the call (success or failure) */ function staticCall(address target, bytes memory calldata, bytes memory extradata) public view returns (bool result) { bytes memory combined = new bytes(calldata.length + extradata.length); uint index; assembly { index := add(combined, 0x20) } index = ArrayUtils.unsafeWriteBytes(index, extradata); ArrayUtils.unsafeWriteBytes(index, calldata); assembly { result := staticcall(gas, target, add(combined, 0x20), mload(combined), mload(0x40), 0) } return result; } /** * @dev Hash an order, returning the canonical EIP-712 order hash without the domain separator * @param order Order to hash * @param nonce maker nonce to hash * @return Hash of order */ function hashOrder(Order memory order, uint nonce) internal pure returns (bytes32 hash) { /* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */ uint size = 800; bytes memory array = new bytes(size); uint index; assembly { index := add(array, 0x20) } index = ArrayUtils.unsafeWriteBytes32(index, _ORDER_TYPEHASH); index = ArrayUtils.unsafeWriteAddressWord(index, order.exchange); index = ArrayUtils.unsafeWriteAddressWord(index, order.maker); index = ArrayUtils.unsafeWriteAddressWord(index, order.taker); index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee); index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee); index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee); index = ArrayUtils.unsafeWriteAddressWord(index, order.feeRecipient); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.feeMethod)); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.side)); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.saleKind)); index = ArrayUtils.unsafeWriteAddressWord(index, order.target); index = ArrayUtils.unsafeWriteUint8Word(index, uint8(order.howToCall)); index = ArrayUtils.unsafeWriteBytes32(index, keccak256(order.calldata)); index = ArrayUtils.unsafeWriteBytes32(index, keccak256(order.replacementPattern)); index = ArrayUtils.unsafeWriteAddressWord(index, order.staticTarget); index = ArrayUtils.unsafeWriteBytes32(index, keccak256(order.staticExtradata)); index = ArrayUtils.unsafeWriteAddressWord(index, order.paymentToken); index = ArrayUtils.unsafeWriteUint(index, order.basePrice); index = ArrayUtils.unsafeWriteUint(index, order.extra); index = ArrayUtils.unsafeWriteUint(index, order.listingTime); index = ArrayUtils.unsafeWriteUint(index, order.expirationTime); index = ArrayUtils.unsafeWriteUint(index, order.salt); index = ArrayUtils.unsafeWriteUint(index, nonce); assembly { hash := keccak256(add(array, 0x20), size) } return hash; } /** * @dev Hash an order, returning the hash that a client must sign via EIP-712 including the message prefix * @param order Order to hash * @param nonce Nonce to hash * @return Hash of message prefix and order hash per Ethereum format */ function hashToSign(Order memory order, uint nonce) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashOrder(order, nonce)) ); } /** * @dev Assert an order is valid and return its hash * @param order Order to validate * @param nonce Nonce to validate * @param sig ECDSA signature */ function requireValidOrder(Order memory order, Sig memory sig, uint nonce) internal view returns (bytes32) { bytes32 hash = hashToSign(order, nonce); require(validateOrder(hash, order, sig)); return hash; } /** * @dev Validate order parameters (does *not* check signature validity) * @param order Order to validate */ function validateOrderParameters(Order memory order) internal view returns (bool) { /* Order must be targeted at this protocol version (this Exchange contract). */ if (order.exchange != address(this)) { return false; } /* Order must have a maker. */ if (order.maker == address(0)) { return false; } /* Order must possess valid sale kind parameter combination. */ if (!SaleKindInterface.validateParameters(order.saleKind, order.expirationTime)) { return false; } /* If using the split fee method, order must have sufficient protocol fees. */ if (order.feeMethod == FeeMethod.SplitFee && (order.makerProtocolFee < minimumMakerProtocolFee || order.takerProtocolFee < minimumTakerProtocolFee)) { return false; } return true; } /** * @dev Validate a provided previously approved / signed order, hash, and signature. * @param hash Order hash (already calculated, passed to avoid recalculation) * @param order Order to validate * @param sig ECDSA signature */ function validateOrder(bytes32 hash, Order memory order, Sig memory sig) internal view returns (bool) { /* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */ /* Order must have valid parameters. */ if (!validateOrderParameters(order)) { return false; } /* Order must have not been canceled or already filled. */ if (cancelledOrFinalized[hash]) { return false; } /* Return true if order has been previously approved with the current nonce */ uint approvedOrderNoncePlusOne = _approvedOrdersByNonce[hash]; if (approvedOrderNoncePlusOne != 0) { return approvedOrderNoncePlusOne == nonces[order.maker] + 1; } /* Prevent signature malleability and non-standard v values. */ if (uint256(sig.s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return false; } if (sig.v != 27 && sig.v != 28) { return false; } /* recover via ECDSA, signed by maker (already verified as non-zero). */ if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) { return true; } /* fallback — attempt EIP-1271 isValidSignature check. */ return _tryContractSignature(order.maker, hash, sig); } function _tryContractSignature(address orderMaker, bytes32 hash, Sig memory sig) internal view returns (bool) { bytes memory isValidSignatureData = abi.encodeWithSelector( _EIP_1271_MAGIC_VALUE, hash, abi.encodePacked(sig.r, sig.s, sig.v) ); bytes4 result; // NOTE: solidity 0.4.x does not support STATICCALL outside of assembly assembly { let success := staticcall( // perform a staticcall gas, // forward all available gas orderMaker, // call the order maker add(isValidSignatureData, 0x20), // calldata offset comes after length mload(isValidSignatureData), // load calldata length 0, // do not use memory for return data 0 // do not use memory for return data ) if iszero(success) { // if the call fails returndatacopy(0, 0, returndatasize) // copy returndata buffer to memory revert(0, returndatasize) // revert + pass through revert data } if eq(returndatasize, 0x20) { // if returndata == 32 (one word) returndatacopy(0, 0, 0x20) // copy return data to memory in scratch space result := mload(0) // load return data from memory to the stack } } return result == _EIP_1271_MAGIC_VALUE; } /** * @dev Determine if an order has been approved. Note that the order may not still * be valid in cases where the maker's nonce has been incremented. * @param hash Hash of the order * @return whether or not the order was approved. */ function approvedOrders(bytes32 hash) public view returns (bool approved) { return _approvedOrdersByNonce[hash] != 0; } /** * @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order * @param order Order to approve * @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks */ function approveOrder(Order memory order, bool orderbookInclusionDesired) internal { /* CHECKS */ /* Assert sender is authorized to approve order. */ require(msg.sender == order.maker); /* Calculate order hash. */ bytes32 hash = hashToSign(order, nonces[order.maker]); /* Assert order has not already been approved. */ require(_approvedOrdersByNonce[hash] == 0); /* EFFECTS */ /* Mark order as approved. */ _approvedOrdersByNonce[hash] = nonces[order.maker] + 1; /* Log approval event. Must be split in two due to Solidity stack size limitations. */ { emit OrderApprovedPartOne(hash, order.exchange, order.maker, order.taker, order.makerRelayerFee, order.takerRelayerFee, order.makerProtocolFee, order.takerProtocolFee, order.feeRecipient, order.feeMethod, order.side, order.saleKind, order.target); } { emit OrderApprovedPartTwo(hash, order.howToCall, order.calldata, order.replacementPattern, order.staticTarget, order.staticExtradata, order.paymentToken, order.basePrice, order.extra, order.listingTime, order.expirationTime, order.salt, orderbookInclusionDesired); } } /** * @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order * @param order Order to cancel * @param nonce Nonce to cancel * @param sig ECDSA signature */ function cancelOrder(Order memory order, Sig memory sig, uint nonce) internal { /* CHECKS */ /* Calculate order hash. */ bytes32 hash = requireValidOrder(order, sig, nonce); /* Assert sender is authorized to cancel order. */ require(msg.sender == order.maker); /* EFFECTS */ /* Mark order as cancelled, preventing it from being matched. */ cancelledOrFinalized[hash] = true; /* Log cancel event. */ emit OrderCancelled(hash); } /** * @dev Calculate the current price of an order (convenience function) * @param order Order to calculate the price of * @return The current price of the order */ function calculateCurrentPrice (Order memory order) internal view returns (uint) { return SaleKindInterface.calculateFinalPrice(order.side, order.saleKind, order.basePrice, order.extra, order.listingTime, order.expirationTime); } /** * @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail) * @param buy Buy-side order * @param sell Sell-side order * @return Match price */ function calculateMatchPrice(Order memory buy, Order memory sell) view internal returns (uint) { /* Calculate sell price. */ uint sellPrice = SaleKindInterface.calculateFinalPrice(sell.side, sell.saleKind, sell.basePrice, sell.extra, sell.listingTime, sell.expirationTime); /* Calculate buy price. */ uint buyPrice = SaleKindInterface.calculateFinalPrice(buy.side, buy.saleKind, buy.basePrice, buy.extra, buy.listingTime, buy.expirationTime); /* Require price cross. */ require(buyPrice >= sellPrice); /* Maker/taker priority. */ return sell.feeRecipient != address(0) ? sellPrice : buyPrice; } /** * @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer) * @param buy Buy-side order * @param sell Sell-side order */ function executeFundsTransfer(Order memory buy, Order memory sell) internal returns (uint) { /* Only payable in the special case of unwrapped Ether. */ if (sell.paymentToken != address(0)) { require(msg.value == 0); } /* Calculate match price. */ uint price = calculateMatchPrice(buy, sell); /* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */ if (price > 0 && sell.paymentToken != address(0)) { transferTokens(sell.paymentToken, buy.maker, sell.maker, price); } /* Amount that will be received by seller (for Ether). */ uint receiveAmount = price; /* Amount that must be sent by buyer (for Ether). */ uint requiredAmount = price; /* Determine maker/taker and charge fees accordingly. */ if (sell.feeRecipient != address(0)) { /* Sell-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* Assert taker fee is less than or equal to maximum fee specified by buyer. */ require(sell.takerProtocolFee <= buy.takerProtocolFee); /* Maker fees are deducted from the token amount that the maker receives. Taker fees are extra tokens that must be paid by the taker. */ if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); } else { transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); } else { transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); } else { transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); } else { transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } else { /* Charge maker fee to seller. */ chargeProtocolFee(sell.maker, sell.feeRecipient, sell.makerRelayerFee); /* Charge taker fee to buyer. */ chargeProtocolFee(buy.maker, sell.feeRecipient, sell.takerRelayerFee); } } else { /* Buy-side order is maker. */ /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerRelayerFee <= sell.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { /* The Exchange does not escrow Ether, so direct Ether can only be used to with sell-side maker / buy-side taker orders. */ require(sell.paymentToken != address(0)); /* Assert taker fee is less than or equal to maximum fee specified by seller. */ require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } else { /* Charge maker fee to buyer. */ chargeProtocolFee(buy.maker, buy.feeRecipient, buy.makerRelayerFee); /* Charge taker fee to seller. */ chargeProtocolFee(sell.maker, buy.feeRecipient, buy.takerRelayerFee); } } if (sell.paymentToken == address(0)) { /* Special-case Ether, order must be matched by buyer. */ require(msg.value >= requiredAmount); sell.maker.transfer(receiveAmount); /* Allow overshoot for variable-price auctions, refund difference. */ uint diff = SafeMath.sub(msg.value, requiredAmount); if (diff > 0) { buy.maker.transfer(diff); } } /* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */ return price; } /** * @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldata or perform static calls) * @param buy Buy-side order * @param sell Sell-side order * @return Whether or not the two orders can be matched */ function ordersCanMatch(Order memory buy, Order memory sell) internal view returns (bool) { return ( /* Must be opposite-side. */ (buy.side == SaleKindInterface.Side.Buy && sell.side == SaleKindInterface.Side.Sell) && /* Must use same fee method. */ (buy.feeMethod == sell.feeMethod) && /* Must use same payment token. */ (buy.paymentToken == sell.paymentToken) && /* Must match maker/taker addresses. */ (sell.taker == address(0) || sell.taker == buy.maker) && (buy.taker == address(0) || buy.taker == sell.maker) && /* One must be maker and the other must be taker (no bool XOR in Solidity). */ ((sell.feeRecipient == address(0) && buy.feeRecipient != address(0)) || (sell.feeRecipient != address(0) && buy.feeRecipient == address(0))) && /* Must match target. */ (buy.target == sell.target) && /* Must match howToCall. */ (buy.howToCall == sell.howToCall) && /* Buy-side order must be settleable. */ SaleKindInterface.canSettleOrder(buy.listingTime, buy.expirationTime) && /* Sell-side order must be settleable. */ SaleKindInterface.canSettleOrder(sell.listingTime, sell.expirationTime) ); } /** * @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock. * @param buy Buy-side order * @param buySig Buy-side order signature * @param sell Sell-side order * @param sellSig Sell-side order signature */ function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata) internal reentrancyGuard { /* CHECKS */ /* Ensure buy order validity and calculate hash if necessary. */ bytes32 buyHash; if (buy.maker == msg.sender) { require(validateOrderParameters(buy)); } else { buyHash = _requireValidOrderWithNonce(buy, buySig); } /* Ensure sell order validity and calculate hash if necessary. */ bytes32 sellHash; if (sell.maker == msg.sender) { require(validateOrderParameters(sell)); } else { sellHash = _requireValidOrderWithNonce(sell, sellSig); } /* Must be matchable. */ require(ordersCanMatch(buy, sell)); /* Target must exist (prevent malicious selfdestructs just prior to order settlement). */ uint size; address target = sell.target; assembly { size := extcodesize(target) } require(size > 0); /* Must match calldata after replacement, if specified. */ if (buy.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buy.calldata, sell.calldata, buy.replacementPattern); } if (sell.replacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sell.calldata, buy.calldata, sell.replacementPattern); } require(ArrayUtils.arrayEq(buy.calldata, sell.calldata)); /* Retrieve delegateProxy contract. */ OwnableDelegateProxy delegateProxy = registry.proxies(sell.maker); /* Proxy must exist. */ require(delegateProxy != address(0)); /* Access the passthrough AuthenticatedProxy. */ AuthenticatedProxy proxy = AuthenticatedProxy(delegateProxy); /* EFFECTS */ /* Mark previously signed or approved orders as finalized. */ if (msg.sender != buy.maker) { cancelledOrFinalized[buyHash] = true; } if (msg.sender != sell.maker && sell.saleKind != SaleKindInterface.SaleKind.CollectionRandomSale) { cancelledOrFinalized[sellHash] = true; } /* INTERACTIONS */ /* change the baseprice based on the qutity. */ if (sell.saleKind == SaleKindInterface.SaleKind.CollectionRandomSale) { uint256 quantity = getQuantity(buy); if (quantity > 1) { sell.basePrice = SafeMath.mul(sell.basePrice, quantity); buy.basePrice = sell.basePrice; } } /* Execute funds transfer and pay fees. */ uint price = executeFundsTransfer(buy, sell); /* Assert implementation. */ require(delegateProxy.implementation() == registry.delegateProxyImplementation()); /* Execute specified call through proxy. */ require(proxy.proxy(sell.target, sell.howToCall, sell.calldata)); /* Static calls are intentionally done after the effectful call so they can check resulting state. */ /* Handle buy-side static call if specified. */ if (buy.staticTarget != address(0)) { require(staticCall(buy.staticTarget, sell.calldata, buy.staticExtradata)); } /* Handle sell-side static call if specified. */ if (sell.staticTarget != address(0)) { require(staticCall(sell.staticTarget, sell.calldata, sell.staticExtradata)); } /* Log match event. */ emit OrdersMatched(buyHash, sellHash, sell.feeRecipient != address(0) ? sell.maker : buy.maker, sell.feeRecipient != address(0) ? buy.maker : sell.maker, price, metadata); } function _requireValidOrderWithNonce(Order memory order, Sig memory sig) internal view returns (bytes32) { return requireValidOrder(order, sig, nonces[order.maker]); } function getQuantity(Order memory buy) internal pure returns (uint256) { bytes memory quantityBytes = new bytes(2); uint index = SafeMath.sub(buy.calldata.length, 2); uint lastIndex = SafeMath.sub(buy.calldata.length, 1); quantityBytes[0] = buy.calldata[index]; quantityBytes[1] = buy.calldata[lastIndex]; uint256 quantity = bytesToUint(quantityBytes); return quantity; } function bytesToUint(bytes memory b) internal pure returns (uint256) { uint256 number; for(uint i = 0; i< b.length; i++) { uint index = SafeMath.add(i, 1); uint length = SafeMath.sub(b.length, index); uint offset = 2**SafeMath.mul(8, length); uint offsetCount = SafeMath.mul(uint8(b[i]), offset); number = SafeMath.add(number, offsetCount); } return number; } } contract Exchange is ExchangeCore { /** * @dev Call guardedArrayReplace - library function exposed for testing. */ function guardedArrayReplace(bytes array, bytes desired, bytes mask) public pure returns (bytes) { ArrayUtils.guardedArrayReplace(array, desired, mask); return array; } /** * @dev Call calculateFinalPrice - library function exposed for testing. */ function calculateFinalPrice(SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime) public view returns (uint) { return SaleKindInterface.calculateFinalPrice(side, saleKind, basePrice, extra, listingTime, expirationTime); } /** * @dev Call hashOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashOrder_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (bytes32) { return hashOrder( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), nonces[addrs[1]] ); } /** * @dev Call hashToSign - Solidity ABI encoding limitation workaround, hopefully temporary. */ function hashToSign_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (bytes32) { return hashToSign( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), nonces[addrs[1]] ); } /** * @dev Call validateOrderParameters - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrderParameters_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) view public returns (bool) { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return validateOrderParameters( order ); } /** * @dev Call validateOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function validateOrder_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s) view public returns (bool) { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return validateOrder( hashToSign(order, nonces[order.maker]), order, Sig(v, r, s) ); } /** * @dev Call approveOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function approveOrder_ ( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, bool orderbookInclusionDesired) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return approveOrder(order, orderbookInclusionDesired); } /** * @dev Call cancelOrder - Solidity ABI encoding limitation workaround, hopefully temporary. */ function cancelOrder_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return cancelOrder( order, Sig(v, r, s), nonces[order.maker] ); } /** * @dev Call cancelOrder, supplying a specific nonce — enables cancelling orders that were signed with nonces greater than the current nonce. */ function cancelOrderWithNonce_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata, uint8 v, bytes32 r, bytes32 s, uint nonce) public { Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); return cancelOrder( order, Sig(v, r, s), nonce ); } /** * @dev Call calculateCurrentPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateCurrentPrice_( address[7] addrs, uint[9] uints, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, AuthenticatedProxy.HowToCall howToCall, bytes calldata, bytes replacementPattern, bytes staticExtradata) public view returns (uint) { return calculateCurrentPrice( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, calldata, replacementPattern, addrs[5], staticExtradata, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]) ); } /** * @dev Call ordersCanMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function ordersCanMatch_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell) public view returns (bool) { Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]); return ordersCanMatch( buy, sell ); } /** * @dev Return whether or not two orders' calldata specifications can match * @param buyCalldata Buy-side order calldata * @param buyReplacementPattern Buy-side order calldata replacement mask * @param sellCalldata Sell-side order calldata * @param sellReplacementPattern Sell-side order calldata replacement mask * @return Whether the orders' calldata can be matched */ function orderCalldataCanMatch(bytes buyCalldata, bytes buyReplacementPattern, bytes sellCalldata, bytes sellReplacementPattern) public pure returns (bool) { if (buyReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(buyCalldata, sellCalldata, buyReplacementPattern); } if (sellReplacementPattern.length > 0) { ArrayUtils.guardedArrayReplace(sellCalldata, buyCalldata, sellReplacementPattern); } return ArrayUtils.arrayEq(buyCalldata, sellCalldata); } /** * @dev Call calculateMatchPrice - Solidity ABI encoding limitation workaround, hopefully temporary. */ function calculateMatchPrice_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell) public view returns (uint) { Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]); Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]); return calculateMatchPrice( buy, sell ); } /** * @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary. */ function atomicMatch_( address[14] addrs, uint[18] uints, uint8[8] feeMethodsSidesKindsHowToCalls, bytes calldataBuy, bytes calldataSell, bytes replacementPatternBuy, bytes replacementPatternSell, bytes staticExtradataBuy, bytes staticExtradataSell, uint8[2] vs, bytes32[5] rssMetadata) public payable callerIsUser { return atomicMatch( Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, ERC20(addrs[6]), uints[4], uints[5], uints[6], uints[7], uints[8]), Sig(vs[0], rssMetadata[0], rssMetadata[1]), Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, ERC20(addrs[13]), uints[13], uints[14], uints[15], uints[16], uints[17]), Sig(vs[1], rssMetadata[2], rssMetadata[3]), rssMetadata[4] ); } modifier callerIsUser() { require(tx.origin == msg.sender, "The caller is another contract"); _; } } contract StarBlockExchange is Exchange { string public constant codename = "Bulk Smash"; /** * @dev Initialize a WyvernExchange instance * @param registryAddress Address of the registry instance which this Exchange instance will use * @param tokenAddress Address of the token used for protocol fees */ constructor (ProxyRegistry registryAddress, TokenTransferProxy tokenTransferProxyAddress, ERC20 tokenAddress, address protocolFeeAddress) public { registry = registryAddress; tokenTransferProxy = tokenTransferProxyAddress; exchangeToken = tokenAddress; protocolFeeRecipient = protocolFeeAddress; owner = msg.sender; } } library SaleKindInterface { /** * Side: buy or sell. */ enum Side { Buy, Sell } /** * Currently supported kinds of sale: fixed price, Dutch auction. * English auctions cannot be supported without stronger escrow guarantees. * Future interesting options: Vickrey auction, nonlinear Dutch auctions. */ enum SaleKind { FixedPrice, DutchAuction, CollectionRandomSale } /** * @dev Check whether the parameters of a sale are valid * @param saleKind Kind of sale * @param expirationTime Order expiration time * @return Whether the parameters were valid */ function validateParameters(SaleKind saleKind, uint expirationTime) pure internal returns (bool) { /* Auctions must have a set expiration date. */ if (expirationTime > 0 ) { return true; }else { if (saleKind == SaleKind.FixedPrice || saleKind == SaleKind.CollectionRandomSale) { return true; } } return false; } /** * @dev Return whether or not an order can be settled * @dev Precondition: parameters have passed validateParameters * @param listingTime Order listing time * @param expirationTime Order expiration time */ function canSettleOrder(uint listingTime, uint expirationTime) view internal returns (bool) { return (listingTime < now) && (expirationTime == 0 || now < expirationTime); } /** * @dev Calculate the settlement price of an order * @dev Precondition: parameters have passed validateParameters. * @param side Order side * @param saleKind Method of sale * @param basePrice Order base price * @param extra Order extra price data * @param listingTime Order listing time * @param expirationTime Order expiration time */ function calculateFinalPrice(Side side, SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime) view internal returns (uint finalPrice) { if (saleKind == SaleKind.FixedPrice || saleKind == SaleKind.CollectionRandomSale) { return basePrice; } else if (saleKind == SaleKind.DutchAuction) { uint diff = SafeMath.div(SafeMath.mul(extra, SafeMath.sub(now, listingTime)), SafeMath.sub(expirationTime, listingTime)); if (side == Side.Sell) { /* Sell-side - start price: basePrice. End price: basePrice - extra. */ return SafeMath.sub(basePrice, diff); } else { /* Buy-side - start price: basePrice. End price: basePrice + extra. */ return SafeMath.add(basePrice, diff); } } } } contract ProxyRegistry is Ownable { /* DelegateProxy implementation contract. Must be initialized. */ address public delegateProxyImplementation; /* Authenticated proxies by user. */ mapping(address => OwnableDelegateProxy) public proxies; /* Contracts pending access. */ mapping(address => uint) public pending; /* Contracts allowed to call those proxies. */ mapping(address => bool) public contracts; /* Delay period for adding an authenticated contract. This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO), a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have plenty of time to notice and transfer their assets. */ uint public DELAY_PERIOD = 2 weeks; /** * Start the process to enable access for specified contract. Subject to delay period. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function startGrantAuthentication (address addr) public onlyOwner { require(!contracts[addr] && pending[addr] == 0); pending[addr] = now; } /** * End the process to nable access for specified contract after delay period has passed. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function endGrantAuthentication (address addr) public onlyOwner { require(!contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < now)); pending[addr] = 0; contracts[addr] = true; } /** * Revoke access for specified contract. Can be done instantly. * * @dev ProxyRegistry owner only * @param addr Address of which to revoke permissions */ function revokeAuthentication (address addr) public onlyOwner { contracts[addr] = false; } /** * Register a proxy contract with this registry * * @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy * @return New AuthenticatedProxy contract */ function registerProxy() public returns (OwnableDelegateProxy proxy) { require(proxies[msg.sender] == address(0)); proxy = new OwnableDelegateProxy(msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this))); proxies[msg.sender] = proxy; return proxy; } } contract TokenTransferProxy { /* Authentication registry. */ ProxyRegistry public registry; /** * Call ERC20 `transferFrom` * * @dev Authenticated contract only * @param token ERC20 token address * @param from From address * @param to To address * @param amount Transfer amount */ function transferFrom(address token, address from, address to, uint amount) public returns (bool) { require(registry.contracts(msg.sender)); return ERC20(token).transferFrom(from, to, amount); } } contract OwnedUpgradeabilityStorage { // Current implementation address internal _implementation; // Owner of the contract address private _upgradeabilityOwner; /** * @dev Tells the address of the owner * @return the address of the owner */ function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; } /** * @dev Sets the address of the owner */ function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal { _upgradeabilityOwner = newUpgradeabilityOwner; } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address) { return _implementation; } /** * @dev Tells the proxy type (EIP 897) * @return Proxy type, 2 for forwarding proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return 2; } } contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage { /* Whether initialized. */ bool initialized = false; /* Address which owns this proxy. */ address public user; /* Associated registry with contract authentication information. */ ProxyRegistry public registry; /* Whether access has been revoked. */ bool public revoked; /* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */ enum HowToCall { Call, DelegateCall } /* Event fired when the proxy access is revoked or unrevoked. */ event Revoked(bool revoked); /** * Initialize an AuthenticatedProxy * * @param addrUser Address of user on whose behalf this proxy will act * @param addrRegistry Address of ProxyRegistry contract which will manage this proxy */ function initialize (address addrUser, ProxyRegistry addrRegistry) public { require(!initialized); initialized = true; user = addrUser; registry = addrRegistry; } /** * Set the revoked flag (allows a user to revoke ProxyRegistry access) * * @dev Can be called by the user only * @param revoke Whether or not to revoke access */ function setRevoke(bool revoke) public { require(msg.sender == user); revoked = revoke; emit Revoked(revoke); } /** * Execute a message call from the proxy contract * * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access * @param dest Address to which the call will be sent * @param howToCall Which kind of call to make * @param calldata Calldata to send * @return Result of the call (success or failure) */ function proxy(address dest, HowToCall howToCall, bytes calldata) public returns (bool result) { require(msg.sender == user || (!revoked && registry.contracts(msg.sender))); if (howToCall == HowToCall.Call) { result = dest.call(calldata); } else if (howToCall == HowToCall.DelegateCall) { result = dest.delegatecall(calldata); } return result; } /** * Execute a message call and assert success * * @dev Same functionality as `proxy`, just asserts the return value * @param dest Address to which the call will be sent * @param howToCall What kind of call to make * @param calldata Calldata to send */ function proxyAssert(address dest, HowToCall howToCall, bytes calldata) public { require(proxy(dest, howToCall, calldata)); } } contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); /** * @dev Tells the type of proxy (EIP 897) * @return Type of proxy, 2 for upgradeable proxy */ function proxyType() public pure returns (uint256 proxyTypeId); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () payable public { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); /** * @dev Upgrades the implementation address * @param implementation representing the address of the new implementation to be set */ function _upgradeTo(address implementation) internal { require(_implementation != implementation); _implementation = implementation; emit Upgraded(implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes data) payable public onlyProxyOwner { upgradeTo(implementation); require(address(this).delegatecall(data)); } } contract OwnableDelegateProxy is OwnedUpgradeabilityProxy { constructor(address owner, address initialImplementation, bytes calldata) public { setUpgradeabilityOwner(owner); _upgradeTo(initialImplementation); require(initialImplementation.delegatecall(calldata)); } }
Calculate sell price. / Calculate buy price. / Require price cross. / Maker/taker priority. / Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer) buy Buy-side order sell Sell-side order/
{ function cancelOrder(Order memory order, Sig memory sig, uint nonce) internal } function calculateCurrentPrice (Order memory order) internal view returns (uint) } function calculateMatchPrice(Order memory buy, Order memory sell) view internal returns (uint) } function executeFundsTransfer(Order memory buy, Order memory sell) internal returns (uint) if (sell.paymentToken != address(0)) { require(msg.value == 0); } uint price = calculateMatchPrice(buy, sell); if (price > 0 && sell.paymentToken != address(0)) { transferTokens(sell.paymentToken, buy.maker, sell.maker, price); } uint receiveAmount = price; uint requiredAmount = price; if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } } else { if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } } else { if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } } else { if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } } else { } else { chargeProtocolFee(sell.maker, sell.feeRecipient, sell.makerRelayerFee); chargeProtocolFee(buy.maker, sell.feeRecipient, sell.takerRelayerFee); } else { require(buy.takerRelayerFee <= sell.takerRelayerFee); if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeRecipient != address(0)) { require(sell.takerRelayerFee <= buy.takerRelayerFee); if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.takerProtocolFee <= buy.takerProtocolFee); if (sell.makerRelayerFee > 0) { uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee); sell.feeRecipient.transfer(makerRelayerFee); transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee); } } if (sell.takerRelayerFee > 0) { uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee); sell.feeRecipient.transfer(takerRelayerFee); transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee); } } if (sell.makerProtocolFee > 0) { uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee); protocolFeeRecipient.transfer(makerProtocolFee); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee); } } if (sell.takerProtocolFee > 0) { uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT); if (sell.paymentToken == address(0)) { requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee); protocolFeeRecipient.transfer(takerProtocolFee); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee); } } } if (sell.feeMethod == FeeMethod.SplitFee) { require(sell.paymentToken != address(0)); require(buy.takerProtocolFee <= sell.takerProtocolFee); if (buy.makerRelayerFee > 0) { makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee); } if (buy.takerRelayerFee > 0) { takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee); } if (buy.makerProtocolFee > 0) { makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee); } if (buy.takerProtocolFee > 0) { takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT); transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee); } } } } else { chargeProtocolFee(buy.maker, buy.feeRecipient, buy.makerRelayerFee); chargeProtocolFee(sell.maker, buy.feeRecipient, buy.takerRelayerFee); if (sell.paymentToken == address(0)) { require(msg.value >= requiredAmount); sell.maker.transfer(receiveAmount); uint diff = SafeMath.sub(msg.value, requiredAmount); if (diff > 0) { buy.maker.transfer(diff); } } return price; if (sell.paymentToken == address(0)) { require(msg.value >= requiredAmount); sell.maker.transfer(receiveAmount); uint diff = SafeMath.sub(msg.value, requiredAmount); if (diff > 0) { buy.maker.transfer(diff); } } return price; }
251,937
pragma solidity ^0.5.0; contract ResolverBase { bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_META_ID; } function isAuthorised(bytes32 node) internal view returns(bool); modifier authorised(bytes32 node) { require(isAuthorised(node)); _; } function bytesToAddress(bytes memory b) internal pure returns(address payable a) { require(b.length == 20); assembly { a := div(mload(add(b, 32)), exp(256, 12)) } } function addressToBytes(address a) internal pure returns(bytes memory b) { b = new bytes(20); assembly { mstore(add(b, 32), mul(a, exp(256, 12))) } } } pragma solidity >=0.5.0; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); // Logged when an operator is added or removed. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address owner, address operator) external view returns (bool); } /** * The ENS registry contract. */ contract ENSRegistry is ENS { struct Record { address owner; address resolver; uint64 ttl; } mapping (bytes32 => Record) records; mapping (address => mapping(address => bool)) operators; // Permits modifications only by the owner of the specified node. modifier authorised(bytes32 node) { address owner = records[node].owner; require(owner == msg.sender || operators[owner][msg.sender]); _; } /** * @dev Constructs a new ENS registrar. */ constructor() public { records[0x0].owner = msg.sender; } /** * @dev Sets the record for a node. * @param node The node to update. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external { setOwner(node, owner); _setResolverAndTTL(node, resolver, ttl); } /** * @dev Sets the record for a subnode. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. * @param resolver The address of the resolver. * @param ttl The TTL in seconds. */ function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external { bytes32 subnode = setSubnodeOwner(node, label, owner); _setResolverAndTTL(subnode, resolver, ttl); } /** * @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) public authorised(node) { _setOwner(node, owner); emit Transfer(node, owner); } /** * @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public authorised(node) returns(bytes32) { bytes32 subnode = keccak256(abi.encodePacked(node, label)); _setOwner(subnode, owner); emit NewOwner(node, label, owner); return subnode; } /** * @dev Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) public authorised(node) { emit NewResolver(node, resolver); records[node].resolver = resolver; } /** * @dev Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) public authorised(node) { emit NewTTL(node, ttl); records[node].ttl = ttl; } /** * @dev Enable or disable approval for a third party ("operator") to manage * all of `msg.sender`'s ENS records. Emits the ApprovalForAll event. * @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 { operators[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev Returns the address that owns the specified node. * @param node The specified node. * @return address of the owner. */ function owner(bytes32 node) public view returns (address) { address addr = records[node].owner; if (addr == address(this)) { return address(0x0); } return addr; } /** * @dev Returns the address of the resolver for the specified node. * @param node The specified node. * @return address of the resolver. */ function resolver(bytes32 node) public view returns (address) { return records[node].resolver; } /** * @dev Returns the TTL of a node, and any records associated with it. * @param node The specified node. * @return ttl of the node. */ function ttl(bytes32 node) public view returns (uint64) { return records[node].ttl; } /** * @dev Returns whether a record has been imported to the registry. * @param node The specified node. * @return Bool if record exists */ function recordExists(bytes32 node) public view returns (bool) { return records[node].owner != address(0x0); } /** * @dev Query if an address is an authorized operator for another address. * @param owner The address that owns the records. * @param operator The address that acts on behalf of the owner. * @return True if `operator` is an approved operator for `owner`, false otherwise. */ function isApprovedForAll(address owner, address operator) external view returns (bool) { return operators[owner][operator]; } function _setOwner(bytes32 node, address owner) internal { records[node].owner = owner; } function _setResolverAndTTL(bytes32 node, address resolver, uint64 ttl) internal { if(resolver != records[node].resolver) { records[node].resolver = resolver; emit NewResolver(node, resolver); } if(ttl != records[node].ttl) { records[node].ttl = ttl; emit NewTTL(node, ttl); } } } pragma solidity ^0.5.0; contract ABIResolver is ResolverBase { bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56; event ABIChanged(bytes32 indexed node, uint256 indexed contentType); mapping(bytes32=>mapping(uint256=>bytes)) abis; /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); abis[node][contentType] = data; emit ABIChanged(node, contentType); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) { mapping(uint256=>bytes) storage abiset = abis[node]; for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) { return (contentType, abiset[contentType]); } } return (0, bytes("")); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract AddrResolver is ResolverBase { bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant private ADDRESS_INTERFACE_ID = 0xf1cb7e06; uint constant private COIN_TYPE_ETH = 60; event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); mapping(bytes32=>mapping(uint=>bytes)) _addresses; /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param a The address to set. */ function setAddr(bytes32 node, address a) external authorised(node) { setAddr(node, COIN_TYPE_ETH, addressToBytes(a)); } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address payable) { bytes memory a = addr(node, COIN_TYPE_ETH); if(a.length == 0) { return address(0); } return bytesToAddress(a); } function setAddr(bytes32 node, uint coinType, bytes memory a) public authorised(node) { emit AddressChanged(node, coinType, a); if(coinType == COIN_TYPE_ETH) { emit AddrChanged(node, bytesToAddress(a)); } _addresses[node][coinType] = a; } function addr(bytes32 node, uint coinType) public view returns(bytes memory) { return _addresses[node][coinType]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == ADDRESS_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract ContentHashResolver is ResolverBase { bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1; event ContenthashChanged(bytes32 indexed node, bytes hash); mapping(bytes32=>bytes) hashes; /** * Sets the contenthash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The contenthash to set */ function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) { hashes[node] = hash; emit ContenthashChanged(node, hash); } /** * Returns the contenthash associated with an ENS node. * @param node The ENS node to query. * @return The associated contenthash. */ function contenthash(bytes32 node) external view returns (bytes memory) { return hashes[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity >0.4.23; library BytesUtils { /* * @dev Returns the keccak-256 hash of a byte range. * @param self The byte string to hash. * @param offset The position to start hashing at. * @param len The number of bytes to hash. * @return The hash of the byte range. */ function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) { require(offset + len <= self.length); assembly { ret := keccak256(add(add(self, 32), offset), len) } } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two bytes are equal. * @param self The first bytes to compare. * @param other The second bytes to compare. * @return The result of the comparison. */ function compare(bytes memory self, bytes memory other) internal pure returns (int) { return compare(self, 0, self.length, other, 0, other.length); } /* * @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 bytes are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first bytes to compare. * @param offset The offset of self. * @param len The length of self. * @param other The second bytes to compare. * @param otheroffset The offset of the other string. * @param otherlen The length of the other string. * @return The result of the comparison. */ function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) { uint shortest = len; if (otherlen < len) shortest = otherlen; uint selfptr; uint otherptr; assembly { selfptr := add(self, add(offset, 32)) otherptr := add(other, add(otheroffset, 32)) } 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; if (shortest > 32) { mask = uint256(- 1); // aka 0xffffff.... } else { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(len) - int(otherlen); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @param len The number of bytes to compare * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) { return keccak(self, offset, len) == keccak(other, otherOffset, len); } /* * @dev Returns true if the two byte ranges are equal with offsets. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @param otherOffset The offset into the second byte range. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) { return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset); } /* * @dev Compares a range of 'self' to all of 'other' and returns True iff * they are equal. * @param self The first byte range to compare. * @param offset The offset into the first byte range. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) { return self.length >= offset + other.length && equals(self, offset, other, 0, other.length); } /* * @dev Returns true if the two byte ranges are equal. * @param self The first byte range to compare. * @param other The second byte range to compare. * @return True if the byte ranges are equal, false otherwise. */ function equals(bytes memory self, bytes memory other) internal pure returns(bool) { return self.length == other.length && equals(self, 0, other, 0, self.length); } /* * @dev Returns the 8-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 8 bits of the string, interpreted as an integer. */ function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) { return uint8(self[idx]); } /* * @dev Returns the 16-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 16 bits of the string, interpreted as an integer. */ function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) { require(idx + 2 <= self.length); assembly { ret := and(mload(add(add(self, 2), idx)), 0xFFFF) } } /* * @dev Returns the 32-bit number at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bits of the string, interpreted as an integer. */ function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) { require(idx + 4 <= self.length); assembly { ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) { require(idx + 32 <= self.length); assembly { ret := mload(add(add(self, 32), idx)) } } /* * @dev Returns the 32 byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes * @return The specified 32 bytes of the string. */ function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) { require(idx + 20 <= self.length); assembly { ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000) } } /* * @dev Returns the n byte value at the specified index of self. * @param self The byte string. * @param idx The index into the bytes. * @param len The number of bytes. * @return The specified 32 bytes of the string. */ function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes32 ret) { require(len <= 32); require(idx + len <= self.length); assembly { let mask := not(sub(exp(256, sub(32, len)), 1)) ret := and(mload(add(add(self, 32), idx)), mask) } } function memcpy(uint dest, uint src, uint len) private pure { // 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 Copies a substring into a new byte string. * @param self The byte string to copy from. * @param offset The offset to start copying at. * @param len The number of bytes to copy. */ function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) { require(offset + len <= self.length); bytes memory ret = new bytes(len); uint dest; uint src; assembly { dest := add(ret, 32) src := add(add(self, 32), offset) } memcpy(dest, src, len); return ret; } // Maps characters from 0x30 to 0x7A to their base32 values. // 0xFF represents invalid characters in that range. bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F'; /** * @dev Decodes unpadded base32 data of up to one word in length. * @param self The data to decode. * @param off Offset into the string to start at. * @param len Number of characters to decode. * @return The decoded data, left aligned. */ function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) { require(len <= 52); uint ret = 0; uint8 decoded; for(uint i = 0; i < len; i++) { bytes1 char = self[off + i]; require(char >= 0x30 && char <= 0x7A); decoded = uint8(base32HexTable[uint(uint8(char)) - 0x30]); require(decoded <= 0x20); if(i == len - 1) { break; } ret = (ret << 5) | decoded; } uint bitlen = len * 5; if(len % 8 == 0) { // Multiple of 8 characters, no padding ret = (ret << 5) | decoded; } else if(len % 8 == 2) { // Two extra characters - 1 byte ret = (ret << 3) | (decoded >> 2); bitlen -= 2; } else if(len % 8 == 4) { // Four extra characters - 2 bytes ret = (ret << 1) | (decoded >> 4); bitlen -= 4; } else if(len % 8 == 5) { // Five extra characters - 3 bytes ret = (ret << 4) | (decoded >> 1); bitlen -= 1; } else if(len % 8 == 7) { // Seven extra characters - 4 bytes ret = (ret << 2) | (decoded >> 3); bitlen -= 3; } else { revert(); } return bytes32(ret << (256 - bitlen)); } } pragma solidity >0.4.18; /** * @dev A library for working with mutable byte buffers in Solidity. * * Byte buffers are mutable and expandable, and provide a variety of primitives * for writing to them. At any time you can fetch a bytes object containing the * current contents of the buffer. The bytes object should not be stored between * operations, as it may change due to resizing of the buffer. */ library Buffer { /** * @dev Represents a mutable buffer. Buffers have a current value (buf) and * a capacity. The capacity may be longer than the current value, in * which case it can be extended without the need to allocate more memory. */ struct buffer { bytes buf; uint capacity; } /** * @dev Initializes a buffer with an initial capacity. * @param buf The buffer to initialize. * @param capacity The number of bytes of space to allocate the buffer. * @return The buffer, for chaining. */ function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) { if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(32, add(ptr, capacity))) } return buf; } /** * @dev Initializes a new buffer from an existing bytes object. * Changes to the buffer may mutate the original value. * @param b The bytes object to initialize the buffer with. * @return A new buffer. */ function fromBytes(bytes memory b) internal pure returns(buffer memory) { buffer memory buf; buf.buf = b; buf.capacity = b.length; return buf; } 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) { if (a > b) { return a; } return b; } /** * @dev Sets buffer length to 0. * @param buf The buffer to truncate. * @return The original buffer, for chaining.. */ function truncate(buffer memory buf) internal pure returns (buffer memory) { assembly { let bufptr := mload(buf) mstore(bufptr, 0) } return buf; } /** * @dev Writes a byte string to a buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The start offset to write to. * @param data The data to append. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes memory data, uint len) internal pure returns(buffer memory) { require(len <= data.length); if (off + len > buf.capacity) { resize(buf, max(buf.capacity, len + off) * 2); } uint dest; uint src; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + offset + sizeof(buffer length) dest := add(add(bufptr, 32), off) // Update buffer length if we're extending it if gt(add(len, off), buflen) { mstore(bufptr, add(len, off)) } src := add(data, 32) } // 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)) } return buf; } /** * @dev Appends a byte string to a 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. * @param len The number of bytes to copy. * @return The original buffer, for chaining. */ function append(buffer memory buf, bytes memory data, uint len) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, len); } /** * @dev Appends a byte string to a 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, for chaining. */ function append(buffer memory buf, bytes memory data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, data.length); } /** * @dev Writes a byte to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write the byte at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) { if (off >= buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + sizeof(buffer length) + off let dest := add(add(bufptr, off), 32) mstore8(dest, data) // Update buffer length if we extended it if eq(off, buflen) { mstore(bufptr, add(buflen, 1)) } } return buf; } /** * @dev Appends a byte to 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, for chaining. */ function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) { return writeUint8(buf, buf.buf.length, data); } /** * @dev Writes up to 32 bytes to the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (left-aligned). * @return The original buffer, for chaining. */ function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; // Right-align data data = data >> (8 * (32 - len)); assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + sizeof(buffer length) + off + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } return buf; } /** * @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the * capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @return The original buffer, for chaining. */ function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) { return write(buf, off, bytes32(data), 20); } /** * @dev Appends a bytes20 to 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, for chhaining. */ function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, bytes32(data), 20); } /** * @dev Appends a bytes32 to 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, for chaining. */ function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) { return write(buf, buf.buf.length, data, 32); } /** * @dev Writes an integer to the buffer. Resizes if doing so would exceed * the capacity of the buffer. * @param buf The buffer to append to. * @param off The offset to write at. * @param data The data to append. * @param len The number of bytes to write (right-aligned). * @return The original buffer, for chaining. */ function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) { if (len + off > buf.capacity) { resize(buf, (len + off) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Address = buffer address + off + sizeof(buffer length) + len let dest := add(add(bufptr, off), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length if we extended it if gt(add(off, len), mload(bufptr)) { mstore(bufptr, add(off, len)) } } 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 appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { return writeInt(buf, buf.buf.length, data, len); } } pragma solidity >0.4.23; /** * @dev RRUtils is a library that provides utilities for parsing DNS resource records. */ library RRUtils { using BytesUtils for *; using Buffer for *; /** * @dev Returns the number of bytes in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The length of the DNS name at 'offset', in bytes. */ function nameLength(bytes memory self, uint offset) internal pure returns(uint) { uint idx = offset; while (true) { assert(idx < self.length); uint labelLen = self.readUint8(idx); idx += labelLen + 1; if (labelLen == 0) { break; } } return idx - offset; } /** * @dev Returns a DNS format name at the specified offset of self. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The name. */ function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) { uint len = nameLength(self, offset); return self.substring(offset, len); } /** * @dev Returns the number of labels in the DNS name at 'offset' in 'self'. * @param self The byte array to read a name from. * @param offset The offset to start reading at. * @return The number of labels in the DNS name at 'offset', in bytes. */ function labelCount(bytes memory self, uint offset) internal pure returns(uint) { uint count = 0; while (true) { assert(offset < self.length); uint labelLen = self.readUint8(offset); offset += labelLen + 1; if (labelLen == 0) { break; } count += 1; } return count; } /** * @dev An iterator over resource records. */ struct RRIterator { bytes data; uint offset; uint16 dnstype; uint16 class; uint32 ttl; uint rdataOffset; uint nextOffset; } /** * @dev Begins iterating over resource records. * @param self The byte string to read from. * @param offset The offset to start reading at. * @return An iterator object. */ function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) { ret.data = self; ret.nextOffset = offset; next(ret); } /** * @dev Returns true iff there are more RRs to iterate. * @param iter The iterator to check. * @return True iff the iterator has finished. */ function done(RRIterator memory iter) internal pure returns(bool) { return iter.offset >= iter.data.length; } /** * @dev Moves the iterator to the next resource record. * @param iter The iterator to advance. */ function next(RRIterator memory iter) internal pure { iter.offset = iter.nextOffset; if (iter.offset >= iter.data.length) { return; } // Skip the name uint off = iter.offset + nameLength(iter.data, iter.offset); // Read type, class, and ttl iter.dnstype = iter.data.readUint16(off); off += 2; iter.class = iter.data.readUint16(off); off += 2; iter.ttl = iter.data.readUint32(off); off += 4; // Read the rdata uint rdataLength = iter.data.readUint16(off); off += 2; iter.rdataOffset = off; iter.nextOffset = off + rdataLength; } /** * @dev Returns the name of the current record. * @param iter The iterator. * @return A new bytes object containing the owner name from the RR. */ function name(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset)); } /** * @dev Returns the rdata portion of the current record. * @param iter The iterator. * @return A new bytes object containing the RR's RDATA. */ function rdata(RRIterator memory iter) internal pure returns(bytes memory) { return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset); } /** * @dev Checks if a given RR type exists in a type bitmap. * @param self The byte string to read the type bitmap from. * @param offset The offset to start reading at. * @param rrtype The RR type to check for. * @return True if the type is found in the bitmap, false otherwise. */ function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) { uint8 typeWindow = uint8(rrtype >> 8); uint8 windowByte = uint8((rrtype & 0xff) / 8); uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7))); for (uint off = offset; off < self.length;) { uint8 window = self.readUint8(off); uint8 len = self.readUint8(off + 1); if (typeWindow < window) { // We've gone past our window; it's not here. return false; } else if (typeWindow == window) { // Check this type bitmap if (len * 8 <= windowByte) { // Our type is past the end of the bitmap return false; } return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0; } else { // Skip this type bitmap off += len + 2; } } return false; } function compareNames(bytes memory self, bytes memory other) internal pure returns (int) { if (self.equals(other)) { return 0; } uint off; uint otheroff; uint prevoff; uint otherprevoff; uint counts = labelCount(self, 0); uint othercounts = labelCount(other, 0); // Keep removing labels from the front of the name until both names are equal length while (counts > othercounts) { prevoff = off; off = progress(self, off); counts--; } while (othercounts > counts) { otherprevoff = otheroff; otheroff = progress(other, otheroff); othercounts--; } // Compare the last nonequal labels to each other while (counts > 0 && !self.equals(off, other, otheroff)) { prevoff = off; off = progress(self, off); otherprevoff = otheroff; otheroff = progress(other, otheroff); counts -= 1; } if (off == 0) { return -1; } if(otheroff == 0) { return 1; } return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff)); } function progress(bytes memory body, uint off) internal pure returns(uint) { return off + 1 + body.readUint8(off); } } pragma solidity ^0.5.0; contract DNSResolver is ResolverBase { using RRUtils for *; using BytesUtils for bytes; bytes4 constant private DNS_RECORD_INTERFACE_ID = 0xa8fa5682; bytes4 constant private DNS_ZONE_INTERFACE_ID = 0x5c47637c; // DNSRecordChanged is emitted whenever a given node/name/resource's RRSET is updated. event DNSRecordChanged(bytes32 indexed node, bytes name, uint16 resource, bytes record); // DNSRecordDeleted is emitted whenever a given node/name/resource's RRSET is deleted. event DNSRecordDeleted(bytes32 indexed node, bytes name, uint16 resource); // DNSZoneCleared is emitted whenever a given node's zone information is cleared. event DNSZoneCleared(bytes32 indexed node); // DNSZonehashChanged is emitted whenever a given node's zone hash is updated. event DNSZonehashChanged(bytes32 indexed node, bytes lastzonehash, bytes zonehash); // Zone hashes for the domains. // A zone hash is an EIP-1577 content hash in binary format that should point to a // resource containing a single zonefile. // node => contenthash mapping(bytes32=>bytes) private zonehashes; // Version the mapping for each zone. This allows users who have lost // track of their entries to effectively delete an entire zone by bumping // the version number. // node => version mapping(bytes32=>uint256) private versions; // The records themselves. Stored as binary RRSETs // node => version => name => resource => data mapping(bytes32=>mapping(uint256=>mapping(bytes32=>mapping(uint16=>bytes)))) private records; // Count of number of entries for a given name. Required for DNS resolvers // when resolving wildcards. // node => version => name => number of records mapping(bytes32=>mapping(uint256=>mapping(bytes32=>uint16))) private nameEntriesCount; /** * Set one or more DNS records. Records are supplied in wire-format. * Records with the same node/name/resource must be supplied one after the * other to ensure the data is updated correctly. For example, if the data * was supplied: * a.example.com IN A 1.2.3.4 * a.example.com IN A 5.6.7.8 * www.example.com IN CNAME a.example.com. * then this would store the two A records for a.example.com correctly as a * single RRSET, however if the data was supplied: * a.example.com IN A 1.2.3.4 * www.example.com IN CNAME a.example.com. * a.example.com IN A 5.6.7.8 * then this would store the first A record, the CNAME, then the second A * record which would overwrite the first. * * @param node the namehash of the node for which to set the records * @param data the DNS wire format records to set */ function setDNSRecords(bytes32 node, bytes calldata data) external authorised(node) { uint16 resource = 0; uint256 offset = 0; bytes memory name; bytes memory value; bytes32 nameHash; // Iterate over the data to add the resource records for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) { if (resource == 0) { resource = iter.dnstype; name = iter.name(); nameHash = keccak256(abi.encodePacked(name)); value = bytes(iter.rdata()); } else { bytes memory newName = iter.name(); if (resource != iter.dnstype || !name.equals(newName)) { setDNSRRSet(node, name, resource, data, offset, iter.offset - offset, value.length == 0); resource = iter.dnstype; offset = iter.offset; name = newName; nameHash = keccak256(name); value = bytes(iter.rdata()); } } } if (name.length > 0) { setDNSRRSet(node, name, resource, data, offset, data.length - offset, value.length == 0); } } /** * Obtain a DNS record. * @param node the namehash of the node for which to fetch the record * @param name the keccak-256 hash of the fully-qualified name for which to fetch the record * @param resource the ID of the resource as per https://en.wikipedia.org/wiki/List_of_DNS_record_types * @return the DNS record in wire format if present, otherwise empty */ function dnsRecord(bytes32 node, bytes32 name, uint16 resource) public view returns (bytes memory) { return records[node][versions[node]][name][resource]; } /** * Check if a given node has records. * @param node the namehash of the node for which to check the records * @param name the namehash of the node for which to check the records */ function hasDNSRecords(bytes32 node, bytes32 name) public view returns (bool) { return (nameEntriesCount[node][versions[node]][name] != 0); } /** * Clear all information for a DNS zone. * @param node the namehash of the node for which to clear the zone */ function clearDNSZone(bytes32 node) public authorised(node) { versions[node]++; emit DNSZoneCleared(node); } /** * setZonehash sets the hash for the zone. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The zonehash to set */ function setZonehash(bytes32 node, bytes calldata hash) external authorised(node) { bytes memory oldhash = zonehashes[node]; zonehashes[node] = hash; emit DNSZonehashChanged(node, oldhash, hash); } /** * zonehash obtains the hash for the zone. * @param node The ENS node to query. * @return The associated contenthash. */ function zonehash(bytes32 node) external view returns (bytes memory) { return zonehashes[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == DNS_RECORD_INTERFACE_ID || interfaceID == DNS_ZONE_INTERFACE_ID || super.supportsInterface(interfaceID); } function setDNSRRSet( bytes32 node, bytes memory name, uint16 resource, bytes memory data, uint256 offset, uint256 size, bool deleteRecord) private { uint256 version = versions[node]; bytes32 nameHash = keccak256(name); bytes memory rrData = data.substring(offset, size); if (deleteRecord) { if (records[node][version][nameHash][resource].length != 0) { nameEntriesCount[node][version][nameHash]--; } delete(records[node][version][nameHash][resource]); emit DNSRecordDeleted(node, name, resource); } else { if (records[node][version][nameHash][resource].length == 0) { nameEntriesCount[node][version][nameHash]++; } records[node][version][nameHash][resource] = rrData; emit DNSRecordChanged(node, name, resource, rrData); } } } pragma solidity ^0.5.0; contract InterfaceResolver is ResolverBase, AddrResolver { bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)")); bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer); mapping(bytes32=>mapping(bytes4=>address)) interfaces; /** * Sets an interface associated with a name. * Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support. * @param node The node to update. * @param interfaceID The EIP 165 interface ID. * @param implementer The address of a contract that implements this interface for this node. */ function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) { interfaces[node][interfaceID] = implementer; emit InterfaceChanged(node, interfaceID, implementer); } /** * Returns the address of a contract that implements the specified interface for this name. * If an implementer has not been set for this interfaceID and name, the resolver will query * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that * contract implements EIP165 and returns `true` for the specified interfaceID, its address * will be returned. * @param node The ENS node to query. * @param interfaceID The EIP 165 interface ID to check for. * @return The address that implements this interface, or 0 if the interface is unsupported. */ function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) { address implementer = interfaces[node][interfaceID]; if(implementer != address(0)) { return implementer; } address a = addr(node); if(a == address(0)) { return address(0); } (bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // EIP 165 not supported by target return address(0); } (success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // Specified interface not supported by target return address(0); } return a; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract NameResolver is ResolverBase { bytes4 constant private NAME_INTERFACE_ID = 0x691f3431; event NameChanged(bytes32 indexed node, string name); mapping(bytes32=>string) names; /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string calldata name) external authorised(node) { names[node] = name; emit NameChanged(node, name); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) external view returns (string memory) { return names[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract PubkeyResolver is ResolverBase { bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233; event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); struct PublicKey { bytes32 x; bytes32 y; } mapping(bytes32=>PublicKey) pubkeys; /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) { pubkeys[node] = PublicKey(x, y); emit PubkeyChanged(node, x, y); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) { return (pubkeys[node].x, pubkeys[node].y); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; contract TextResolver is ResolverBase { bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c; event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); mapping(bytes32=>mapping(string=>string)) texts; /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) { texts[node][key] = value; emit TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string calldata key) external view returns (string memory) { return texts[node][key]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID); } } pragma solidity ^0.5.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, DNSResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver { ENS ens; /** * A mapping of authorisations. An address that is authorised for a name * may make any changes to the name that the owner could, but may not update * the set of authorisations. * (node, owner, caller) => isAuthorised */ mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations; event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised); constructor(ENS _ens) public { ens = _ens; } /** * @dev Sets or clears an authorisation. * Authorisations are specific to the caller. Any account can set an authorisation * for any name, but the authorisation that is checked will be that of the * current owner of a name. Thus, transferring a name effectively clears any * existing authorisations, and new authorisations can be set in advance of * an ownership transfer if desired. * * @param node The name to change the authorisation on. * @param target The address that is to be authorised or deauthorised. * @param isAuthorised True if the address should be authorised, or false if it should be deauthorised. */ function setAuthorisation(bytes32 node, address target, bool isAuthorised) external { authorisations[node][msg.sender][target] = isAuthorised; emit AuthorisationChanged(node, msg.sender, target, isAuthorised); } function isAuthorised(bytes32 node) internal view returns(bool) { address owner = ens.owner(node); return owner == msg.sender || authorisations[node][owner][msg.sender]; } }
Returns the contenthash associated with an ENS node. node The ENS node to query. return The associated contenthash./
function contenthash(bytes32 node) external view returns (bytes memory) { return hashes[node]; }
15,471
./full_match/421611/0x481148ed881807B574548B759141A0F515060d3f/sources/_aave/core-v3/contracts/protocol/libraries/logic/ValidationLogic.sol
Validates a flashloan action assets The assets being flashborrowed amounts The amounts for each asset being borrowed reservesData The state of all the reserves/
function validateFlashloan( address[] memory assets, uint256[] memory amounts, mapping(address => DataTypes.ReserveData) storage reservesData ) internal view { for (uint256 i = 0; i < assets.length; i++) { require(!reservesData[assets[i]].configuration.getPaused(), Errors.VL_RESERVE_PAUSED); require(reservesData[assets[i]].configuration.getActive(), Errors.VL_NO_ACTIVE_RESERVE); } require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS); }
13,220,285
./full_match/10200/0x34E520dc1d2Db660113b64724e14CEdCD01Ee879/sources/src/kleros-v1/kleros-liquid-xdai/xKlerosLiquidV2.sol
DEPRECATED. Called when `_owner` sends ETH to the Wrapped Token contract. _owner The address that sent the ETH to create tokens. return allowed Whether the operation should be allowed or not./
function proxyPayment(address _owner) public payable override returns (bool allowed) { allowed = false; }
3,785,045
./partial_match/1/0x963ee0e8ACE94ce6d9402277F6F54B1cEDf1f23A/sources/ZeroExV2Handler.sol
Reads an address from a position in a byte array. b Byte array containing an address. index Index in byte array of address. return address from byte array. Add offset to index: 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) Read address from array memory
{ require( "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED" ); index += 20; function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) assembly { result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; }
4,079,576
./full_match/137/0xb67642f60B83b0f1D4a47b342E6dE54318385A43/sources/contracts/Pausable.sol
returns to normal state
function unpause() public virtual whenPaused { paused = false; emit Unpause(); }
3,771,926
./full_match/4/0x3B1B20261A7318e1696ffdc8CF5e173B3e0517cC/sources/contracts/praverse.sol
Function to mint new NFTs during the public sale It is payable. Amount is calculated as per (NFT_PRICE.mul(_numOfTokens))/
function mintNFT(uint256 _numOfTokens) public payable nonReentrant { require(isActive, "Contract is not active"); require(!isWhitelistSaleActive, "Presale is still active"); require(_numOfTokens != 0, "impossible to mint 0 "); require(_numOfTokens <= BUY_LIMIT_PER_TX, "Cannot mint above limit"); require( totalSupply().add(_numOfTokens).sub(giveawayCount) <= MAX_PUBLIC_SUPPLY, "Purchase would exceed max public supply of NFTs" ); require( NFT_PRICE.mul(_numOfTokens) == msg.value, "Ether value sent is not correct" ); for (uint256 i = 0; i < _numOfTokens; i++) { _safeMint(msg.sender, totalSupply().sub(giveawayCount)); } }
792,256
//SPDX-License-Identifier: UNLICENSED pragma solidity >=0.7.0 <0.9.0; import "./CorporateFactory.sol"; import "./Admin.sol"; // Contract that funds are received at // needs to contain an idenitifier contract Receiver { address public ownerReceiver; Admin public admin; uint public funds; event ValueReceived(address user, uint amount); bool public valid; constructor(Admin admin_) { admin = admin_; ownerReceiver = msg.sender; valid = true; } // Gives the receiver the funds receive() external isValid payable { funds += msg.value; emit ValueReceived(msg.sender, msg.value); } function tFunds(address toSend, uint amount) external payable{ payable(toSend).transfer(amount); } function disableContract() public onlyOwner { valid = false; } function spendFunds(uint cost, address to_) external payable isValid onlyOwner { funds -= cost; (bool success,) = payable(to_).call{value:cost}(""); } // this function is used to send Subsidiaries funds when a transaction is made function sendSubFunds(Subsidiary toSend, uint tx_amount) payable external isValid returns(bool){ require(address(this).balance >= tx_amount, "Receiver contract does not have enough funds"); // check enough funds require(address(admin) == address(toSend.admin()) || ownerReceiver == toSend.owner(), "Owners/Admin do not match"); // check not hostile subsidiary require(toSend.valid() == true, "This subsidiary is no longer valid"); // check sub is valid // send the requested funds (bool success,) = payable(toSend).call{value:tx_amount}(""); return true; } modifier onlyOwner() { require(msg.sender == admin.owner() || msg.sender == address(admin)); _; } modifier isValid() { require(valid == true,"Receiver no longer valid"); _; } } contract ReceiverFactory { address public owner; // Owner of the contract Admin public admin; // Associated Admin Receiver[] public receiver_array; // Array of receivers mapping(address=> bool) public receivers; address public corporateFactory; constructor(Admin admin_) { admin = admin_; owner = msg.sender; } // This function creates a recevier contract function createreceiver() public onlyOwner returns (address) { // passes the admin to the receiver Receiver child = new Receiver(admin); // marks the receiver as valid receivers[address(child)] = true; // adds it to the array of receivers receiver_array.push(child); return address(child); } // checks if receiver exists function checkReceiver(address toCheck) external view returns (bool){ if (receivers[toCheck] == true ){ return true; } return false; } // updates associated Corporate Factory function updateCorporateFactory(address corp) public onlyOwner { corporateFactory = corp; } // gets a Receiver at index function getReceiver(uint index) public view returns(address){ return address(receiver_array[index]); } // Returns total number of receivers function getNumOfReceivers() public view returns(uint){ return receiver_array.length; } // checks if valid sender modifier onlyOwner() { require(msg.sender == owner || msg.sender == address(admin)); _; } }
checks if receiver exists
function checkReceiver(address toCheck) external view returns (bool){ if (receivers[toCheck] == true ){ return true; } return false; }
7,321,816
/** *Submitted for verification at Etherscan.io on 2022-04-27 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.13; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _createInitialSupply(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, 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); } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() external virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface ILpPair { function sync() external; } interface IDexRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function swapExactTokensForETHSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external; function swapExactETHForTokensSupportingFeeOnTransferTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable; function swapExactTokensForTokensSupportingFeeOnTransferTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external; function addLiquidityETH(address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity); function addLiquidity(address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline) external returns (uint amountA, uint amountB, uint liquidity); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); } interface IDexFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } contract TokenHandler is Ownable { function sendTokenToOwner(address token) external onlyOwner { if(IERC20(token).balanceOf(address(this)) > 0){ IERC20(token).transfer(owner(), IERC20(token).balanceOf(address(this))); } } } contract Contract2 is ERC20, Ownable { uint256 public maxBuyAmount; uint256 public maxSellAmount; uint256 public maxWalletAmount; IDexRouter public immutable dexRouter; address public immutable lpPair; TokenHandler public immutable tokenHandler; bool private swapping; uint256 public swapTokensAtAmount; address public operationsAddress; address public yashaAddress; uint256 public tradingActiveBlock = 0; // 0 means trading is not active bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; IERC20 public constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // Testnet: 0xeb8f08a975Ab53E34D8a0330E0D34de942C95926 //Mainnet: 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 uint256 public buyTotalFees; uint256 public buyOperationsFee; uint256 public buyLiquidityFee; uint256 public buyYashaFee; uint256 public sellTotalFees; uint256 public sellOperationsFee; uint256 public sellLiquidityFee; uint256 public sellYashaFee; uint256 public tokensForOperations; uint256 public tokensForLiquidity; uint256 public tokensForYasha; uint256 public lpWithdrawRequestTimestamp; uint256 public lpWithdrawRequestDuration = 3 days; bool public lpWithdrawRequestPending; uint256 public lpPercToWithDraw; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event EnabledTrading(); event RemovedLimits(); event ExcludeFromFees(address indexed account, bool isExcluded); event UpdatedMaxBuyAmount(uint256 newAmount); event UpdatedMaxSellAmount(uint256 newAmount); event UpdatedMaxWalletAmount(uint256 newAmount); event UpdatedOperationsAddress(address indexed newWallet); event UpdatedYashaAddress(address indexed newWallet); event MaxTransactionExclusion(address _address, bool excluded); event RequestedLPWithdraw(); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event TransferForeignToken(address token, uint256 amount); constructor() ERC20("Contract2", "C2") { address newOwner = msg.sender; // can leave alone if owner is deployer. IDexRouter _dexRouter = IDexRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); _excludeFromMaxTransaction(address(_dexRouter), true); dexRouter = _dexRouter; lpPair = IDexFactory(_dexRouter.factory()).createPair(address(this), address(USDC)); _setAutomatedMarketMakerPair(address(lpPair), true); tokenHandler = new TokenHandler(); uint256 totalSupply = 1 * 1e9 * 1e18; maxBuyAmount = totalSupply * 1 / 1000; maxSellAmount = totalSupply * 1 / 1000; maxWalletAmount = totalSupply * 2 / 1000; swapTokensAtAmount = totalSupply * 25 / 100000; // 0.025% swap amount buyOperationsFee = 2; buyLiquidityFee = 3; buyYashaFee = 1; buyTotalFees = buyOperationsFee + buyLiquidityFee + buyYashaFee; sellOperationsFee = 5; sellLiquidityFee = 3; sellYashaFee = 1; sellTotalFees = sellOperationsFee + sellLiquidityFee + sellYashaFee; _excludeFromMaxTransaction(newOwner, true); _excludeFromMaxTransaction(address(this), true); _excludeFromMaxTransaction(address(0xdead), true); excludeFromFees(newOwner, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); operationsAddress = address(newOwner); yashaAddress = address(newOwner); _createInitialSupply(newOwner, totalSupply); transferOwnership(newOwner); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { require(!tradingActive, "Cannot reenable trading"); tradingActive = true; swapEnabled = true; tradingActiveBlock = block.number; emit EnabledTrading(); } // remove limits after token is stable function removeLimits() external onlyOwner { limitsInEffect = false; transferDelayEnabled = false; emit RemovedLimits(); } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner { transferDelayEnabled = false; } function updateMaxBuyAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set max buy amount lower than 0.1%"); maxBuyAmount = newNum * (10**18); emit UpdatedMaxBuyAmount(maxBuyAmount); } function updateMaxSellAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set max sell amount lower than 0.1%"); maxSellAmount = newNum * (10**18); emit UpdatedMaxSellAmount(maxSellAmount); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 3 / 1000)/1e18, "Cannot set max wallet amount lower than 0.3%"); maxWalletAmount = newNum * (10**18); emit UpdatedMaxWalletAmount(maxWalletAmount); } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner { require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 1 / 1000, "Swap amount cannot be higher than 0.1% total supply."); swapTokensAtAmount = newAmount; } function _excludeFromMaxTransaction(address updAds, bool isExcluded) private { _isExcludedMaxTransactionAmount[updAds] = isExcluded; emit MaxTransactionExclusion(updAds, isExcluded); } function airdropToWallets(address[] memory wallets, uint256[] memory amountsInTokens) external onlyOwner { require(wallets.length == amountsInTokens.length, "arrays must be the same length"); require(wallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop + launch at the same exact time, reducing delays and reducing sniper input. for(uint256 i = 0; i < wallets.length; i++){ address wallet = wallets[i]; uint256 amount = amountsInTokens[i]*1e18; _transfer(msg.sender, wallet, amount); } } function excludeFromMaxTransaction(address updAds, bool isEx) external onlyOwner { if(!isEx){ require(updAds != lpPair, "Cannot remove uniswap pair from max txn"); } _isExcludedMaxTransactionAmount[updAds] = isEx; } function setAutomatedMarketMakerPair(address pair, bool value) external onlyOwner { require(pair != lpPair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; _excludeFromMaxTransaction(pair, value); emit SetAutomatedMarketMakerPair(pair, value); } function updateBuyFees(uint256 _operationsFee, uint256 _liquidityFee, uint256 _yashaFee) external onlyOwner { buyOperationsFee = _operationsFee; buyLiquidityFee = _liquidityFee; buyYashaFee = _yashaFee; buyTotalFees = buyOperationsFee + buyLiquidityFee + buyYashaFee; require(buyTotalFees <= 15, "Must keep fees at 15% or less"); } function updateSellFees(uint256 _operationsFee, uint256 _liquidityFee, uint256 _yashaFee) external onlyOwner { sellOperationsFee = _operationsFee; sellLiquidityFee = _liquidityFee; sellYashaFee = _yashaFee; sellTotalFees = sellOperationsFee + sellLiquidityFee + sellYashaFee; require(sellTotalFees <= 20, "Must keep fees at 20% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "amount must be greater than 0"); if(limitsInEffect){ if (from != owner() && to != owner() && to != address(0) && to != address(0xdead)){ if(!tradingActive){ require(_isExcludedMaxTransactionAmount[from] || _isExcludedMaxTransactionAmount[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != address(dexRouter) && to != address(lpPair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number - 4 && _holderLastTransferTimestamp[to] < block.number - 4, "_transfer:: Transfer Delay enabled. Try again later."); _holderLastTransferTimestamp[tx.origin] = block.number; _holderLastTransferTimestamp[to] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxBuyAmount, "Buy transfer amount exceeds the max buy."); require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxSellAmount, "Sell transfer amount exceeds the max sell."); } else if (!_isExcludedMaxTransactionAmount[to] && !_isExcludedMaxTransactionAmount[from]){ require(amount + balanceOf(to) <= maxWalletAmount, "Cannot Exceed max wallet"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if(canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { swapping = true; swapBack(); swapping = false; } bool takeFee = true; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; uint256 penaltyAmount = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // bot/sniper penalty. Tokens get transferred to marketing wallet to allow potential refund. if(tradingActiveBlock + 1 >= block.number && automatedMarketMakerPairs[from]){ penaltyAmount = amount * 99 / 100; super._transfer(from, operationsAddress, penaltyAmount); } // on sell else if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount * sellTotalFees /100; tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForOperations += fees * sellOperationsFee / sellTotalFees; tokensForYasha += fees * sellYashaFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount * buyTotalFees / 100; tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForOperations += fees * buyOperationsFee / buyTotalFees; tokensForYasha += fees * buyYashaFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees + penaltyAmount; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); _approve(address(this), address(dexRouter), tokenAmount); // make the swap dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 usdcAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(dexRouter), tokenAmount); USDC.approve(address(dexRouter), usdcAmount); // add the liquidity dexRouter.addLiquidity(address(this), address(USDC), tokenAmount, usdcAmount, 0, 0, address(this), block.timestamp); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForOperations + tokensForYasha; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 10){ contractBalance = swapTokensAtAmount * 10; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; swapTokensForUSDC(contractBalance - liquidityTokens); tokenHandler.sendTokenToOwner(address(USDC)); uint256 usdcBalance = USDC.balanceOf(address(this)); uint256 usdcForLiquidity = usdcBalance; uint256 usdcForOperations = usdcBalance * tokensForOperations / (totalTokensToSwap - (tokensForLiquidity/2)); uint256 usdcForYasha = usdcBalance * tokensForYasha / (totalTokensToSwap - (tokensForLiquidity/2)); usdcForLiquidity -= usdcForOperations + usdcForYasha; tokensForLiquidity = 0; tokensForOperations = 0; tokensForYasha = 0; if(liquidityTokens > 0 && usdcForLiquidity > 0){ addLiquidity(liquidityTokens, usdcForLiquidity); } if(usdcForYasha > 0){ USDC.transfer(yashaAddress, usdcForYasha); } if(USDC.balanceOf(address(this)) > 0){ USDC.transfer(operationsAddress, USDC.balanceOf(address(this))); } } function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) { require(_token != address(0), "_token address cannot be 0"); require(_token != address(this), "Can't withdraw native tokens"); uint256 _contractBalance = IERC20(_token).balanceOf(address(this)); _sent = IERC20(_token).transfer(_to, _contractBalance); emit TransferForeignToken(_token, _contractBalance); } function swapTokensForUSDC(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = address(USDC); _approve(address(this), address(dexRouter), tokenAmount); // make the swap dexRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(tokenHandler), block.timestamp ); } // withdraw ETH if stuck or someone sends to the address function withdrawStuckETH() external onlyOwner { bool success; (success,) = address(msg.sender).call{value: address(this).balance}(""); } function setOperationsAddress(address _operationsAddress) external onlyOwner { require(_operationsAddress != address(0), "_operationsAddress address cannot be 0"); operationsAddress = payable(_operationsAddress); emit UpdatedOperationsAddress(_operationsAddress); } function setYashaAddress(address _yashaAddress) external onlyOwner { require(_yashaAddress != address(0), "_yashaAddress address cannot be 0"); yashaAddress = payable(_yashaAddress); emit UpdatedYashaAddress(_yashaAddress); } function requestToWithdrawLP(uint256 percToWithdraw) external onlyOwner { require(!lpWithdrawRequestPending, "Cannot request again until first request is over."); require(percToWithdraw <= 100 && percToWithdraw > 0, "Need to set between 1-100%"); lpWithdrawRequestTimestamp = block.timestamp; lpWithdrawRequestPending = true; lpPercToWithDraw = percToWithdraw; emit RequestedLPWithdraw(); } function nextAvailableLpWithdrawDate() public view returns (uint256){ if(lpWithdrawRequestPending){ return lpWithdrawRequestTimestamp + lpWithdrawRequestDuration; } else { return 0; // 0 means no open requests } } function withdrawRequestedLP() external onlyOwner { require(block.timestamp >= nextAvailableLpWithdrawDate() && nextAvailableLpWithdrawDate() > 0, "Must request and wait."); lpWithdrawRequestTimestamp = 0; lpWithdrawRequestPending = false; uint256 amtToWithdraw = IERC20(address(lpPair)).balanceOf(address(this)) * lpPercToWithDraw / 100; lpPercToWithDraw = 0; IERC20(lpPair).transfer(msg.sender, amtToWithdraw); } function cancelLPWithdrawRequest() external onlyOwner { lpWithdrawRequestPending = false; } }
generate the uniswap pair path of token -> weth make the swap
function swapTokensForUSDC(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = address(USDC); _approve(address(this), address(dexRouter), tokenAmount); dexRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens( tokenAmount, path, address(tokenHandler), block.timestamp ); }
10,913,793
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "./IntMath.sol"; struct Rebase { uint128 elastic; uint128 base; } /** * * @dev This library provides a collection of functions to manipulate a base and elastic values saved in a Rebase struct. * In a pool context, the base represents the amount of tokens deposited or withdrawn from an investor. * The elastic value represents how the pool tokens performed over time by incurring losses or profits. * With this library, one can easily calculate how much loss or profit each investor incurred based on their tokens * invested. * * @notice We use the {SafeCast} Open Zeppelin library for safely converting from uint256 to uint128 memory storage efficiency. * Therefore, it is important to keep in mind of the upperbound limit number this library supports. * */ library RebaseLibrary { using SafeCast for uint256; using IntMath for uint256; /** * @dev Calculates a base value from an elastic value using the ratio of a {Rebase} struct. * * @param total {Rebase} struct, which represents a base/elastic pair. * @param elastic The new base is calculated from this elastic. * @param roundUp Rounding logic due to solidity always rounding down. * @return base The calculated base. * */ function toBase( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (uint256 base) { if (total.elastic == 0) { base = elastic; } else { base = elastic.mulDiv(total.base, total.elastic); if (roundUp && base.mulDiv(total.elastic, total.base) < elastic) { base += 1; } } } /** * @dev Calculates the elastic value from a base value using the ratio of a {Rebase} struct. * * @param total {Rebase} struct, which represents a base/elastic pair. * @param base The new base, which the new elastic will be calculated from. * @param roundUp Rounding logic due to solidity always rounding down. * @return elastic The calculated elastic. * */ function toElastic( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (uint256 elastic) { if (total.base == 0) { elastic = base; } else { elastic = base.mulDiv(total.elastic, total.base); if (roundUp && elastic.mulDiv(total.base, total.elastic) < base) { elastic += 1; } } } /** * @dev Calculates new values to a {Rebase} pair by incrementing the elastic value. * This function maintains the ratio of the current pair. * * @param total {Rebase} struct which represents a base/elastic pair. * @param elastic The new elastic to be added to the pair. * A new base will be calculated based on the new elastic using {toBase} function. * @param roundUp Rounding logic due to solidity always rounding down. * @return (total, base) A pair of the new {Rebase} pair values and new calculated base. * */ function add( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (Rebase memory, uint256 base) { base = toBase(total, elastic, roundUp); total.elastic += elastic.toUint128(); total.base += base.toUint128(); return (total, base); } /** * @dev Calculates new values to a {Rebase} pair by reducing the base. * This function maintains the ratio of the current pair. * * @param total {Rebase} struct, which represents a base/elastic pair. * @param base The number to be subtracted from the base. * The new elastic will be calculated based on the new base value via the {toElastic} function. * @param roundUp Rounding logic due to solidity always rounding down. * @return (total, elastic) A pair of the new {Rebase} pair values and the new elastic based on the updated base. * */ function sub( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (Rebase memory, uint256 elastic) { elastic = toElastic(total, base, roundUp); total.elastic -= elastic.toUint128(); total.base -= base.toUint128(); return (total, elastic); } /** * @dev Increases the base and elastic from a {Rebase} pair without keeping a specific ratio. * * @param total {Rebase} struct which represents a base/elastic pair that will be updated. * @param base The value to be added to the `total.base`. * @param elastic The value to be added to the `total.elastic`. * @return total The new {Rebase} pair calculated by adding the `base` and `elastic` values. * */ function add( Rebase memory total, uint256 base, uint256 elastic ) internal pure returns (Rebase memory) { total.base += base.toUint128(); total.elastic += elastic.toUint128(); return total; } /** * @dev Decreases the base and elastic from a {Rebase} pair without keeping a specific ratio. * * @param total The base/elastic pair that will be updated. * @param base The value to be decreased from the `total.base`. * @param elastic The value to be decreased from the `total.elastic`. * @return total The new {Rebase} calculated by decreasing the base and pair from `total`. * */ function sub( Rebase memory total, uint256 base, uint256 elastic ) internal pure returns (Rebase memory) { total.base -= base.toUint128(); total.elastic -= elastic.toUint128(); return total; } /** * @dev Adds elastic to a {Rebase} pair. * * @notice The `total` parameter is saved in storage. This will update the global state of the caller contract. * * @param total The {Rebase} struct, which will have its' elastic increased. * @param elastic The value to be added to the elastic of `total`. * @return newElastic The new elastic value after reducing `elastic` from `total.elastic`. * */ function addElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic += elastic.toUint128(); } /** * @dev Reduces the elastic of a {Rebase} pair. * * @notice The `total` parameter is saved in storage. The caller contract will have its' storage updated. * * @param total The {Rebase} struct to be updated. * @param elastic The value to be removed from the `total` elastic. * @return newElastic The new elastic after decreasing `elastic` from `total.elastic`. * */ function subElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) { newElastic = total.elastic -= elastic.toUint128(); } }
Calculates new values to a {Rebase} pair by incrementing the elastic value. This function maintains the ratio of the current pair. total {Rebase} struct which represents a base/elastic pair. elastic The new elastic to be added to the pair. A new base will be calculated based on the new elastic using {toBase} function. roundUp Rounding logic due to solidity always rounding down. return (total, base) A pair of the new {Rebase} pair values and new calculated base./
function add( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (Rebase memory, uint256 base) { base = toBase(total, elastic, roundUp); total.elastic += elastic.toUint128(); total.base += base.toUint128(); return (total, base); }
15,796,722
pragma solidity 0.8.13; import "./PoolToken.sol"; import "./BAllowance.sol"; import "./BInterestRateModel.sol"; import "./BSetter.sol"; import "./BStorage.sol"; import "./interfaces/IBorrowable.sol"; import "./interfaces/ICollateral.sol"; import "./interfaces/IImpermaxCallee.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IFactory.sol"; import "./interfaces/IBorrowTracker.sol"; import "./libraries/Math.sol"; import "./libraries/Errors.sol"; // TODO: Inherit IBorrowable contract Borrowable is PoolToken, BStorage, BSetter, BInterestRateModel, BAllowance { uint public constant BORROW_FEE = 0; event Borrow(address indexed sender, address indexed borrower, address indexed receiver, uint borrowAmount, uint repayAmount, uint accountBorrowsPrior, uint accountBorrows, uint totalBorrows); event Liquidate(address indexed sender, address indexed borrower, address indexed liquidator, uint seizeTokens, uint repayAmount, uint accountBorrowsPrior, uint accountBorrows, uint totalBorrows); /*** PoolToken ***/ function _update() internal override { super._update(); _calculateBorrowRate(); } function _mintReserves(uint _exchangeRate, uint _totalSupply) internal returns (uint) { uint _exchangeRateLast = exchangeRateLast; if (_exchangeRate > _exchangeRateLast) { uint _exchangeRateNew = _exchangeRate - (((_exchangeRate - _exchangeRateLast) * reserveFactor) / 1e18); uint liquidity = ((_totalSupply * _exchangeRate) / _exchangeRateNew) - _totalSupply; if (liquidity > 0) { address reservesManager = IFactory(factory).reservesManager(); _mint(reservesManager, liquidity); } exchangeRateLast = _exchangeRateNew; return _exchangeRateNew; } else return _exchangeRate; } function exchangeRate() public override accrue returns (uint) { uint _totalSupply = totalSupply; uint _actualBalance = totalBalance + totalBorrows; if (_totalSupply == 0 || _actualBalance == 0) return initialExchangeRate; uint _exchangeRate = (_actualBalance * 1e18) / _totalSupply; return _mintReserves(_exchangeRate, _totalSupply); } // force totalBalance to match real balance function sync() external override nonReentrant update accrue {} /*** Borrowable ***/ // this is the stored borrow balance; the current borrow balance may be slightly higher function borrowBalance(address borrower) public view returns (uint) { BorrowSnapshot memory borrowSnapshot = borrowBalances[borrower]; if (borrowSnapshot.interestIndex == 0) return 0; // not initialized return (uint(borrowSnapshot.principal) * borrowIndex) / borrowSnapshot.interestIndex; } function _trackBorrow(address borrower, uint accountBorrows, uint _borrowIndex) internal { address _borrowTracker = borrowTracker; if (_borrowTracker == address(0)) return; IBorrowTracker(_borrowTracker).trackBorrow(borrower, accountBorrows, _borrowIndex); } function _updateBorrow(address borrower, uint borrowAmount, uint repayAmount) private returns (uint accountBorrowsPrior, uint accountBorrows, uint _totalBorrows) { accountBorrowsPrior = borrowBalance(borrower); if (borrowAmount == repayAmount) return (accountBorrowsPrior, accountBorrowsPrior, totalBorrows); uint112 _borrowIndex = borrowIndex; if (borrowAmount > repayAmount) { BorrowSnapshot storage borrowSnapshot = borrowBalances[borrower]; uint increaseAmount = borrowAmount - repayAmount; accountBorrows = accountBorrowsPrior + increaseAmount; borrowSnapshot.principal = safe112(accountBorrows); borrowSnapshot.interestIndex = _borrowIndex; _totalBorrows = uint(totalBorrows) + increaseAmount; totalBorrows = safe112(_totalBorrows); } else { BorrowSnapshot storage borrowSnapshot = borrowBalances[borrower]; uint decreaseAmount = repayAmount - borrowAmount; accountBorrows = accountBorrowsPrior > decreaseAmount ? accountBorrowsPrior - decreaseAmount : 0; borrowSnapshot.principal = safe112(accountBorrows); if(accountBorrows == 0) { borrowSnapshot.interestIndex = 0; } else { borrowSnapshot.interestIndex = _borrowIndex; } uint actualDecreaseAmount = accountBorrowsPrior - accountBorrows; _totalBorrows = totalBorrows; // gas savings _totalBorrows = _totalBorrows > actualDecreaseAmount ? _totalBorrows - actualDecreaseAmount : 0; totalBorrows = safe112(_totalBorrows); } _trackBorrow(borrower, accountBorrows, _borrowIndex); } // this low-level function should be called from another contract function borrow(address borrower, address receiver, uint borrowAmount, bytes calldata data) external nonReentrant update accrue { uint _totalBalance = totalBalance; _require(borrowAmount <= _totalBalance, Errors.INSUFFICIENT_CASH); _checkBorrowAllowance(borrower, msg.sender, borrowAmount); // optimistically transfer funds if (borrowAmount > 0) _safeTransfer(receiver, borrowAmount); if (data.length > 0) IImpermaxCallee(receiver).impermaxBorrow(msg.sender, borrower, borrowAmount, data); uint balance = IERC20(underlying).balanceOf(address(this)); uint borrowFee = (borrowAmount * BORROW_FEE) / 1e18; uint adjustedBorrowAmount = borrowAmount + borrowFee; uint repayAmount = (balance + borrowAmount) - _totalBalance; (uint accountBorrowsPrior, uint accountBorrows, uint _totalBorrows) = _updateBorrow(borrower, adjustedBorrowAmount, repayAmount); if(adjustedBorrowAmount > repayAmount) _require( ICollateral(collateral).canBorrow(borrower, address(this), accountBorrows), Errors.INSUFFICIENT_LIQUIDITY ); emit Borrow(msg.sender, borrower, receiver, borrowAmount, repayAmount, accountBorrowsPrior, accountBorrows, _totalBorrows); } // this low-level function should be called from another contract function liquidate(address borrower, address liquidator) external nonReentrant update accrue returns (uint seizeTokens) { uint balance = IERC20(underlying).balanceOf(address(this)); uint repayAmount = balance - totalBalance; uint actualRepayAmount = Math.min(borrowBalance(borrower), repayAmount); seizeTokens = ICollateral(collateral).seize(liquidator, borrower, actualRepayAmount); (uint accountBorrowsPrior, uint accountBorrows, uint _totalBorrows) = _updateBorrow(borrower, 0, repayAmount); emit Liquidate(msg.sender, borrower, liquidator, seizeTokens, repayAmount, accountBorrowsPrior, accountBorrows, _totalBorrows); } function trackBorrow(address borrower) external { _trackBorrow(borrower, borrowBalance(borrower), borrowIndex); } modifier accrue() { accrueInterest(); _; } }
force totalBalance to match real balance
function sync() external override nonReentrant update accrue {}
5,342,667
//Address: 0x2e63cceffa42b095f0bd6d0fcadb521200b8fef5 //Contract name: EtherAuction //Balance: 0 Ether //Verification Date: 11/14/2017 //Transacion Count: 6 // CODE STARTS HERE pragma solidity ^0.4.18; contract EtherAuction { // The address that deploys this auction and volunteers 1 eth as price. address public auctioneer; uint public auctionedEth = 0; uint public highestBid = 0; uint public secondHighestBid = 0; address public highestBidder; address public secondHighestBidder; uint public latestBidTime = 0; uint public auctionEndTime; mapping (address => uint) public balances; bool public auctionStarted = false; bool public auctionFinalized = false; event E_AuctionStarted(address _auctioneer, uint _auctionStart, uint _auctionEnd); event E_Bid(address _highestBidder, uint _highestBid); event E_AuctionFinished(address _highestBidder,uint _highestBid,address _secondHighestBidder,uint _secondHighestBid,uint _auctionEndTime); function EtherAuction(){ auctioneer = msg.sender; } // The auctioneer has to call this function while supplying the 1th to start the auction function startAuction() public payable{ require(!auctionStarted); require(msg.sender == auctioneer); require(msg.value == (1 * 10 ** 18)); auctionedEth = msg.value; auctionStarted = true; auctionEndTime = now + (3600 * 24 * 7); // Ends 7 days after the deployment of the contract E_AuctionStarted(msg.sender,now, auctionEndTime); } //Anyone can bid by calling this function and supplying the corresponding eth function bid() public payable { require(auctionStarted); require(now < auctionEndTime); require(msg.sender != auctioneer); require(highestBidder != msg.sender); //If sender is already the highest bidder, reject it. address _newBidder = msg.sender; uint previousBid = balances[_newBidder]; uint _newBid = msg.value + previousBid; require (_newBid == highestBid + (5 * 10 ** 16)); //Each bid has to be 0.05 eth higher // The highest bidder is now the second highest bidder secondHighestBid = highestBid; secondHighestBidder = highestBidder; highestBid = _newBid; highestBidder = _newBidder; latestBidTime = now; //Update the bidder's balance so they can later withdraw any pending balance balances[_newBidder] = _newBid; //If there's less than an hour remaining and someone bids, extend end time. if(auctionEndTime - now < 3600) auctionEndTime += 3600; // Each bid extends the auctionEndTime by 1 hour E_Bid(highestBidder, highestBid); } // Once the auction end has been reached, we distribute the ether. function finalizeAuction() public { require (now > auctionEndTime); require (!auctionFinalized); auctionFinalized = true; if(highestBidder == address(0)){ //If no one bid at the auction, auctioneer can withdraw the funds. balances[auctioneer] = auctionedEth; }else{ // Second highest bidder gets nothing, his latest bid is lost and sent to the auctioneer balances[secondHighestBidder] -= secondHighestBid; balances[auctioneer] += secondHighestBid; //Auctioneer gets the highest bid from the highest bidder. balances[highestBidder] -= highestBid; balances[auctioneer] += highestBid; //winner gets the 1eth being auctioned. balances[highestBidder] += auctionedEth; auctionedEth = 0; } E_AuctionFinished(highestBidder,highestBid,secondHighestBidder,secondHighestBid,auctionEndTime); } //Once the auction has finished, the bidders can withdraw the eth they put //Winner will withdraw the auctionedEth //Auctioneer will withdraw the highest bid from the winner //Second highest bidder will already have his balance at 0 //The rest of the bidders get their money back function withdrawBalance() public{ require (auctionFinalized); uint ethToWithdraw = balances[msg.sender]; if(ethToWithdraw > 0){ balances[msg.sender] = 0; msg.sender.transfer(ethToWithdraw); } } //Call thisfunction to know how many seconds remain for the auction to end function timeRemaining() public view returns (uint){ require (auctionEndTime > now); return auctionEndTime - now; } function myLatestBid() public view returns (uint){ return balances[msg.sender]; } }
Once the auction has finished, the bidders can withdraw the eth they putWinner will withdraw the auctionedEthAuctioneer will withdraw the highest bid from the winnerSecond highest bidder will already have his balance at 0The rest of the bidders get their money back
function withdrawBalance() public{ require (auctionFinalized); uint ethToWithdraw = balances[msg.sender]; if(ethToWithdraw > 0){ balances[msg.sender] = 0; msg.sender.transfer(ethToWithdraw); } }
12,947,166
pragma solidity >=0.4.21 <0.7.0; interface ArbOwner { // Support actions that can be taken by the chain's owner. // All methods will revert, unless the caller is the chain's owner. function addToReserveFunds() external payable; function setFairGasPriceSender(address addr, bool isFairGasPriceSender) external; function isFairGasPriceSender(address addr) external view returns(bool); function getAllFairGasPriceSenders() external view returns(bytes memory); // DEPRECATED: use ArbGasInfo.setL1GasPriceEstimate(priceInGwei * 1000000000) instead function setL1GasPriceEstimate(uint priceInGwei) external; // Deploy a contract on the chain // The contract is deployed as if it was submitted by deemedSender with deemedNonce // Reverts if there is already a contract at that address // Returns the address of the deployed contract function deployContract(bytes calldata constructorData, address deemedSender, uint deemedNonce) external payable returns(address); // To upgrade ArbOS, the owner calls startArbosUpgrade or startArbosUpgradeWithCheck, // then calls continueArbosUpgrade one or more times to upload // the code to be installed as the upgrade, then calls finishArbosUpgrade to complete the upgrade and start executing the new code. // startCodeUploadWithCheck will revert unless oldCodeHash equals either zero or the hash of the last ArbOS upgrade function startCodeUpload() external; function startCodeUploadWithCheck(bytes32 oldCodeHash) external; function continueCodeUpload(bytes calldata marshalledCode) external; function getUploadedCodeHash() external view returns(bytes32); // Install the currently uploaded code as an ArbOS upgrade. // Revert if the hash of the uploaded code bytes does not equal newCodeHash // Revert if (oldCodeHash != 0) && (oldCodeHash != [hash of code bytes from the previous ArbOS upgrade] function finishCodeUploadAsArbosUpgrade(bytes32 newCodeHash, bytes32 oldCodeHash) external; // Get the code hash of the last upgrade that was installed, or zero if there hasn't been an upgrade on this chain function getLastUpgradeHash() external view returns(bytes32); // Get and set chain parameters function getChainParameter(bytes32 which) external view returns(uint); function setChainParameter(bytes32 which, uint value) external; // reverts if param doesn't already exist function createChainParameter(bytes32 which, uint value) external; // sets param, even if it didn't already exist function serializeAllParameters() external view returns(bytes memory); // Manage the set of allowed senders // address 0 and the chain owner are always allowed to send, even if not on the list function allowAllSenders() external; function allowOnlyOwnerToSend() external; function isAllowedSender(address addr) external view returns(bool); function addAllowedSender(address addr) external; function removeAllowedSender(address addr) external; function getAllAllowedSenders() external view returns(bytes memory); // reverts if all or nearly all senders are allowed // Manage the set of chain owners function addChainOwner(address newOwner) external; function removeChainOwner(address ownerToRemove) external; // revert if ownerToRemove is not an owner function isChainOwner(address addr) external view returns(bool); function getAllChainOwners() external view returns(bytes memory); // Manage exceptions to L1->L2 address remapping function addMappingException(uint from, uint to) external; function removeMappingException(uint from, uint to) external; function isMappingException(uint from, uint to) external view returns(bool); function getAllMappingExceptions() external view returns (bytes memory); function getTotalOfEthBalances() external view returns(uint); }
revert if ownerToRemove is not an owner
function removeChainOwner(address ownerToRemove) external;
886,701
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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: 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 Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function parseAssetsForAction( address _vaultProxy, bytes4 _selector, bytes calldata _encodedCallArgs ) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../utils/actions/CurveGaugeV2RewardsHandlerMixin.sol"; import "../utils/bases/CurveLiquidityAdapterBase.sol"; /// @title CurveLiquidityAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for liquidity provision in Curve pools that adhere to pool templates, /// as well as some old pools that have almost the same required interface (e.g., 3pool). /// Allows staking via Curve gauges. /// @dev Rewards tokens are not included as incoming assets for claimRewards() /// Rationale: /// - rewards tokens can be claimed to the vault outside of the IntegrationManager, so no need /// to enforce policy management or emit an event /// - rewards tokens can be outside of the asset universe, in which case they cannot be tracked contract CurveLiquidityAdapter is CurveLiquidityAdapterBase, CurveGaugeV2RewardsHandlerMixin { constructor( address _integrationManager, address _curveAddressProvider, address _wrappedNativeAsset, address _curveMinter, address _crvToken ) public CurveLiquidityAdapterBase(_integrationManager, _curveAddressProvider, _wrappedNativeAsset) CurveGaugeV2RewardsHandlerMixin(_curveMinter, _crvToken) {} // EXTERNAL FUNCTIONS /// @notice Claims rewards from the Curve Minter as well as pool-specific rewards /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @dev Pool must have an ERC20 liquidity gauge (e.g., v2, v3, v4) or an ERC20 wrapper (e.g., v1) function claimRewards( address _vaultProxy, bytes calldata _actionData, bytes calldata ) external onlyIntegrationManager { __curveGaugeV2ClaimAllRewards(__decodeClaimRewardsCallArgs(_actionData), _vaultProxy); } /// @notice Lends assets for LP tokens (not staked) /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @param _assetData Parsed spend assets and incoming assets data for this action function lend( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData) { ( address pool, uint256[] memory orderedOutgoingAssetAmounts, uint256 minIncomingLpTokenAmount, bool useUnderlyings ) = __decodeLendCallArgs(_actionData); (address[] memory spendAssets, , ) = __decodeAssetData(_assetData); __curveAddLiquidity( pool, spendAssets, orderedOutgoingAssetAmounts, minIncomingLpTokenAmount, useUnderlyings ); } /// @notice Lends assets for LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @param _assetData Parsed spend assets and incoming assets data for this action function lendAndStake( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData) { ( address pool, uint256[] memory orderedOutgoingAssetAmounts, address incomingStakingToken, uint256 minIncomingStakingTokenAmount, bool useUnderlyings ) = __decodeLendAndStakeCallArgs(_actionData); (address[] memory spendAssets, , ) = __decodeAssetData(_assetData); // Pool already validated by validating the gauge address lpToken = ICurveRegistry( ICurveAddressProvider(getAddressProvider()).get_registry() ) .get_lp_token(pool); __curveAddLiquidity( pool, spendAssets, orderedOutgoingAssetAmounts, minIncomingStakingTokenAmount, useUnderlyings ); __curveGaugeV2Stake( incomingStakingToken, lpToken, ERC20(lpToken).balanceOf(address(this)) ); } /// @notice Redeems LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @param _assetData Parsed spend assets and incoming assets data for this action function redeem( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData) { ( address pool, uint256 outgoingLpTokenAmount, bool useUnderlyings, RedeemType redeemType, bytes memory incomingAssetsData ) = __decodeRedeemCallArgs(_actionData); __curveRedeem(pool, outgoingLpTokenAmount, useUnderlyings, redeemType, incomingAssetsData); } /// @notice Stakes LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _assetData Parsed spend assets and incoming assets data for this action function stake( address _vaultProxy, bytes calldata, bytes calldata _assetData ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData) { ( address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeAssetData(_assetData); __curveGaugeV2Stake(incomingAssets[0], spendAssets[0], spendAssetAmounts[0]); } /// @notice Unstakes LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @param _assetData Parsed spend assets and incoming assets data for this action function unstake( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData) { (, address outgoingStakingToken, uint256 amount) = __decodeUnstakeCallArgs(_actionData); __curveGaugeV2Unstake(outgoingStakingToken, amount); } /// @notice Unstakes LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @param _assetData Parsed spend assets and incoming assets data for this action function unstakeAndRedeem( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData) { ( address pool, address outgoingStakingToken, uint256 outgoingStakingTokenAmount, bool useUnderlyings, RedeemType redeemType, bytes memory incomingAssetsData ) = __decodeUnstakeAndRedeemCallArgs(_actionData); __curveGaugeV2Unstake(outgoingStakingToken, outgoingStakingTokenAmount); __curveRedeem( pool, outgoingStakingTokenAmount, useUnderlyings, redeemType, incomingAssetsData ); } ///////////////////////////// // PARSE ASSETS FOR METHOD // ///////////////////////////// /// @notice Parses the expected assets in a particular action /// @param _selector The function selector for the callOnIntegration /// @param _actionData Data specific to this action /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForAction( address, bytes4 _selector, bytes calldata _actionData ) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == CLAIM_REWARDS_SELECTOR) { return __parseAssetsForClaimRewards(); } else if (_selector == LEND_SELECTOR) { return __parseAssetsForLend(_actionData); } else if (_selector == LEND_AND_STAKE_SELECTOR) { return __parseAssetsForLendAndStake(_actionData); } else if (_selector == REDEEM_SELECTOR) { return __parseAssetsForRedeem(_actionData); } else if (_selector == STAKE_SELECTOR) { return __parseAssetsForStake(_actionData); } else if (_selector == UNSTAKE_SELECTOR) { return __parseAssetsForUnstake(_actionData); } else if (_selector == UNSTAKE_AND_REDEEM_SELECTOR) { return __parseAssetsForUnstakeAndRedeem(_actionData); } revert("parseAssetsForAction: _selector invalid"); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during claimRewards() calls. /// No action required, all values empty. function __parseAssetsForClaimRewards() private pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { return ( IIntegrationManager.SpendAssetsHandleType.None, new address[](0), new uint256[](0), new address[](0), new uint256[](0) ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during lend() calls function __parseAssetsForLend(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( address pool, uint256[] memory orderedOutgoingAssetAmounts, uint256 minIncomingLpTokenAmount, bool useUnderlyings ) = __decodeLendCallArgs(_actionData); address curveRegistry = ICurveAddressProvider(getAddressProvider()).get_registry(); address lpToken = ICurveRegistry(curveRegistry).get_lp_token(pool); require(lpToken != address(0), "__parseAssetsForLend: Invalid pool"); incomingAssets_ = new address[](1); incomingAssets_[0] = lpToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingLpTokenAmount; (spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls( curveRegistry, pool, orderedOutgoingAssetAmounts, useUnderlyings ); return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during lendAndStake() calls function __parseAssetsForLendAndStake(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( address pool, uint256[] memory orderedOutgoingAssetAmounts, address incomingStakingToken, uint256 minIncomingStakingTokenAmount, bool useUnderlyings ) = __decodeLendAndStakeCallArgs(_actionData); address curveRegistry = ICurveAddressProvider(getAddressProvider()).get_registry(); __validateGauge(curveRegistry, pool, incomingStakingToken); (spendAssets_, spendAssetAmounts_) = __parseSpendAssetsForLendingCalls( curveRegistry, pool, orderedOutgoingAssetAmounts, useUnderlyings ); incomingAssets_ = new address[](1); incomingAssets_[0] = incomingStakingToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingStakingTokenAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during redeem() calls function __parseAssetsForRedeem(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( address pool, uint256 outgoingLpTokenAmount, bool useUnderlyings, RedeemType redeemType, bytes memory incomingAssetsData ) = __decodeRedeemCallArgs(_actionData); address curveRegistry = ICurveAddressProvider(getAddressProvider()).get_registry(); address lpToken = ICurveRegistry(curveRegistry).get_lp_token(pool); require(lpToken != address(0), "__parseAssetsForRedeem: Invalid pool"); spendAssets_ = new address[](1); spendAssets_[0] = lpToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLpTokenAmount; (incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls( curveRegistry, pool, useUnderlyings, redeemType, incomingAssetsData ); return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during stake() calls function __parseAssetsForStake(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { (address pool, address incomingStakingToken, uint256 amount) = __decodeStakeCallArgs( _actionData ); // No need to validate pool at this point, as the gauge is validated below address curveRegistry = ICurveAddressProvider(getAddressProvider()).get_registry(); address lpToken = ICurveRegistry(curveRegistry).get_lp_token(pool); __validateGauge(curveRegistry, pool, incomingStakingToken); spendAssets_ = new address[](1); spendAssets_[0] = lpToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingStakingToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during unstake() calls function __parseAssetsForUnstake(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { (address pool, address outgoingStakingToken, uint256 amount) = __decodeUnstakeCallArgs( _actionData ); // No need to validate pool at this point, as the gauge is validated below address curveRegistry = ICurveAddressProvider(getAddressProvider()).get_registry(); address lpToken = ICurveRegistry(curveRegistry).get_lp_token(pool); __validateGauge(curveRegistry, pool, outgoingStakingToken); spendAssets_ = new address[](1); spendAssets_[0] = outgoingStakingToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = lpToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper function to parse spend and incoming assets from encoded call args /// during unstakeAndRedeem() calls function __parseAssetsForUnstakeAndRedeem(bytes calldata _actionData) private view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( address pool, address outgoingStakingToken, uint256 outgoingStakingTokenAmount, bool useUnderlyings, RedeemType redeemType, bytes memory incomingAssetsData ) = __decodeUnstakeAndRedeemCallArgs(_actionData); address curveRegistry = ICurveAddressProvider(getAddressProvider()).get_registry(); __validateGauge(curveRegistry, pool, outgoingStakingToken); spendAssets_ = new address[](1); spendAssets_[0] = outgoingStakingToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStakingTokenAmount; (incomingAssets_, minIncomingAssetAmounts_) = __parseIncomingAssetsForRedemptionCalls( curveRegistry, pool, useUnderlyings, redeemType, incomingAssetsData ); return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Helper to validate a user-input liquidity gauge function __validateGauge( address _curveRegistry, address _pool, address _gauge ) private view { require(_gauge != address(0), "__validateGauge: Empty gauge"); (address[10] memory gauges, ) = ICurveRegistry(_curveRegistry).get_gauges(_pool); bool isValid; for (uint256 i; i < gauges.length; i++) { if (_gauge == gauges[i]) { isValid = true; break; } } require(isValid, "__validateGauge: Invalid gauge"); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../utils/AssetHelpers.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors, AssetHelpers { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _assetData ) { _; (, , address[] memory incomingAssets) = __decodeAssetData(_assetData); __pushFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler(address _vaultProxy, bytes memory _assetData) { _; (address[] memory spendAssets, , ) = __decodeAssetData(_assetData); __pushFullAssetBalances(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper to decode the _assetData param passed to adapter call function __decodeAssetData(bytes memory _assetData) internal pure returns ( address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode(_assetData, (address[], uint256[], address[])); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Rewards bytes4 public constant CLAIM_REWARDS_SELECTOR = bytes4( keccak256("claimRewards(address,bytes,bytes)") ); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../../utils/AssetHelpers.sol"; /// @title CurveGaugeV2ActionsMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin contract for interacting with any Curve LiquidityGaugeV2 contract abstract contract CurveGaugeV2ActionsMixin is AssetHelpers { uint256 private constant CURVE_GAUGE_V2_MAX_REWARDS = 8; /// @dev Helper to claim pool-specific rewards function __curveGaugeV2ClaimRewards(address _gauge, address _target) internal { ICurveLiquidityGaugeV2(_gauge).claim_rewards(_target); } /// @dev Helper to get list of pool-specific rewards tokens function __curveGaugeV2GetRewardsTokens(address _gauge) internal view returns (address[] memory rewardsTokens_) { address[] memory lpRewardsTokensWithEmpties = new address[](CURVE_GAUGE_V2_MAX_REWARDS); uint256 rewardsTokensCount; for (uint256 i; i < CURVE_GAUGE_V2_MAX_REWARDS; i++) { address rewardToken = ICurveLiquidityGaugeV2(_gauge).reward_tokens(i); if (rewardToken != address(0)) { lpRewardsTokensWithEmpties[i] = rewardToken; rewardsTokensCount++; } else { break; } } rewardsTokens_ = new address[](rewardsTokensCount); for (uint256 i; i < rewardsTokensCount; i++) { rewardsTokens_[i] = lpRewardsTokensWithEmpties[i]; } return rewardsTokens_; } /// @dev Helper to stake LP tokens function __curveGaugeV2Stake( address _gauge, address _lpToken, uint256 _amount ) internal { __approveAssetMaxAsNeeded(_lpToken, _gauge, _amount); ICurveLiquidityGaugeV2(_gauge).deposit(_amount, address(this)); } /// @dev Helper to unstake LP tokens function __curveGaugeV2Unstake(address _gauge, uint256 _amount) internal { ICurveLiquidityGaugeV2(_gauge).withdraw(_amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../../interfaces/ICurveMinter.sol"; import "../../../../../utils/AddressArrayLib.sol"; import "./CurveGaugeV2ActionsMixin.sol"; /// @title CurveGaugeV2RewardsHandlerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin contract for handling claiming and reinvesting rewards for a Curve pool /// that uses the LiquidityGaugeV2 contract abstract contract CurveGaugeV2RewardsHandlerMixin is CurveGaugeV2ActionsMixin { using AddressArrayLib for address[]; address private immutable CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN; address private immutable CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER; constructor(address _minter, address _crvToken) public { CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN = _crvToken; CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER = _minter; } /// @dev Helper to claim all rewards (CRV and pool-specific). /// Requires contract to be approved to use mint_for(). function __curveGaugeV2ClaimAllRewards(address _gauge, address _target) internal { // Claim owed $CRV ICurveMinter(CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER).mint_for(_gauge, _target); // Claim owed pool-specific rewards __curveGaugeV2ClaimRewards(_gauge, _target); } /// @dev Helper to get all rewards tokens for staking LP tokens function __curveGaugeV2GetRewardsTokensWithCrv(address _gauge) internal view returns (address[] memory rewardsTokens_) { return __curveGaugeV2GetRewardsTokens(_gauge).addUniqueItem( CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN` variable /// @return crvToken_ The `CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN` variable value function getCurveGaugeV2RewardsHandlerCrvToken() public view returns (address crvToken_) { return CURVE_GAUGE_V2_REWARDS_HANDLER_CRV_TOKEN; } /// @notice Gets the `CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER` variable /// @return minter_ The `CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER` variable value function getCurveGaugeV2RewardsHandlerMinter() public view returns (address minter_) { return CURVE_GAUGE_V2_REWARDS_HANDLER_MINTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/Strings.sol"; import "../../../../../interfaces/IWETH.sol"; import "../../../../../utils/AssetHelpers.sol"; /// @title CurveLiquidityActionsMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin contract for interacting with the Curve pool liquidity functions /// @dev Inheriting contract must have a receive() function if lending or redeeming for the native asset abstract contract CurveLiquidityActionsMixin is AssetHelpers { using Strings for uint256; uint256 private constant ASSET_APPROVAL_TOP_UP_THRESHOLD = 1e76; // Arbitrary, slightly less than 1/11 of max uint256 bytes4 private constant CURVE_REMOVE_LIQUIDITY_ONE_COIN_SELECTOR = 0x1a4d01d2; bytes4 private constant CURVE_REMOVE_LIQUIDITY_ONE_COIN_USE_UNDERLYINGS_SELECTOR = 0x517a55a3; address private immutable CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET; constructor(address _wrappedNativeAsset) public { CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET = _wrappedNativeAsset; } /// @dev Helper to add liquidity to the pool. /// _squashedOutgoingAssets are only those pool assets that are actually used to add liquidity, /// which can be verbose and ordered, but it is more gas-efficient to only include non-0 amounts. function __curveAddLiquidity( address _pool, address[] memory _squashedOutgoingAssets, uint256[] memory _orderedOutgoingAssetAmounts, uint256 _minIncomingLpTokenAmount, bool _useUnderlyings ) internal { // Approve and/or unwrap native asset as necessary. // Rather than using exact amounts for approvals, // this tops up to max approval if 1/2 max is reached. uint256 outgoingNativeAssetAmount; for (uint256 i; i < _squashedOutgoingAssets.length; i++) { if (_squashedOutgoingAssets[i] == getCurveLiquidityWrappedNativeAsset()) { // It is never the case that a pool has multiple slots for the same native asset, // so this is not additive outgoingNativeAssetAmount = ERC20(getCurveLiquidityWrappedNativeAsset()).balanceOf( address(this) ); IWETH(getCurveLiquidityWrappedNativeAsset()).withdraw(outgoingNativeAssetAmount); } else { // Once an asset it approved for a given pool, it will almost definitely // never need approval again, but it is topped up to max once an arbitrary // threshold is reached __approveAssetMaxAsNeeded( _squashedOutgoingAssets[i], _pool, ASSET_APPROVAL_TOP_UP_THRESHOLD ); } } // Dynamically call the appropriate selector (bool success, bytes memory returnData) = _pool.call{value: outgoingNativeAssetAmount}( __curveAddLiquidityEncodeCalldata( _orderedOutgoingAssetAmounts, _minIncomingLpTokenAmount, _useUnderlyings ) ); require(success, string(returnData)); } /// @dev Helper to remove liquidity from the pool. /// if using _redeemSingleAsset, must pre-validate that one - and only one - asset /// has a non-zero _orderedMinIncomingAssetAmounts value. function __curveRemoveLiquidity( address _pool, uint256 _outgoingLpTokenAmount, uint256[] memory _orderedMinIncomingAssetAmounts, bool _useUnderlyings ) internal { // Dynamically call the appropriate selector (bool success, bytes memory returnData) = _pool.call( __curveRemoveLiquidityEncodeCalldata( _outgoingLpTokenAmount, _orderedMinIncomingAssetAmounts, _useUnderlyings ) ); require(success, string(returnData)); // Wrap native asset __curveLiquidityWrapNativeAssetBalance(); } /// @dev Helper to remove liquidity from the pool and receive all value owed in one specified token function __curveRemoveLiquidityOneCoin( address _pool, uint256 _outgoingLpTokenAmount, int128 _incomingAssetPoolIndex, uint256 _minIncomingAssetAmount, bool _useUnderlyings ) internal { bytes memory callData; if (_useUnderlyings) { callData = abi.encodeWithSelector( CURVE_REMOVE_LIQUIDITY_ONE_COIN_USE_UNDERLYINGS_SELECTOR, _outgoingLpTokenAmount, _incomingAssetPoolIndex, _minIncomingAssetAmount, true ); } else { callData = abi.encodeWithSelector( CURVE_REMOVE_LIQUIDITY_ONE_COIN_SELECTOR, _outgoingLpTokenAmount, _incomingAssetPoolIndex, _minIncomingAssetAmount ); } // Dynamically call the appropriate selector (bool success, bytes memory returnData) = _pool.call(callData); require(success, string(returnData)); // Wrap native asset __curveLiquidityWrapNativeAssetBalance(); } // PRIVATE FUNCTIONS /// @dev Helper to encode calldata for a call to add liquidity on Curve function __curveAddLiquidityEncodeCalldata( uint256[] memory _orderedOutgoingAssetAmounts, uint256 _minIncomingLpTokenAmount, bool _useUnderlyings ) private pure returns (bytes memory callData_) { bytes memory finalEncodedArgOrEmpty; if (_useUnderlyings) { finalEncodedArgOrEmpty = abi.encode(true); } return abi.encodePacked( __curveAddLiquidityEncodeSelector( _orderedOutgoingAssetAmounts.length, _useUnderlyings ), abi.encodePacked(_orderedOutgoingAssetAmounts), _minIncomingLpTokenAmount, finalEncodedArgOrEmpty ); } /// @dev Helper to encode selector for a call to add liquidity on Curve function __curveAddLiquidityEncodeSelector(uint256 _numberOfCoins, bool _useUnderlyings) private pure returns (bytes4 selector_) { string memory finalArgOrEmpty; if (_useUnderlyings) { finalArgOrEmpty = ",bool"; } return bytes4( keccak256( abi.encodePacked( "add_liquidity(uint256[", _numberOfCoins.toString(), "],", "uint256", finalArgOrEmpty, ")" ) ) ); } /// @dev Helper to wrap the full native asset balance of the current contract function __curveLiquidityWrapNativeAssetBalance() private { uint256 nativeAssetBalance = payable(address(this)).balance; if (nativeAssetBalance > 0) { IWETH(payable(getCurveLiquidityWrappedNativeAsset())).deposit{ value: nativeAssetBalance }(); } } /// @dev Helper to encode calldata for a call to remove liquidity from Curve function __curveRemoveLiquidityEncodeCalldata( uint256 _outgoingLpTokenAmount, uint256[] memory _orderedMinIncomingAssetAmounts, bool _useUnderlyings ) private pure returns (bytes memory callData_) { bytes memory finalEncodedArgOrEmpty; if (_useUnderlyings) { finalEncodedArgOrEmpty = abi.encode(true); } return abi.encodePacked( __curveRemoveLiquidityEncodeSelector( _orderedMinIncomingAssetAmounts.length, _useUnderlyings ), _outgoingLpTokenAmount, abi.encodePacked(_orderedMinIncomingAssetAmounts), finalEncodedArgOrEmpty ); } /// @dev Helper to encode selector for a call to remove liquidity on Curve function __curveRemoveLiquidityEncodeSelector(uint256 _numberOfCoins, bool _useUnderlyings) private pure returns (bytes4 selector_) { string memory finalArgOrEmpty; if (_useUnderlyings) { finalArgOrEmpty = ",bool"; } return bytes4( keccak256( abi.encodePacked( "remove_liquidity(uint256,", "uint256[", _numberOfCoins.toString(), "]", finalArgOrEmpty, ")" ) ) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET` variable /// @return addressProvider_ The `CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET` variable value function getCurveLiquidityWrappedNativeAsset() public view returns (address addressProvider_) { return CURVE_LIQUIDITY_WRAPPED_NATIVE_ASSET; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "../../../../../interfaces/ICurveRegistry.sol"; import "../actions/CurveLiquidityActionsMixin.sol"; import "../AdapterBase.sol"; /// @title CurveLiquidityAdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base adapter for liquidity provision in Curve pools that adhere to pool templates, /// as well as some old pools that have almost the same required interface (e.g., 3pool). /// Implementing contracts can allow staking via Curve gauges, Convex, etc. abstract contract CurveLiquidityAdapterBase is AdapterBase, CurveLiquidityActionsMixin { enum RedeemType {Standard, OneCoin} address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private immutable ADDRESS_PROVIDER; constructor( address _integrationManager, address _addressProvider, address _wrappedNativeAsset ) public AdapterBase(_integrationManager) CurveLiquidityActionsMixin(_wrappedNativeAsset) { ADDRESS_PROVIDER = _addressProvider; } /// @dev Needed to unwrap and receive the native asset receive() external payable {} // INTERNAL FUNCTIONS /// @dev Helper to return the wrappedNativeAsset if the input is the native asset function __castWrappedIfNativeAsset(address _tokenOrNativeAsset) internal view returns (address token_) { if (_tokenOrNativeAsset == ETH_ADDRESS) { return getCurveLiquidityWrappedNativeAsset(); } return _tokenOrNativeAsset; } /// @dev Helper to correctly call the relevant redeem function based on RedeemType function __curveRedeem( address _pool, uint256 _outgoingLpTokenAmount, bool _useUnderlyings, RedeemType _redeemType, bytes memory _incomingAssetsData ) internal { if (_redeemType == RedeemType.OneCoin) { ( uint256 incomingAssetPoolIndex, uint256 minIncomingAssetAmount ) = __decodeIncomingAssetsDataRedeemOneCoin(_incomingAssetsData); __curveRemoveLiquidityOneCoin( _pool, _outgoingLpTokenAmount, int128(incomingAssetPoolIndex), minIncomingAssetAmount, _useUnderlyings ); } else { __curveRemoveLiquidity( _pool, _outgoingLpTokenAmount, __decodeIncomingAssetsDataRedeemStandard(_incomingAssetsData), _useUnderlyings ); } } /// @dev Helper function to parse spend assets for redeem() and unstakeAndRedeem() calls function __parseIncomingAssetsForRedemptionCalls( address _curveRegistry, address _pool, bool _useUnderlyings, RedeemType _redeemType, bytes memory _incomingAssetsData ) internal view returns (address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_) { address[8] memory canonicalPoolAssets; if (_useUnderlyings) { canonicalPoolAssets = ICurveRegistry(_curveRegistry).get_underlying_coins(_pool); } else { canonicalPoolAssets = ICurveRegistry(_curveRegistry).get_coins(_pool); } if (_redeemType == RedeemType.OneCoin) { ( uint256 incomingAssetPoolIndex, uint256 minIncomingAssetAmount ) = __decodeIncomingAssetsDataRedeemOneCoin(_incomingAssetsData); // No need to validate incomingAssetPoolIndex, // as an out-of-bounds index will fail in the call to Curve incomingAssets_ = new address[](1); incomingAssets_[0] = __castWrappedIfNativeAsset( canonicalPoolAssets[incomingAssetPoolIndex] ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { minIncomingAssetAmounts_ = __decodeIncomingAssetsDataRedeemStandard( _incomingAssetsData ); // No need to validate minIncomingAssetAmounts_.length, // as an incorrect length will fail with the wrong n_tokens in the call to Curve incomingAssets_ = new address[](minIncomingAssetAmounts_.length); for (uint256 i; i < incomingAssets_.length; i++) { incomingAssets_[i] = __castWrappedIfNativeAsset(canonicalPoolAssets[i]); } } return (incomingAssets_, minIncomingAssetAmounts_); } /// @dev Helper function to parse spend assets for lend() and lendAndStake() calls function __parseSpendAssetsForLendingCalls( address _curveRegistry, address _pool, uint256[] memory _orderedOutgoingAssetAmounts, bool _useUnderlyings ) internal view returns (address[] memory spendAssets_, uint256[] memory spendAssetAmounts_) { address[8] memory canonicalPoolAssets; if (_useUnderlyings) { canonicalPoolAssets = ICurveRegistry(_curveRegistry).get_underlying_coins(_pool); } else { canonicalPoolAssets = ICurveRegistry(_curveRegistry).get_coins(_pool); } uint256 spendAssetsCount; for (uint256 i; i < _orderedOutgoingAssetAmounts.length; i++) { if (_orderedOutgoingAssetAmounts[i] > 0) { spendAssetsCount++; } } spendAssets_ = new address[](spendAssetsCount); spendAssetAmounts_ = new uint256[](spendAssetsCount); uint256 spendAssetsIndex; for (uint256 i; i < _orderedOutgoingAssetAmounts.length; i++) { if (_orderedOutgoingAssetAmounts[i] > 0) { spendAssets_[spendAssetsIndex] = __castWrappedIfNativeAsset( canonicalPoolAssets[i] ); spendAssetAmounts_[spendAssetsIndex] = _orderedOutgoingAssetAmounts[i]; spendAssetsIndex++; if (spendAssetsIndex == spendAssetsCount) { break; } } } return (spendAssets_, spendAssetAmounts_); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// // Some of these decodings are not relevant to inheriting contracts, // and some parameters will be ignored, but this keeps the payloads // consistent for all inheriting adapters. /// @dev Helper to decode the encoded call arguments for claiming rewards function __decodeClaimRewardsCallArgs(bytes memory _actionData) internal pure returns (address stakingToken_) { return abi.decode(_actionData, (address)); } /// @dev Helper to decode the encoded call arguments for lending and then staking function __decodeLendAndStakeCallArgs(bytes memory _actionData) internal pure returns ( address pool_, uint256[] memory orderedOutgoingAssetAmounts_, address incomingStakingToken_, uint256 minIncomingStakingTokenAmount_, bool useUnderlyings_ ) { return abi.decode(_actionData, (address, uint256[], address, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _actionData) internal pure returns ( address pool_, uint256[] memory orderedOutgoingAssetAmounts_, uint256 minIncomingLpTokenAmount_, bool useUnderlyings_ ) { return abi.decode(_actionData, (address, uint256[], uint256, bool)); } /// @dev Helper to decode the encoded call arguments for redeeming function __decodeRedeemCallArgs(bytes memory _actionData) internal pure returns ( address pool_, uint256 outgoingLpTokenAmount_, bool useUnderlyings_, RedeemType redeemType_, bytes memory incomingAssetsData_ ) { return abi.decode(_actionData, (address, uint256, bool, RedeemType, bytes)); } /// @dev Helper to decode the encoded incoming assets arguments for RedeemType.OneCoin function __decodeIncomingAssetsDataRedeemOneCoin(bytes memory _incomingAssetsData) internal pure returns (uint256 incomingAssetPoolIndex_, uint256 minIncomingAssetAmount_) { return abi.decode(_incomingAssetsData, (uint256, uint256)); } /// @dev Helper to decode the encoded incoming assets arguments for RedeemType.Standard function __decodeIncomingAssetsDataRedeemStandard(bytes memory _incomingAssetsData) internal pure returns (uint256[] memory orderedMinIncomingAssetAmounts_) { return abi.decode(_incomingAssetsData, (uint256[])); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _actionData) internal pure returns ( address pool_, address incomingStakingToken_, uint256 amount_ ) { return abi.decode(_actionData, (address, address, uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking and then redeeming function __decodeUnstakeAndRedeemCallArgs(bytes memory _actionData) internal pure returns ( address pool_, address outgoingStakingToken_, uint256 outgoingStakingTokenAmount_, bool useUnderlyings_, RedeemType redeemType_, bytes memory incomingAssetsData_ ) { return abi.decode(_actionData, (address, address, uint256, bool, RedeemType, bytes)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _actionData) internal pure returns ( address pool_, address outgoingStakingToken_, uint256 amount_ ) { return abi.decode(_actionData, (address, address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() public view returns (address addressProvider_) { return ADDRESS_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[email protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityGaugeV2 { function claim_rewards(address) external; function deposit(uint256, address) external; function reward_tokens(uint256) external view returns (address); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveMinter interface /// @author Enzyme Council <[email protected]> interface ICurveMinter { function mint_for(address, address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistry interface /// @author Enzyme Council <[email protected]> interface ICurveRegistry { function get_coins(address) external view returns (address[8] memory); function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); function get_pool_from_lp_token(address) external view returns (address); function get_underlying_coins(address) external view returns (address[8] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { ///////////// // STORAGE // ///////////// /// @dev Helper to remove an item from a storage array function removeStorageItem(address[] storage _self, address _itemToRemove) internal returns (bool removed_) { uint256 itemCount = _self.length; for (uint256 i; i < itemCount; i++) { if (_self[i] == _itemToRemove) { if (i < itemCount - 1) { _self[i] = _self[itemCount - 1]; } _self.pop(); removed_ = true; break; } } return removed_; } //////////// // MEMORY // //////////// /// @dev Helper to add an item to an array. Does not assert uniqueness of the new item. function addItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { nextArray_ = new address[](_self.length + 1); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } nextArray_[_self.length] = _itemToAdd; return nextArray_; } /// @dev Helper to add an item to an array, only if it is not already in the array. function addUniqueItem(address[] memory _self, address _itemToAdd) internal pure returns (address[] memory nextArray_) { if (contains(_self, _itemToAdd)) { return _self; } return addItem(_self, _itemToAdd); } /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to merge the unique items of a second array. /// Does not consider uniqueness of either array, only relative uniqueness. /// Preserves ordering. function mergeArray(address[] memory _self, address[] memory _arrayToMerge) internal pure returns (address[] memory nextArray_) { uint256 newUniqueItemCount; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { newUniqueItemCount++; } } if (newUniqueItemCount == 0) { return _self; } nextArray_ = new address[](_self.length + newUniqueItemCount); for (uint256 i; i < _self.length; i++) { nextArray_[i] = _self[i]; } uint256 nextArrayIndex = _self.length; for (uint256 i; i < _arrayToMerge.length; i++) { if (!contains(_self, _arrayToMerge[i])) { nextArray_[nextArrayIndex] = _arrayToMerge[i]; nextArrayIndex++; } } return nextArray_; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /// @title AssetHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice A util contract for common token actions abstract contract AssetHelpers { using SafeERC20 for ERC20; using SafeMath for uint256; /// @dev Helper to approve a target account with the max amount of an asset. /// This is helpful for fully trusted contracts, such as adapters that /// interact with external protocol like Uniswap, Compound, etc. function __approveAssetMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { uint256 allowance = ERC20(_asset).allowance(address(this), _target); if (allowance < _neededAmount) { if (allowance > 0) { ERC20(_asset).safeApprove(_target, 0); } ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to transfer full asset balances from the current contract to a target function __pushFullAssetBalances(address _target, address[] memory _assets) internal returns (uint256[] memory amountsTransferred_) { amountsTransferred_ = new uint256[](_assets.length); for (uint256 i; i < _assets.length; i++) { ERC20 assetContract = ERC20(_assets[i]); amountsTransferred_[i] = assetContract.balanceOf(address(this)); if (amountsTransferred_[i] > 0) { assetContract.safeTransfer(_target, amountsTransferred_[i]); } } return amountsTransferred_; } }
Helper to decode the encoded call arguments for claiming rewards
function __decodeClaimRewardsCallArgs(bytes memory _actionData) internal pure returns (address stakingToken_) { return abi.decode(_actionData, (address)); }
9,930,855
./full_match/4/0x4631ceDADbF39677f5573A8034Cffc44237916f5/sources/_openzeppelin/contracts/utils/math/Math.sol
Return the log in base 10, following the selected rounding direction, of a positive value. Returns 0 if given 0./
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0); } }
653,999
pragma solidity ^0.4.24; import "zeppelin/token/ERC20/SafeERC20.sol"; import "zeppelin/math/SafeMath.sol"; import "zeppelin/math/Math.sol"; import "./lib/AdditionalMath.sol"; import "contracts/MinersEscrow.sol"; import "contracts/NuCypherToken.sol"; import "contracts/proxy/Upgradeable.sol"; /** * @notice Contract holds policy data and locks fees **/ contract PolicyManager is Upgradeable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using AdditionalMath for int256; using AdditionalMath for uint16; event PolicyCreated( bytes16 indexed policyId, address indexed client ); event PolicyRevoked( bytes16 indexed policyId, address indexed client, uint256 value ); event ArrangementRevoked( bytes16 indexed policyId, address indexed client, address indexed node, uint256 value ); event Withdrawn( address indexed node, address indexed recipient, uint256 value ); event RefundForArrangement( bytes16 indexed policyId, address indexed client, address indexed node, uint256 value ); event RefundForPolicy( bytes16 indexed policyId, address indexed client, uint256 value ); struct ArrangementInfo { address node; uint256 indexOfDowntimePeriods; uint16 lastRefundedPeriod; } struct Policy { address client; // policy for activity periods uint256 rewardRate; uint256 firstPartialReward; uint16 startPeriod; uint16 lastPeriod; bool disabled; ArrangementInfo[] arrangements; } struct NodeInfo { uint256 reward; uint256 rewardRate; uint16 lastMinedPeriod; mapping (uint16 => int256) rewardDelta; uint256 minRewardRate; } bytes16 constant RESERVED_POLICY_ID = bytes16(0); address constant RESERVED_NODE = 0x0; MinersEscrow public escrow; uint32 public secondsPerPeriod; mapping (bytes16 => Policy) public policies; mapping (address => NodeInfo) public nodes; /** * @notice Constructor sets address of the escrow contract * @param _escrow Escrow contract **/ constructor(MinersEscrow _escrow) public { require(address(_escrow) != 0x0); escrow = _escrow; secondsPerPeriod = escrow.secondsPerPeriod(); } /** * @dev Checks that sender is the MinersEscrow contract **/ modifier onlyEscrowContract() { require(msg.sender == address(escrow)); _; } /** * @return Number of current period **/ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @notice Register a node * @param _node Node address * @param _period Initial period **/ function register(address _node, uint16 _period) external onlyEscrowContract { NodeInfo storage nodeInfo = nodes[_node]; require(nodeInfo.lastMinedPeriod == 0); nodeInfo.lastMinedPeriod = _period; } /** * @notice Set the minimum reward that the node will take **/ function setMinRewardRate(uint256 _minRewardRate) public { NodeInfo storage node = nodes[msg.sender]; node.minRewardRate = _minRewardRate; } /** * @notice Create policy by client * @dev Generate policy id before creation. * @dev Formula for reward calculation: numberOfNodes * (firstPartialReward + rewardRate * numberOfPeriods) * @param _policyId Policy id * @param _numberOfPeriods Duration of the policy in periods except first period * @param _firstPartialReward Partial reward for first/current period * @param _nodes Nodes that will handle policy **/ function createPolicy( bytes16 _policyId, uint16 _numberOfPeriods, uint256 _firstPartialReward, address[] _nodes ) public payable { require( _policyId != RESERVED_POLICY_ID && policies[_policyId].rewardRate == 0 && _numberOfPeriods != 0 && msg.value > 0 ); Policy storage policy = policies[_policyId]; policy.client = msg.sender; uint16 currentPeriod = getCurrentPeriod(); policy.startPeriod = currentPeriod.add16(1); policy.lastPeriod = currentPeriod.add16(_numberOfPeriods); policy.rewardRate = msg.value.div(_nodes.length).sub(_firstPartialReward).div(_numberOfPeriods); policy.firstPartialReward = _firstPartialReward; require(policy.rewardRate > _firstPartialReward && (_firstPartialReward + policy.rewardRate * _numberOfPeriods) * _nodes.length == msg.value); uint16 endPeriod = policy.lastPeriod.add16(1); uint256 startReward = policy.rewardRate - _firstPartialReward; for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; require(node != RESERVED_NODE); NodeInfo storage nodeInfo = nodes[node]; require(nodeInfo.lastMinedPeriod != 0 && policy.rewardRate >= nodeInfo.minRewardRate); nodeInfo.rewardDelta[currentPeriod] = nodeInfo.rewardDelta[currentPeriod].add(_firstPartialReward); nodeInfo.rewardDelta[policy.startPeriod] = nodeInfo.rewardDelta[policy.startPeriod] .add(startReward); nodeInfo.rewardDelta[endPeriod] = nodeInfo.rewardDelta[endPeriod].sub(policy.rewardRate); policy.arrangements.push(ArrangementInfo(node, escrow.getPastDowntimeLength(node), 0)); } emit PolicyCreated(_policyId, msg.sender); } /** * @notice Update node reward * @param _node Node address * @param _period Processed period **/ function updateReward(address _node, uint16 _period) external onlyEscrowContract { NodeInfo storage node = nodes[_node]; if (node.lastMinedPeriod == 0 || _period <= node.lastMinedPeriod) { return; } for (uint16 i = node.lastMinedPeriod + 1; i <= _period; i++) { node.rewardRate = node.rewardRate.add(node.rewardDelta[i]); } node.lastMinedPeriod = _period; node.reward = node.reward.add(node.rewardRate); } /** * @notice Withdraw reward by node **/ function withdraw() public returns (uint256) { return withdraw(msg.sender); } /** * @notice Withdraw reward by node * @param _recipient Recipient of the reward **/ function withdraw(address _recipient) public returns (uint256) { NodeInfo storage node = nodes[msg.sender]; uint256 reward = node.reward; require(reward != 0); node.reward = 0; _recipient.transfer(reward); emit Withdrawn(msg.sender, _recipient, reward); return reward; } /** * @notice Calculate amount of refund * @param _policy Policy * @param _arrangement Arrangement **/ function calculateRefundValue(Policy storage _policy, ArrangementInfo storage _arrangement) internal view returns (uint256 refundValue, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod) { uint16 maxPeriod = AdditionalMath.min16(getCurrentPeriod(), _policy.lastPeriod); uint16 minPeriod = AdditionalMath.max16(_policy.startPeriod, _arrangement.lastRefundedPeriod); uint16 downtimePeriods = 0; uint256 length = escrow.getPastDowntimeLength(_arrangement.node); for (indexOfDowntimePeriods = _arrangement.indexOfDowntimePeriods; indexOfDowntimePeriods < length; indexOfDowntimePeriods++) { (uint16 startPeriod, uint16 endPeriod) = escrow.getPastDowntime(_arrangement.node, indexOfDowntimePeriods); if (startPeriod > maxPeriod) { break; } else if (endPeriod < minPeriod) { continue; } downtimePeriods = downtimePeriods.add16( AdditionalMath.min16(maxPeriod, endPeriod) .sub16(AdditionalMath.max16(minPeriod, startPeriod)) .add16(1)); if (maxPeriod <= endPeriod) { break; } } uint16 lastActivePeriod = escrow.getLastActivePeriod(_arrangement.node); if (indexOfDowntimePeriods == length && lastActivePeriod < maxPeriod) { downtimePeriods = downtimePeriods.add16( maxPeriod.sub16(AdditionalMath.max16( minPeriod.sub16(1), lastActivePeriod))); } // check activity for the first period if (_arrangement.lastRefundedPeriod == 0) { if (lastActivePeriod < _policy.startPeriod - 1) { refundValue = _policy.firstPartialReward; } else if (_arrangement.indexOfDowntimePeriods < length) { (startPeriod, endPeriod) = escrow.getPastDowntime( _arrangement.node, _arrangement.indexOfDowntimePeriods); if (_policy.startPeriod > startPeriod && _policy.startPeriod - 1 <= endPeriod) { refundValue = _policy.firstPartialReward; } } } refundValue = refundValue.add(_policy.rewardRate.mul(downtimePeriods)); lastRefundedPeriod = maxPeriod.add16(1); } /** * @notice Revoke/refund arrangement/policy by the client * @param _policyId Policy id * @param _node Node that will be excluded or RESERVED_NODE if full policy should be used ( @param _forceRevoke Force revoke arrangement/policy **/ function refundInternal(bytes16 _policyId, address _node, bool _forceRevoke) internal returns (uint256 refundValue) { Policy storage policy = policies[_policyId]; require(policy.client == msg.sender && !policy.disabled); uint16 endPeriod = policy.lastPeriod.add16(1); uint256 numberOfActive = policy.arrangements.length; for (uint256 i = 0; i < policy.arrangements.length; i++) { ArrangementInfo storage arrangement = policy.arrangements[i]; address node = arrangement.node; if (node == RESERVED_NODE || _node != RESERVED_NODE && _node != node) { numberOfActive--; continue; } uint256 nodeRefundValue; (nodeRefundValue, arrangement.indexOfDowntimePeriods, arrangement.lastRefundedPeriod) = calculateRefundValue(policy, arrangement); if (_forceRevoke) { NodeInfo storage nodeInfo = nodes[node]; nodeInfo.rewardDelta[arrangement.lastRefundedPeriod] = nodeInfo.rewardDelta[arrangement.lastRefundedPeriod].sub(policy.rewardRate); nodeInfo.rewardDelta[endPeriod] = nodeInfo.rewardDelta[endPeriod].add(policy.rewardRate); nodeRefundValue = nodeRefundValue.add( uint256(endPeriod.sub16(arrangement.lastRefundedPeriod)).mul(policy.rewardRate)); } if (_forceRevoke || arrangement.lastRefundedPeriod > policy.lastPeriod) { arrangement.node = RESERVED_NODE; numberOfActive--; emit ArrangementRevoked(_policyId, msg.sender, node, nodeRefundValue); } else { emit RefundForArrangement(_policyId, msg.sender, node, nodeRefundValue); } refundValue = refundValue.add(nodeRefundValue); if (_node != RESERVED_NODE) { break; } } if (refundValue > 0) { msg.sender.transfer(refundValue); } if (_node == RESERVED_NODE) { if (numberOfActive == 0) { policy.disabled = true; emit PolicyRevoked(_policyId, msg.sender, refundValue); } else { emit RefundForPolicy(_policyId, msg.sender, refundValue); } } else { // arrangement not found require(i < policy.arrangements.length); } } /** * @notice Calculate amount of refund * @param _policyId Policy id * @param _node Node or RESERVED_NODE if all nodes should be used **/ function calculateRefundValueInternal(bytes16 _policyId, address _node) internal view returns (uint256 refundValue) { Policy storage policy = policies[_policyId]; require(msg.sender == policy.client && !policy.disabled); for (uint256 i = 0; i < policy.arrangements.length; i++) { ArrangementInfo storage arrangement = policy.arrangements[i]; if (arrangement.node == RESERVED_NODE || _node != RESERVED_NODE && _node != arrangement.node) { continue; } (uint256 nodeRefundValue,,) = calculateRefundValue(policy, arrangement); refundValue = refundValue.add(nodeRefundValue); if (_node != RESERVED_NODE) { break; } } if (_node != RESERVED_NODE) { // arrangement not found require(i < policy.arrangements.length); } } /** * @notice Revoke policy by client * @param _policyId Policy id **/ function revokePolicy(bytes16 _policyId) public { refundInternal(_policyId, RESERVED_NODE, true); } /** * @notice Revoke arrangement by client * @param _policyId Policy id * @param _node Node that will be excluded **/ function revokeArrangement(bytes16 _policyId, address _node) public returns (uint256 refundValue) { require(_node != RESERVED_NODE); return refundInternal(_policyId, _node, true); } /** * @notice Refund part of fee by client * @param _policyId Policy id **/ function refund(bytes16 _policyId) public { refundInternal(_policyId, RESERVED_NODE, false); } /** * @notice Refund part of one node's fee by client * @param _policyId Policy id * @param _node Node address **/ function refund(bytes16 _policyId, address _node) public returns (uint256 refundValue) { require(_node != RESERVED_NODE); return refundInternal(_policyId, _node, false); } /** * @notice Calculate amount of refund * @param _policyId Policy id **/ function calculateRefundValue(bytes16 _policyId) external view returns (uint256 refundValue) { return calculateRefundValueInternal(_policyId, RESERVED_NODE); } /** * @notice Calculate amount of refund * @param _policyId Policy id * @param _node Node **/ function calculateRefundValue(bytes16 _policyId, address _node) external view returns (uint256 refundValue) { require(_node != RESERVED_NODE); return calculateRefundValueInternal(_policyId, _node); } /** * @notice Get number of arrangements in the policy * @param _policyId Policy id **/ function getArrangementsLength(bytes16 _policyId) public view returns (uint256) { return policies[_policyId].arrangements.length; } /** * @notice Get information about node reward * @param _node Address of node * @param _period Period to get reward delta **/ function getNodeRewardDelta(address _node, uint16 _period) public view returns (int256) { return nodes[_node].rewardDelta[_period]; } /** * @notice Return the information about arrangement **/ function getArrangementInfo(bytes16 _policyId, uint256 _index) // TODO change to structure when ABIEncoderV2 is released // public view returns (ArrangementInfo) public view returns (address node, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod) { ArrangementInfo storage info = policies[_policyId].arrangements[_index]; node = info.node; indexOfDowntimePeriods = info.indexOfDowntimePeriods; lastRefundedPeriod = info.lastRefundedPeriod; } /** * @dev Get Policy structure by delegatecall **/ function delegateGetPolicy(address _target, bytes16 _policyId) internal returns (Policy memory result) { bytes32 memoryAddress = delegateGetData(_target, "policies(bytes16)", 1, bytes32(_policyId), 0); assembly { result := memoryAddress } } /** * @dev Get ArrangementInfo structure by delegatecall **/ function delegateGetArrangementInfo(address _target, bytes16 _policyId, uint256 _index) internal returns (ArrangementInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, "getArrangementInfo(bytes16,uint256)", 2, bytes32(_policyId), bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get NodeInfo structure by delegatecall **/ function delegateGetNodeInfo(address _target, address _node) internal returns (NodeInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, "nodes(address)", 1, bytes32(_node), 0); assembly { result := memoryAddress } } function verifyState(address _testTarget) public onlyOwner { require(address(delegateGet(_testTarget, "escrow()")) == address(escrow)); require(uint32(delegateGet(_testTarget, "secondsPerPeriod()")) == secondsPerPeriod); Policy storage policy = policies[RESERVED_POLICY_ID]; Policy memory policyToCheck = delegateGetPolicy(_testTarget, RESERVED_POLICY_ID); require(policyToCheck.client == policy.client && policyToCheck.rewardRate == policy.rewardRate && policyToCheck.firstPartialReward == policy.firstPartialReward && policyToCheck.startPeriod == policy.startPeriod && policyToCheck.lastPeriod == policy.lastPeriod && policyToCheck.disabled == policy.disabled); require(uint256(delegateGet(_testTarget, "getArrangementsLength(bytes16)", RESERVED_POLICY_ID)) == policy.arrangements.length); ArrangementInfo storage arrangement = policy.arrangements[0]; ArrangementInfo memory arrangementToCheck = delegateGetArrangementInfo( _testTarget, RESERVED_POLICY_ID, 0); require(arrangementToCheck.node == arrangement.node && arrangementToCheck.indexOfDowntimePeriods == arrangement.indexOfDowntimePeriods && arrangementToCheck.lastRefundedPeriod == arrangement.lastRefundedPeriod); NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; NodeInfo memory nodeInfoToCheck = delegateGetNodeInfo(_testTarget, RESERVED_NODE); require(nodeInfoToCheck.reward == nodeInfo.reward && nodeInfoToCheck.rewardRate == nodeInfo.rewardRate && nodeInfoToCheck.lastMinedPeriod == nodeInfo.lastMinedPeriod && nodeInfoToCheck.minRewardRate == nodeInfo.minRewardRate); require(int256(delegateGet(_testTarget, "getNodeRewardDelta(address,uint16)", bytes32(RESERVED_NODE), 11)) == nodeInfo.rewardDelta[11]); } function finishUpgrade(address _target) public onlyOwner { PolicyManager policyManager = PolicyManager(_target); escrow = policyManager.escrow(); secondsPerPeriod = policyManager.secondsPerPeriod(); // Create fake Policy and NodeInfo to use them in verifyState(address) Policy storage policy = policies[RESERVED_POLICY_ID]; policy.client = owner; policy.startPeriod = 1; policy.lastPeriod = 2; policy.rewardRate = 3; policy.firstPartialReward = 4; policy.disabled = true; policy.arrangements.push(ArrangementInfo(RESERVED_NODE, 11, 22)); NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; nodeInfo.reward = 100; nodeInfo.rewardRate = 33; nodeInfo.lastMinedPeriod = 44; nodeInfo.rewardDelta[11] = 55; nodeInfo.minRewardRate = 777; } }
Get information about node reward _node Address of node _period Period to get reward delta/
function getNodeRewardDelta(address _node, uint16 _period) public view returns (int256) { return nodes[_node].rewardDelta[_period]; }
889,804
/* .'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''.. .;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,. ';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,. ';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,. ...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''.. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. ..... .;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,. .,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,. .,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,.. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. .... ..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. ..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'. ...'.. .';;;;;;;;;;;;;;,,,'. ............... */ // https://github.com/trusttoken/smart-contracts // Dependency file: contracts/truefi/common/Initializable.sol // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // SPDX-License-Identifier: MIT // pragma solidity 0.6.10; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // Dependency file: contracts/truefi/interface/ILoanFactory.sol // pragma solidity 0.6.10; interface ILoanFactory { function createLoanToken( uint256 _amount, uint256 _term, uint256 _apy ) external; function isLoanToken(address) external view returns (bool); } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency 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; } } // Dependency 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); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/ERC20.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/GSN/Context.sol"; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // Dependency file: contracts/truefi/interface/ILoanToken.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface ILoanToken is IERC20 { enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated} function borrower() external view returns (address); function amount() external view returns (uint256); function term() external view returns (uint256); function apy() external view returns (uint256); function start() external view returns (uint256); function lender() external view returns (address); function debt() external view returns (uint256); function profit() external view returns (uint256); function status() external view returns (Status); function borrowerFee() external view returns (uint256); function receivedAmount() external view returns (uint256); function isLoanToken() external pure returns (bool); function getParameters() external view returns ( uint256, uint256, uint256 ); function fund() external; function withdraw(address _beneficiary) external; function close() external; function liquidate() external; function redeem(uint256 _amount) external; function repay(address _sender, uint256 _amount) external; function reclaim() external; function allowTransfer(address account, bool _status) external; function repaid() external view returns (uint256); function balance() external view returns (uint256); function value(uint256 _balance) external view returns (uint256); function currencyToken() external view returns (IERC20); function version() external pure returns (uint8); } // Dependency file: contracts/truefi/LoanToken.sol // pragma solidity 0.6.10; // import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {ILoanToken} from "contracts/truefi/interface/ILoanToken.sol"; /** * @title LoanToken * @dev A token which represents share of a debt obligation * * Each LoanToken has: * - borrower address * - borrow amount * - loan term * - loan APY * * Loan progresses through the following states: * Awaiting: Waiting for funding to meet capital requirements * Funded: Capital requirements met, borrower can withdraw * Withdrawn: Borrower withdraws money, loan waiting to be repaid * Settled: Loan has been paid back in full with interest * Defaulted: Loan has not been paid back in full * Liquidated: Loan has Defaulted and stakers have been Liquidated * * - LoanTokens are non-transferable except for whitelisted addresses * - This version of LoanToken only supports a single funder */ contract LoanToken is ILoanToken, ERC20 { using SafeMath for uint256; uint128 public constant lastMinutePaybackDuration = 1 days; uint8 public constant override version = 3; address public override borrower; address public liquidator; uint256 public override amount; uint256 public override term; uint256 public override apy; uint256 public override start; address public override lender; uint256 public override debt; uint256 public redeemed; // borrow fee -> 25 = 0.25% uint256 public override borrowerFee = 25; // whitelist for transfers mapping(address => bool) public canTransfer; Status public override status; IERC20 public override currencyToken; /** * @dev Emitted when the loan is funded * @param lender Address which funded the loan */ event Funded(address lender); /** * @dev Emitted when transfer whitelist is updated * @param account Account to whitelist for transfers * @param status New whitelist status */ event TransferAllowanceChanged(address account, bool status); /** * @dev Emitted when borrower withdraws funds * @param beneficiary Account which will receive funds */ event Withdrawn(address beneficiary); /** * @dev Emitted when term is over * @param status Final loan status * @param returnedAmount Amount that was returned before expiry */ event Closed(Status status, uint256 returnedAmount); /** * @dev Emitted when a LoanToken is redeemed for underlying currencyTokens * @param receiver Receiver of currencyTokens * @param burnedAmount Amount of LoanTokens burned * @param redeemedAmount Amount of currencyToken received */ event Redeemed(address receiver, uint256 burnedAmount, uint256 redeemedAmount); /** * @dev Emitted when a LoanToken is repaid by the borrower in underlying currencyTokens * @param repayer Sender of currencyTokens * @param repaidAmount Amount of currencyToken repaid */ event Repaid(address repayer, uint256 repaidAmount); /** * @dev Emitted when borrower reclaims remaining currencyTokens * @param borrower Receiver of remaining currencyTokens * @param reclaimedAmount Amount of currencyTokens repaid */ event Reclaimed(address borrower, uint256 reclaimedAmount); /** * @dev Emitted when loan gets liquidated * @param status Final loan status */ event Liquidated(Status status); /** * @dev Create a Loan * @param _currencyToken Token to lend * @param _borrower Borrower address * @param _amount Borrow amount of currency tokens * @param _term Loan length * @param _apy Loan APY */ constructor( IERC20 _currencyToken, address _borrower, address _lender, address _liquidator, uint256 _amount, uint256 _term, uint256 _apy ) public ERC20("Loan Token", "LOAN") { require(_lender != address(0), "LoanToken: Lender is not set"); currencyToken = _currencyToken; borrower = _borrower; liquidator = _liquidator; amount = _amount; term = _term; apy = _apy; lender = _lender; debt = interest(amount); } /** * @dev Only borrower can withdraw & repay loan */ modifier onlyBorrower() { require(msg.sender == borrower, "LoanToken: Caller is not the borrower"); _; } /** * @dev Only liquidator can liquidate */ modifier onlyLiquidator() { require(msg.sender == liquidator, "LoanToken: Caller is not the liquidator"); _; } /** * @dev Only when loan is Settled */ modifier onlyClosed() { require(status >= Status.Settled, "LoanToken: Current status should be Settled or Defaulted"); _; } /** * @dev Only when loan is Funded */ modifier onlyOngoing() { require(status == Status.Funded || status == Status.Withdrawn, "LoanToken: Current status should be Funded or Withdrawn"); _; } /** * @dev Only when loan is Funded */ modifier onlyFunded() { require(status == Status.Funded, "LoanToken: Current status should be Funded"); _; } /** * @dev Only when loan is Withdrawn */ modifier onlyAfterWithdraw() { require(status >= Status.Withdrawn, "LoanToken: Only after loan has been withdrawn"); _; } /** * @dev Only when loan is Awaiting */ modifier onlyAwaiting() { require(status == Status.Awaiting, "LoanToken: Current status should be Awaiting"); _; } /** * @dev Only when loan is Defaulted */ modifier onlyDefaulted() { require(status == Status.Defaulted, "LoanToken: Current status should be Defaulted"); _; } /** * @dev Only whitelisted accounts or lender */ modifier onlyWhoCanTransfer(address sender) { require( sender == lender || canTransfer[sender], "LoanToken: This can be performed only by lender or accounts allowed to transfer" ); _; } /** * @dev Only lender can perform certain actions */ modifier onlyLender() { require(msg.sender == lender, "LoanToken: This can be performed only by lender"); _; } /** * @dev Return true if this contract is a LoanToken * @return True if this contract is a LoanToken */ function isLoanToken() external override pure returns (bool) { return true; } /** * @dev Get loan parameters * @return amount, term, apy */ function getParameters() external override view returns ( uint256, uint256, uint256 ) { return (amount, apy, term); } /** * @dev Get coupon value of this loan token in currencyToken * This assumes the loan will be paid back on time, with interest * @param _balance number of LoanTokens to get value for * @return coupon value of _balance LoanTokens in currencyTokens */ function value(uint256 _balance) external override view returns (uint256) { if (_balance == 0) { return 0; } uint256 passed = block.timestamp.sub(start); if (passed > term) { passed = term; } // assume year is 365 days uint256 interest = amount.mul(apy).mul(passed).div(365 days).div(10000); return amount.add(interest).mul(_balance).div(debt); } /** * @dev Fund a loan * Set status, start time, lender */ function fund() external override onlyAwaiting onlyLender { status = Status.Funded; start = block.timestamp; _mint(msg.sender, debt); require(currencyToken.transferFrom(msg.sender, address(this), receivedAmount())); emit Funded(msg.sender); } /** * @dev Whitelist accounts to transfer * @param account address to allow transfers for * @param _status true allows transfers, false disables transfers */ function allowTransfer(address account, bool _status) external override onlyLender { canTransfer[account] = _status; emit TransferAllowanceChanged(account, _status); } /** * @dev Borrower calls this function to withdraw funds * Sets the status of the loan to Withdrawn * @param _beneficiary address to send funds to */ function withdraw(address _beneficiary) external override onlyBorrower onlyFunded { status = Status.Withdrawn; require(currencyToken.transfer(_beneficiary, receivedAmount())); emit Withdrawn(_beneficiary); } /** * @dev Close the loan and check if it has been repaid */ function close() external override onlyOngoing { require(start.add(term) <= block.timestamp, "LoanToken: Loan cannot be closed yet"); if (_balance() >= debt) { status = Status.Settled; } else { require( start.add(term).add(lastMinutePaybackDuration) <= block.timestamp, "LoanToken: Borrower can still pay the loan back" ); status = Status.Defaulted; } emit Closed(status, _balance()); } /** * @dev Liquidate the loan if it has defaulted */ function liquidate() external override onlyDefaulted onlyLiquidator { status = Status.Liquidated; emit Liquidated(status); } /** * @dev Redeem LoanToken balances for underlying currencyToken * Can only call this function after the loan is Closed * @param _amount amount to redeem */ function redeem(uint256 _amount) external override onlyClosed { uint256 amountToReturn = _amount.mul(_balance()).div(totalSupply()); redeemed = redeemed.add(amountToReturn); _burn(msg.sender, _amount); require(currencyToken.transfer(msg.sender, amountToReturn)); emit Redeemed(msg.sender, _amount, amountToReturn); } /** * @dev Function for borrower to repay the loan * Borrower can repay at any time * @param _sender account sending currencyToken to repay * @param _amount amount of currencyToken to repay */ function repay(address _sender, uint256 _amount) external override onlyAfterWithdraw { require(_amount <= debt.sub(_balance()), "LoanToken: Cannot repay over the debt"); require(currencyToken.transferFrom(_sender, address(this), _amount)); emit Repaid(_sender, _amount); } /** * @dev Function for borrower to reclaim stuck currencyToken * Can only call this function after the loan is Closed * and all of LoanToken holders have been burnt */ function reclaim() external override onlyClosed onlyBorrower { require(totalSupply() == 0, "LoanToken: Cannot reclaim when LoanTokens are in circulation"); uint256 balanceRemaining = _balance(); require(balanceRemaining > 0, "LoanToken: Cannot reclaim when balance 0"); require(currencyToken.transfer(borrower, balanceRemaining)); emit Reclaimed(borrower, balanceRemaining); } /** * @dev Check how much was already repaid * Funds stored on the contract's address plus funds already redeemed by lenders * @return Uint256 representing what value was already repaid */ function repaid() external override view onlyAfterWithdraw returns (uint256) { return _balance().add(redeemed); } /** * @dev Public currency token balance function * @return currencyToken balance of this contract */ function balance() external override view returns (uint256) { return _balance(); } /** * @dev Get currency token balance for this contract * @return currencyToken balance of this contract */ function _balance() internal view returns (uint256) { return currencyToken.balanceOf(address(this)); } /** * @dev Calculate amount borrowed minus fee * @return Amount minus fees */ function receivedAmount() public override view returns (uint256) { return amount.sub(amount.mul(borrowerFee).div(10000)); } /** * @dev Calculate interest that will be paid by this loan for an amount (returned funds included) * amount + ((amount * apy * term) / (365 days / precision)) * @param _amount amount * @return uint256 Amount of interest paid for _amount */ function interest(uint256 _amount) internal view returns (uint256) { return _amount.add(_amount.mul(apy).mul(term).div(365 days).div(10000)); } /** * @dev get profit for this loan * @return profit for this loan */ function profit() external override view returns (uint256) { return debt.sub(amount); } /** * @dev Override ERC20 _transfer so only whitelisted addresses can transfer * @param sender sender of the transaction * @param recipient recipient of the transaction * @param _amount amount to send */ function _transfer( address sender, address recipient, uint256 _amount ) internal override onlyWhoCanTransfer(sender) { return super._transfer(sender, recipient, _amount); } } // Root file: contracts/truefi/LoanFactory.sol pragma solidity 0.6.10; // import {Initializable} from "contracts/truefi/common/Initializable.sol"; // import {ILoanFactory} from "contracts/truefi/interface/ILoanFactory.sol"; // import {LoanToken, IERC20} from "contracts/truefi/LoanToken.sol"; /** * @title LoanFactory * @notice Deploy LoanTokens with this Contract * @dev LoanTokens are deployed through a factory to ensure that all * LoanTokens adhere to the same contract code, rather than using an interface. */ contract LoanFactory is ILoanFactory, Initializable { // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== IERC20 public currencyToken; // @dev Track Valid LoanTokens mapping(address => bool) public override isLoanToken; address public lender; address public liquidator; // ======= STORAGE DECLARATION END ============ /** * @dev Emitted when a LoanToken is created * @param contractAddress LoanToken contract address */ event LoanTokenCreated(address contractAddress); /** * @dev Initialize this contract and set currency token * @param _currencyToken Currency token to lend */ function initialize(IERC20 _currencyToken) external initializer { currencyToken = _currencyToken; } /** @dev sets lender address **/ function setLender() external { lender = 0x16d02Dc67EB237C387023339356b25d1D54b0922; } /** @dev sets liquidator address **/ function setLiquidator() external { liquidator = 0x76dd4921C99AC6b61b3a98f9fa6f181cA6D70c77; } /** * @dev Deploy LoanToken with parameters * @param _amount Amount to borrow * @param _term Length of loan * @param _apy Loan yield */ function createLoanToken( uint256 _amount, uint256 _term, uint256 _apy ) external override { require(_amount > 0, "LoanFactory: Loans of amount 0, will not be approved"); require(_term > 0, "LoanFactory: Loans cannot have instantaneous term of repay"); address newToken = address(new LoanToken(currencyToken, msg.sender, lender, liquidator, _amount, _term, _apy)); isLoanToken[newToken] = true; emit LoanTokenCreated(newToken); } }
sets lender address /
function setLender() external { lender = 0x16d02Dc67EB237C387023339356b25d1D54b0922; }
5,990,477
./full_match/3/0x83D607F5086d1b779f1f4119b6f545437d0c2Ff5/sources/browser/event_emitter.sol
always returns falseemitterCaller.callDoEmit("blah", {from: "[primary acc]", value: web3.toWei(100, "ether
function callDoEmit(string memory message) public returns (bool){ EventEmitter emitter = EventEmitter(emitter); emit TestEvent("abc"); return emitter.doEmit(message); }
14,215,529
./full_match/97/0xE7feee361e18d5A74fD7eeF35Fe0a4aa83e49CE7/sources/project_/contracts/BEP20.sol
Returns the token symbol./
function symbol() public view returns (string memory){ return tokenSymbol; }
5,020,090
/* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } } contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /// @title LRC Foundation Icebox Program /// @author Daniel Wang - <<span class="__cf_email__" data-cfemail="0c686d626569604c6063637c7e65626b22637e6b">[email&#160;protected]</span>>. /// For more information, please visit https://loopring.org. /// Loopring Foundation&#39;s LRC (20% of total supply) will be locked during the first two years, /// two years later, 1/24 of all locked LRC fund can be unlocked every month. contract LRCFoundationIceboxContract { using SafeMath for uint; uint public constant FREEZE_PERIOD = 720 days; // = 2 years address public lrcTokenAddress = 0x0; address public owner = 0x0; uint public lrcInitialBalance = 0; uint public lrcWithdrawn = 0; uint public lrcUnlockPerMonth = 0; uint public startTime = 0; /* * EVENTS */ /// Emitted when program starts. event Started(uint _time); /// Emitted for each sucuessful deposit. uint public withdrawId = 0; event Withdrawal(uint _withdrawId, uint _lrcAmount); /// @dev Initialize the contract /// @param _lrcTokenAddress LRC ERC20 token address /// @param _owner Owner&#39;s address function LRCFoundationIceboxContract(address _lrcTokenAddress, address _owner) { require(_lrcTokenAddress != address(0)); require(_owner != address(0)); lrcTokenAddress = _lrcTokenAddress; owner = _owner; } /* * PUBLIC FUNCTIONS */ /// @dev start the program. function start() public { require(msg.sender == owner); require(startTime == 0); lrcInitialBalance = Token(lrcTokenAddress).balanceOf(address(this)); require(lrcInitialBalance > 0); lrcUnlockPerMonth = lrcInitialBalance.div(24); // 24 month startTime = now; Started(startTime); } function () payable { require(msg.sender == owner); require(msg.value == 0); require(startTime > 0); require(now > startTime + FREEZE_PERIOD); var token = Token(lrcTokenAddress); uint balance = token.balanceOf(address(this)); require(balance > 0); uint lrcAmount = calculateLRCUnlockAmount(now, balance); if (lrcAmount > 0) { lrcWithdrawn += lrcAmount; Withdrawal(withdrawId++, lrcAmount); require(token.transfer(owner, lrcAmount)); } } /* * INTERNAL FUNCTIONS */ function calculateLRCUnlockAmount(uint _now, uint _balance) internal returns (uint lrcAmount) { uint unlockable = (_now - startTime - FREEZE_PERIOD) .div(30 days) .mul(lrcUnlockPerMonth) - lrcWithdrawn; require(unlockable > 0); if (unlockable > _balance) return _balance; else return unlockable; } }
start the program.
function start() public { require(msg.sender == owner); require(startTime == 0); lrcInitialBalance = Token(lrcTokenAddress).balanceOf(address(this)); require(lrcInitialBalance > 0); startTime = now; Started(startTime); }
6,723,316
pragma solidity 0.5.17; import { IBondedECDSAKeepFactory } from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeepFactory.sol"; /// @title Bonded ECDSA keep factory selection strategy. /// @notice The strategy defines the algorithm for selecting a factory. tBTC /// uses two bonded ECDSA keep factories, selecting one of them for each new /// deposit being opened. interface KeepFactorySelector { /// @notice Selects keep factory for the new deposit. /// @param _seed Request seed. /// @param _keepStakedFactory Regular, KEEP-stake based keep factory. /// @param _fullyBackedFactory Fully backed, ETH-bond-only based keep factory. /// @return The selected keep factory. function selectFactory( uint256 _seed, IBondedECDSAKeepFactory _keepStakedFactory, IBondedECDSAKeepFactory _fullyBackedFactory ) external view returns (IBondedECDSAKeepFactory); } /// @title Bonded ECDSA keep factory selection library. /// @notice tBTC uses two bonded ECDSA keep factories: one based on KEEP stake /// and ETH bond, and another based only on ETH bond. The library holds /// a reference to both factories as well as a reference to a selection strategy /// deciding which factory to choose for the new deposit being opened. library KeepFactorySelection { struct Storage { uint256 requestCounter; IBondedECDSAKeepFactory selectedFactory; KeepFactorySelector factorySelector; // Standard ECDSA keep factory: KEEP stake and ETH bond. // Guaranteed to be set for initialized factory. IBondedECDSAKeepFactory keepStakedFactory; // Fully backed ECDSA keep factory: ETH bond only. IBondedECDSAKeepFactory fullyBackedFactory; } /// @notice Initializes the library with the default KEEP-stake-based /// factory. The default factory is guaranteed to be set and this function /// must be called when creating contract using this library. /// @dev This function can be called only one time. function initialize( Storage storage _self, IBondedECDSAKeepFactory _defaultFactory ) public { require( address(_self.keepStakedFactory) == address(0), "Already initialized" ); _self.keepStakedFactory = IBondedECDSAKeepFactory(_defaultFactory); _self.selectedFactory = _self.keepStakedFactory; } /// @notice Returns the selected keep factory. /// This function guarantees that the same factory is returned for every /// call until selectFactoryAndRefresh is executed. This lets to evaluate /// open keep fee estimate on the same factory that will be used later for /// opening a new keep (fee estimate and open keep requests are two /// separate calls). /// @return Selected keep factory. The same vale will be returned for every /// call of this function until selectFactoryAndRefresh is executed. function selectFactory(Storage storage _self) public view returns (IBondedECDSAKeepFactory) { return _self.selectedFactory; } /// @notice Returns the selected keep factory and refreshes the choice /// for the next select call. The value returned by this function has been /// evaluated during the previous call. This lets to return the same value /// from selectFactory and selectFactoryAndRefresh, thus, allowing to use /// the same factory for which open keep fee estimate was evaluated (fee /// estimate and open keep requests are two separate calls). /// @return Selected keep factory. function selectFactoryAndRefresh(Storage storage _self) external returns (IBondedECDSAKeepFactory) { IBondedECDSAKeepFactory factory = selectFactory(_self); refreshFactory(_self); return factory; } /// @notice Sets the minimum bondable value required from the operator to /// join the sortition pool for tBTC. /// @param _minimumBondableValue The minimum bond value the application /// requires from a single keep. /// @param _groupSize Number of signers in the keep. /// @param _honestThreshold Minimum number of honest keep signers. function setMinimumBondableValue( Storage storage _self, uint256 _minimumBondableValue, uint256 _groupSize, uint256 _honestThreshold ) external { if (address(_self.keepStakedFactory) != address(0)) { _self.keepStakedFactory.setMinimumBondableValue( _minimumBondableValue, _groupSize, _honestThreshold ); } if (address(_self.fullyBackedFactory) != address(0)) { _self.fullyBackedFactory.setMinimumBondableValue( _minimumBondableValue, _groupSize, _honestThreshold ); } } /// @notice Refreshes the keep factory choice. If either ETH-bond-only factory /// or selection strategy is not set, KEEP-stake factory is selected. /// Otherwise, calls selection strategy providing addresses of both /// factories to make a choice. Additionally, passes the selection seed /// evaluated from the current request counter value. function refreshFactory(Storage storage _self) internal { if ( address(_self.fullyBackedFactory) == address(0) || address(_self.factorySelector) == address(0) ) { // KEEP-stake factory is guaranteed to be there. If the selection // can not be performed, this is the default choice. _self.selectedFactory = _self.keepStakedFactory; return; } _self.requestCounter++; uint256 seed = uint256( keccak256(abi.encodePacked(address(this), _self.requestCounter)) ); _self.selectedFactory = _self.factorySelector.selectFactory( seed, _self.keepStakedFactory, _self.fullyBackedFactory ); require( _self.selectedFactory == _self.keepStakedFactory || _self.selectedFactory == _self.fullyBackedFactory, "Factory selector returned unknown factory" ); } /// @notice Sets addresses of the keep factories and the selection strategy /// contracts. /// KeepFactorySelection can work without the keep factory selection /// strategy set, always selecting the default KEEP-stake-based factory. /// Once both fully-backed keep factory and factory selection strategy are /// set, KEEP-stake-based factory is no longer the default choice and it is /// up to the selection strategy to decide which factory should be chosen. /// @dev Can be called multiple times! It's responsibility of a contract /// using this library to limit and protect updates. /// @param _keepStakedFactory Address of the regular, KEEP-stake based keep /// factory. /// @param _fullyBackedFactory Address of the fully-backed, ETH-bond-only based /// keep factory. /// @param _factorySelector Address of the keep factory selection strategy. function setFactories( Storage storage _self, address _keepStakedFactory, address _fullyBackedFactory, address _factorySelector ) internal { require( address(_keepStakedFactory) != address(0), "Invalid KEEP-staked factory address" ); _self.keepStakedFactory = IBondedECDSAKeepFactory(_keepStakedFactory); _self.fullyBackedFactory = IBondedECDSAKeepFactory(_fullyBackedFactory); _self.factorySelector = KeepFactorySelector(_factorySelector); } }
Refreshes the keep factory choice. If either ETH-bond-only factory or selection strategy is not set, KEEP-stake factory is selected. Otherwise, calls selection strategy providing addresses of both factories to make a choice. Additionally, passes the selection seed evaluated from the current request counter value. KEEP-stake factory is guaranteed to be there. If the selection can not be performed, this is the default choice.
function refreshFactory(Storage storage _self) internal { if ( address(_self.fullyBackedFactory) == address(0) || address(_self.factorySelector) == address(0) ) { _self.selectedFactory = _self.keepStakedFactory; return; } _self.requestCounter++; uint256 seed = uint256( keccak256(abi.encodePacked(address(this), _self.requestCounter)) ); _self.selectedFactory = _self.factorySelector.selectFactory( seed, _self.keepStakedFactory, _self.fullyBackedFactory ); require( _self.selectedFactory == _self.keepStakedFactory || _self.selectedFactory == _self.fullyBackedFactory, "Factory selector returned unknown factory" ); }
5,375,184
// SPDX-License-Identifier: MIT pragma solidity 0.6.8; // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // /** * @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"); } } } // /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * * Credit: https://github.com/OpenZeppelin/openzeppelin-upgrades/blob/master/packages/core/contracts/Initializable.sol */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // /** * @notice An account contracted created for each user address. * @dev Anyone can directy deposit assets to the Account contract. * @dev Only operators can withdraw asstes or perform operation from the Account contract. */ contract Account is Initializable { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Asset is withdrawn from the Account. */ event Withdrawn(address indexed tokenAddress, address indexed targetAddress, uint256 amount); /** * @dev Spender is allowed to spend an asset. */ event Approved(address indexed tokenAddress, address indexed targetAddress, uint256 amount); /** * @dev A transaction is invoked on the Account. */ event Invoked(address indexed targetAddress, uint256 value, bytes data); address public owner; mapping(address => bool) public admins; mapping(address => bool) public operators; /** * @dev Initializes the owner, admin and operator roles. * @param _owner Address of the contract owner * @param _initialAdmins The list of addresses that are granted the admin role. */ function initialize(address _owner, address[] memory _initialAdmins) public initializer { owner = _owner; // Grant the admin role to the initial admins for (uint256 i = 0; i < _initialAdmins.length; i++) { admins[_initialAdmins[i]] = true; } } /** * @dev Throws if called by any account that does not have operator role. */ modifier onlyOperator() { require(isOperator(msg.sender), "not operator"); _; } /** * @dev Transfers the ownership of the account to another address. * The new owner can be an zero address which means renouncing the ownership. * @param _owner New owner address */ function transferOwnership(address _owner) public { require(msg.sender == owner, "not owner"); owner = _owner; } /** * @dev Grants admin role to a new address. * @param _account New admin address. */ function grantAdmin(address _account) public { require(msg.sender == owner, "not owner"); require(!admins[_account], "already admin"); admins[_account] = true; } /** * @dev Revokes the admin role from an address. Only owner can revoke admin. * @param _account The admin address to revoke. */ function revokeAdmin(address _account) public { require(msg.sender == owner, "not owner"); require(admins[_account], "not admin"); admins[_account] = false; } /** * @dev Grants operator role to a new address. Only owner or admin can grant operator roles. * @param _account The new operator address. */ function grantOperator(address _account) public { require(msg.sender == owner || admins[msg.sender], "not admin"); require(!operators[_account], "already operator"); operators[_account] = true; } /** * @dev Revoke operator role from an address. Only owner or admin can revoke operator roles. * @param _account The operator address to revoke. */ function revokeOperator(address _account) public { require(msg.sender == owner || admins[msg.sender], "not admin"); require(operators[_account], "not operator"); operators[_account] = false; } /** * @dev Allows Account contract to receive ETH. */ receive() payable external {} /** * @dev Checks whether a user is an operator of the contract. * Since admin role can grant operator role and owner can grant admin role, we treat both * admins and owner as operators! * @param userAddress Address to check whether it's an operator. */ function isOperator(address userAddress) public view returns (bool) { return userAddress == owner || admins[userAddress] || operators[userAddress]; } /** * @dev Withdraws ETH from the Account contract. Only operators can withdraw ETH. * @param targetAddress Address to send the ETH to. * @param amount Amount of ETH to withdraw. */ function withdraw(address payable targetAddress, uint256 amount) public onlyOperator { targetAddress.transfer(amount); // Use address(-1) to represent ETH. emit Withdrawn(address(-1), targetAddress, amount); } /** * @dev Withdraws ERC20 token from the Account contract. Only operators can withdraw ERC20 tokens. * @param tokenAddress Address of the ERC20 to withdraw. * @param targetAddress Address to send the ERC20 to. * @param amount Amount of ERC20 token to withdraw. */ function withdrawToken(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator { IERC20(tokenAddress).safeTransfer(targetAddress, amount); emit Withdrawn(tokenAddress, targetAddress, amount); } /** * @dev Withdraws ERC20 token from the Account contract. If the Account contract does not have sufficient balance, * try to withdraw from the owner's address as well. This is useful if users wants to keep assets in their own wallet * by setting adequate allowance to the Account contract. * @param tokenAddress Address of the ERC20 to withdraw. * @param targetAddress Address to send the ERC20 to. * @param amount Amount of ERC20 token to withdraw. */ function withdrawTokenFallThrough(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator { uint256 tokenBalance = IERC20(tokenAddress).balanceOf(address(this)); // If we have enough token balance, send the token directly. if (tokenBalance >= amount) { IERC20(tokenAddress).safeTransfer(targetAddress, amount); emit Withdrawn(tokenAddress, targetAddress, amount); } else { IERC20(tokenAddress).safeTransferFrom(owner, targetAddress, amount.sub(tokenBalance)); IERC20(tokenAddress).safeTransfer(targetAddress, tokenBalance); emit Withdrawn(tokenAddress, targetAddress, amount); } } /** * @dev Allows the spender address to spend up to the amount of token. * @param tokenAddress Address of the ERC20 that can spend. * @param targetAddress Address which can spend the ERC20. * @param amount Amount of ERC20 that can be spent by the target address. */ function approveToken(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator { IERC20(tokenAddress).safeApprove(targetAddress, 0); IERC20(tokenAddress).safeApprove(targetAddress, amount); emit Approved(tokenAddress, targetAddress, amount); } /** * @notice Performs a generic transaction on the Account contract. * @param target The address for the target contract. * @param value The value of the transaction. * @param data The data of the transaction. */ function invoke(address target, uint256 value, bytes memory data) public onlyOperator returns (bytes memory result) { bool success; (success, result) = target.call{value: value}(data); if (!success) { // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } emit Invoked(target, value, data); } } // /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. * * Credit: https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/Proxy.sol */ abstract contract Proxy { /** * @dev Receive function. * Implemented entirely in `_fallback`. */ receive () payable external { _fallback(); } /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. * * Credit: https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/BaseUpgradeabilityProxy.sol */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), "Implementation not set" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } emit Upgraded(newImplementation); } } // /** * @title AdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. * Credit: https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/BaseAdminUpgradeabilityProxy.sol */ contract AdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); _setAdmin(_admin); } /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function changeImplementation(address newImplementation) external ifAdmin { _setImplementation(newImplementation); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } } // /** * @notice Factory of Account contracts. */ contract AccountFactory { /** * @dev A new Account contract is created. */ event AccountCreated(address indexed userAddress, address indexed accountAddress); address public governance; address public accountBase; mapping(address => address) public accounts; /** * @dev Constructor for Account Factory. * @param _accountBase Base account implementation. */ constructor(address _accountBase) public { require(_accountBase != address(0x0), "account base not set"); governance = msg.sender; accountBase = _accountBase; } /** * @dev Updates the base account implementation. Base account must be set. */ function setAccountBase(address _accountBase) public { require(msg.sender == governance, "not governance"); require(_accountBase != address(0x0), "account base not set"); accountBase = _accountBase; } /** * @dev Updates the govenance address. Governance can be empty address which means * renouncing the governance. */ function setGovernance(address _governance) public { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Creates a new Account contract for the caller. * Users can create multiple accounts by invoking this method multiple times. However, * only the latest one is actively tracked and used by the platform. * @param _initialAdmins The list of addresses that are granted the admin role. */ function createAccount(address[] memory _initialAdmins) public returns (Account) { AdminUpgradeabilityProxy proxy = new AdminUpgradeabilityProxy(accountBase, msg.sender); Account account = Account(address(proxy)); account.initialize(msg.sender, _initialAdmins); accounts[msg.sender] = address(account); emit AccountCreated(msg.sender, address(account)); return account; } } // /** * @notice Interface for ERC20 token which supports minting new tokens. */ interface IERC20Mintable is IERC20 { function mint(address _user, uint256 _amount) external; } // /** * @notice Interface for Strategies. */ interface IStrategy { /** * @dev Returns the token address that the strategy expects. */ function want() external view returns (address); /** * @dev Returns the total amount of tokens deposited in this strategy. */ function balanceOf() external view returns (uint256); /** * @dev Deposits the token to start earning. */ function deposit() external; /** * @dev Withdraws partial funds from the strategy. */ function withdraw(uint256 _amount) external; /** * @dev Withdraws all funds from the strategy. */ function withdrawAll() external returns (uint256); /** * @dev Claims yield and convert it back to want token. */ function harvest() external; } // /** * @notice Interface for controller. */ interface IController { function rewardToken() external returns (address); } // /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // /* * @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 Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // /** * @notice YEarn's style vault which earns yield for a specific token. */ contract Vault is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; address public governance; address public strategy; event Deposited(address indexed user, address indexed token, uint256 amount, uint256 shareAmount); event Withdrawn(address indexed user, address indexed token, uint256 amount, uint256 shareAmount); constructor(string memory _name, string memory _symbol, address _token) public ERC20(_name, _symbol) { token = IERC20(_token); governance = msg.sender; } /** * @dev Returns the total balance in both vault and strategy. */ function balance() public view returns (uint256) { return strategy == address(0x0) ? token.balanceOf(address(this)) : token.balanceOf(address(this)).add(IStrategy(strategy).balanceOf()); } /** * @dev Updates the govenance address. */ function setGovernance(address _governance) public { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Updates the active strategy of the vault. */ function setStrategy(address _strategy) public { require(msg.sender == governance, "not governance"); // This also ensures that _strategy must be a valid strategy contract. require(address(token) == IStrategy(_strategy).want(), "different token"); // If the vault has an existing strategy, withdraw all funds from it. if (strategy != address(0x0)) { IStrategy(strategy).withdrawAll(); } strategy = _strategy; // Starts earning once a new strategy is set. earn(); } /** * @dev Starts earning and deposits all current balance into strategy. */ function earn() public { require(strategy != address(0x0), "no strategy"); uint256 _bal = token.balanceOf(address(this)); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } /** * @dev Deposits all balance to the vault. */ function depositAll() public virtual { deposit(token.balanceOf(msg.sender)); } /** * @dev Deposit some balance to the vault. */ function deposit(uint256 _amount) public virtual { require(_amount > 0, "zero amount"); 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 uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); emit Deposited(msg.sender, address(token), _amount, shares); } /** * @dev Withdraws all balance out of the vault. */ function withdrawAll() public virtual { withdraw(balanceOf(msg.sender)); } /** * @dev Withdraws some balance out of the vault. */ function withdraw(uint256 _shares) public virtual { require(_shares > 0, "zero amount"); uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); // Ideally this should not happen. Put here for extra safety. require(strategy != address(0x0), "no strategy"); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); emit Withdrawn(msg.sender, address(token), r, _shares); } /** * @dev Used to salvage any token deposited into the vault by mistake. * @param _tokenAddress Token address to salvage. * @param _amount Amount of token to salvage. */ function salvage(address _tokenAddress, uint256 _amount) public { require(msg.sender == governance, "not governance"); require(_tokenAddress != address(token), "cannot salvage"); require(_amount > 0, "zero amount"); IERC20(_tokenAddress).safeTransfer(governance, _amount); } /** * @dev Returns the number of vault token per share is worth. */ function getPricePerFullShare() public view returns (uint256) { if (totalSupply() == 0) return 0; return balance().mul(1e18).div(totalSupply()); } } // /** * @notice A vault with rewards. */ contract RewardedVault is Vault { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public controller; uint256 public constant DURATION = 7 days; // Rewards are vested for a fixed duration of 7 days. uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => uint256) public claims; event RewardAdded(address indexed rewardToken, uint256 rewardAmount); event RewardPaid(address indexed rewardToken, address indexed user, uint256 rewardAmount); constructor(string memory _name, string memory _symbol, address _controller, address _vaultToken) public Vault(_name, _symbol, _vaultToken) { require(_controller != address(0x0), "controller not set"); controller = _controller; } /** * @dev Updates the controller address. Controller is responsible for reward distribution. */ function setController(address _controller) public { require(msg.sender == governance, "not governance"); require(_controller != address(0x0), "controller not set"); controller = _controller; } modifier updateReward(address _account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (_account != address(0)) { rewards[_account] = earned(_account); userRewardPerTokenPaid[_account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address _account) public view returns (uint256) { return balanceOf(_account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[_account])) .div(1e18) .add(rewards[_account]); } function deposit(uint256 _amount) public virtual override updateReward(msg.sender) { super.deposit(_amount); } function depositAll() public virtual override updateReward(msg.sender) { super.depositAll(); } function withdraw(uint256 _shares) public virtual override updateReward(msg.sender) { super.withdraw(_shares); } function withdrawAll() public virtual override updateReward(msg.sender) { super.withdrawAll(); } /** * @dev Withdraws all balance and all rewards from the vault. */ function exit() external { withdrawAll(); claimReward(); } /** * @dev Claims all rewards from the vault. */ function claimReward() public updateReward(msg.sender) returns (uint256) { uint256 reward = earned(msg.sender); if (reward > 0) { claims[msg.sender] = claims[msg.sender].add(reward); rewards[msg.sender] = 0; address rewardToken = IController(controller).rewardToken(); IERC20(rewardToken).safeTransfer(msg.sender, reward); emit RewardPaid(rewardToken, msg.sender, reward); } return reward; } /** * @dev Notifies the vault that new reward is added. All rewards will be distributed linearly in 7 days. * @param _reward Amount of reward token to add. */ function notifyRewardAmount(uint256 _reward) public updateReward(address(0)) { require(msg.sender == controller, "not controller"); if (block.timestamp >= periodFinish) { rewardRate = _reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = _reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(IController(controller).rewardToken(), _reward); } } // /** * @notice Controller for vaults. */ contract Controller is IController { using SafeMath for uint256; address public override rewardToken; address public governance; address public reserve; uint256 public numVaults; mapping(uint256 => address) public vaults; constructor(address _rewardToken) public { require(_rewardToken != address(0x0), "reward token not set"); governance = msg.sender; reserve = msg.sender; rewardToken = _rewardToken; } /** * @dev Updates the govenance address. */ function setGovernance(address _governance) public { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Updates the rewards token. */ function setRewardToken(address _rewardToken) public { require(msg.sender == governance, "not governance"); require(_rewardToken != address(0x0), "reward token not set"); rewardToken = _rewardToken; } /** * @dev Updates the reserve address. */ function setReserve(address _reserve) public { require(msg.sender == governance, "not governance"); require(_reserve != address(0x0), "reserve not set"); reserve = _reserve; } /** * @dev Add a new vault to the controller. */ function addVault(address _vault) public { require(msg.sender == governance, "not governance"); require(_vault != address(0x0), "vault not set"); vaults[numVaults++] = _vault; } /** * @dev Add new rewards to a rewarded vault. * @param _vaultId ID of the vault to have reward. * @param _rewardAmount Amount of the reward token to add. */ function addRewards(uint256 _vaultId, uint256 _rewardAmount) public { require(msg.sender == governance, "not governance"); require(vaults[_vaultId] != address(0x0), "vault not exist"); require(_rewardAmount > 0, "zero amount"); address vault = vaults[_vaultId]; IERC20Mintable(rewardToken).mint(vault, _rewardAmount); // Mint 40% of tokens to governance. IERC20Mintable(rewardToken).mint(reserve, _rewardAmount.mul(2).div(5)); RewardedVault(vault).notifyRewardAmount(_rewardAmount); } /** * @dev Helpher function to earn in the vault. * @param _vaultId ID of the vault to earn. */ function earn(uint256 _vaultId) public { require(vaults[_vaultId] != address(0x0), "vault not exist"); RewardedVault(vaults[_vaultId]).earn(); } /** * @dev Helper function to earn in all vaults. */ function earnAll() public { for (uint256 i = 0; i < numVaults; i++) { RewardedVault(vaults[i]).earn(); } } /** * @dev Helper function to harvest in the vault. * @param _vaultId ID of the vault to harvest. */ function harvest(uint256 _vaultId) public { require(vaults[_vaultId] != address(0x0), "vault not exist"); address strategy = RewardedVault(vaults[_vaultId]).strategy(); if (strategy != address(0x0)) { IStrategy(strategy).harvest(); } } /** * @dev Helper function to harvest in all vaults. */ function harvestAll() public { for (uint256 i = 0; i < numVaults; i++) { address strategy = RewardedVault(vaults[i]).strategy(); if (strategy != address(0x0)) { IStrategy(strategy).harvest(); } } } } // /** * @dev Application to help stake and get rewards. */ contract StakingApplication { using SafeMath for uint256; event Staked(address indexed staker, uint256 indexed vaultId, address indexed token, uint256 amount); event Unstaked(address indexed staker, uint256 indexed vaultId, address indexed token, uint256 amount); event Claimed(address indexed staker, uint256 indexed vaultId, address indexed token, uint256 amount); address public governance; address public accountFactory; Controller public controller; constructor(address _accountFactory, address _controller) public { require(_accountFactory != address(0x0), "account factory not set"); require(_controller != address(0x0), "controller not set"); governance = msg.sender; accountFactory = _accountFactory; controller = Controller(_controller); } /** * @dev Updates the govenance address. */ function setGovernance(address _governance) public { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Updates the account factory. */ function setAccountFactory(address _accountFactory) public { require(msg.sender == governance, "not governance"); require(_accountFactory != address(0x0), "account factory not set"); accountFactory = _accountFactory; } /** * @dev Updates the controller address. */ function setController(address _controller) public { require(msg.sender == governance, "not governance"); require(_controller != address(0x0), "controller not set"); controller = Controller(_controller); } /** * @dev Retrieve the active account of the user. */ function _getAccount() internal view returns (Account) { address _account = AccountFactory(accountFactory).accounts(msg.sender); require(_account != address(0x0), "no account"); Account account = Account(payable(_account)); require(account.isOperator(address(this)), "not operator"); return account; } /** * @dev Stake token into rewarded vault. * @param _vaultId ID of the vault to stake. * @param _amount Amount of token to stake. */ function stake(uint256 _vaultId, uint256 _amount) public { address _vault = controller.vaults(_vaultId); require(_vault != address(0x0), "no vault"); require(_amount > 0, "zero amount"); Account account = _getAccount(); RewardedVault vault = RewardedVault(_vault); IERC20 token = vault.token(); account.approveToken(address(token), address(vault), _amount); bytes memory methodData = abi.encodeWithSignature("deposit(uint256)", _amount); account.invoke(address(vault), 0, methodData); emit Staked(msg.sender, _vaultId, address(token), _amount); } /** * @dev Unstake token out of RewardedVault. * @param _vaultId ID of the vault to unstake. * @param _amount Amount of token to unstake. */ function unstake(uint256 _vaultId, uint256 _amount) public { address _vault = controller.vaults(_vaultId); require(_vault != address(0x0), "no vault"); require(_amount > 0, "zero amount"); Account account = _getAccount(); RewardedVault vault = RewardedVault(_vault); IERC20 token = vault.token(); // Important: Need to convert token amount to vault share! uint256 totalBalance = vault.balance(); uint256 totalSupply = vault.totalSupply(); uint256 shares = _amount.mul(totalSupply).div(totalBalance); bytes memory methodData = abi.encodeWithSignature("withdraw(uint256)", shares); account.invoke(address(vault), 0, methodData); emit Unstaked(msg.sender, _vaultId, address(token), _amount); } /** * @dev Unstake all token out of RewardedVault. * @param _vaultId ID of the vault to unstake. */ function unstakeAll(uint256 _vaultId) public { address _vault = controller.vaults(_vaultId); require(_vault != address(0x0), "no vault"); Account account = _getAccount(); RewardedVault vault = RewardedVault(_vault); IERC20 token = vault.token(); uint256 totalBalance = vault.balance(); uint256 totalSupply = vault.totalSupply(); uint256 shares = vault.balanceOf(address(account)); uint256 amount = shares.mul(totalBalance).div(totalSupply); bytes memory methodData = abi.encodeWithSignature("withdraw(uint256)", shares); account.invoke(address(vault), 0, methodData); emit Unstaked(msg.sender, _vaultId, address(token), amount); } /** * @dev Claims rewards from RewardedVault. * @param _vaultId ID of the vault to unstake. */ function claimRewards(uint256 _vaultId) public { address _vault = controller.vaults(_vaultId); require(_vault != address(0x0), "no vault"); Account account = _getAccount(); RewardedVault vault = RewardedVault(_vault); IERC20 rewardToken = IERC20(controller.rewardToken()); bytes memory methodData = abi.encodeWithSignature("claimReward()"); bytes memory methodResult = account.invoke(address(vault), 0, methodData); uint256 claimAmount = abi.decode(methodResult, (uint256)); emit Claimed(msg.sender, _vaultId, address(rewardToken), claimAmount); } /** * @dev Retrieves the amount of token staked in RewardedVault. * @param _vaultId ID of the vault to unstake. */ function getStakeBalance(uint256 _vaultId) public view returns (uint256) { address _vault = controller.vaults(_vaultId); require(_vault != address(0x0), "no vault"); address account = AccountFactory(accountFactory).accounts(msg.sender); require(account != address(0x0), "no account"); RewardedVault vault = RewardedVault(_vault); uint256 totalBalance = vault.balance(); uint256 totalSupply = vault.totalSupply(); uint256 share = vault.balanceOf(account); return totalBalance.mul(share).div(totalSupply); } /** * @dev Returns the total balance of the vault. */ function getVaultBalance(uint256 _vaultId) public view returns (uint256) { address _vault = controller.vaults(_vaultId); require(_vault != address(0x0), "no vault"); RewardedVault vault = RewardedVault(_vault); return vault.balance(); } /** * @dev Return the amount of unclaim rewards. * @param _vaultId ID of the vault to unstake. */ function getUnclaimedReward(uint256 _vaultId) public view returns (uint256) { address _vault = controller.vaults(_vaultId); require(_vault != address(0x0), "no vault"); address account = AccountFactory(accountFactory).accounts(msg.sender); require(account != address(0x0), "no account"); return RewardedVault(_vault).earned(account); } /** * @dev Return the amount of claim rewards. * @param _vaultId ID of the vault to unstake. */ function getClaimedReward(uint256 _vaultId) public view returns (uint256) { address _vault = controller.vaults(_vaultId); require(_vault != address(0x0), "no vault"); address account = AccountFactory(accountFactory).accounts(msg.sender); require(account != address(0x0), "no account"); return RewardedVault(_vault).claims(account); } }
Return the amount of claim rewards. _vaultId ID of the vault to unstake./
function getClaimedReward(uint256 _vaultId) public view returns (uint256) { address _vault = controller.vaults(_vaultId); require(_vault != address(0x0), "no vault"); address account = AccountFactory(accountFactory).accounts(msg.sender); require(account != address(0x0), "no account"); return RewardedVault(_vault).claims(account); }
2,315,554
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/governance/extensions/GovernorTimelockAccess.sol
See {IGovernor-_cancel}/ If the proposal has been scheduled it will have an ETA and we may have to externally cancel Only attempt to cancel if the execution plan included a delay Check first if the current operation nonce is the one that we observed previously. It could already have been cancelled and rescheduled. We don't want to cancel unless it is exactly the instance that we previously scheduled. It is important that all calls have an opportunity to be cancelled. We chose to ignore potential failures of some of the cancel operations to give the other operations a chance to be properly cancelled. In particular cancel might fail if the operation was already cancelled by guardians previously. We don't match on the revert reason to avoid encoding assumptions about specific errors.
function _cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal virtual override returns (uint256) { uint256 proposalId = super._cancel(targets, values, calldatas, descriptionHash); uint48 etaSeconds = SafeCast.toUint48(proposalEta(proposalId)); ExecutionPlan storage plan = _executionPlan[proposalId]; if (etaSeconds != 0) { for (uint256 i = 0; i < targets.length; ++i) { (, bool withDelay, uint32 nonce) = _getManagerData(plan, i); if (withDelay) { bytes32 operationId = _manager.hashOperation(address(this), targets[i], calldatas[i]); if (nonce == _manager.getNonce(operationId)) { } } } } return proposalId; }
8,083,826
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; /** Using For The directive using A for B; can be used to attach library functions (from the library A) to any type (B) in the context of a contract. These functions will receive the object they are called on as their first parameter (like the self variable in Python). The effect of using A for *; is that the functions from the library A are attached to any type. In both situations, all functions in the library are attached, even those where the type of the first parameter does not match the type of the object. The type is checked at the point the function is called and function overload resolution is performed. The using A for B; directive is active only within the current contract, including within all of its functions, and has no effect outside of the contract in which it is used. The directive may only be used inside a contract, not inside any of its functions. */ // We define a new struct datatype thar will be used // to hold its data in the calling contract struct Data { mapping(uint => bool) flags; } library Set { // Note that the first parameter is of type 'storage reference' // and thus only its storage address and not its content is // passed as part if the call // This is a special feature of library functions // It is idiomatic to call the first parameter 'self', // if function can be seen as a method of that object function insert(Data storage self, uint value) public returns (bool) { if (self.flags[value]) return false; // aalready here self.flags[value] = true; return true; } function remove(Data storage self, uint value) public returns (bool) { if (!self.flags[value]) return false; //not there self.flags[value] = false; return true; } function contains(Data storage self, uint value) public view returns (bool) { return self.flags[value]; } } contract C { using Set for Data; Data knownValues; function register(uint value) public { // Here, all variables of type Data have // corresponding member functions // The following function call is identicall // to 'Set.insert(knownValues, value) require(knownValues.insert(value)); } }
Here, all variables of type Data have corresponding member functions The following function call is identicall to 'Set.insert(knownValues, value)
function register(uint value) public { require(knownValues.insert(value)); }
5,493,170
/** Source code of Opium Protocol Web https://opium.network Telegram https://t.me/opium_network Twitter https://twitter.com/opium_network */ // File: LICENSE /** The software and documentation available in this repository (the "Software") is protected by copyright law and accessible pursuant to the license set forth below. Copyright © 2020 Blockeys BV. All rights reserved. Permission is hereby granted, free of charge, to any person or organization obtaining the Software (the “Licensee”) to privately study, review, and analyze the Software. Licensee shall not use the Software for any other purpose. Licensee shall not modify, transfer, assign, share, or sub-license the Software or any derivative works of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 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. */ // File: contracts/Lib/LibDerivative.sol pragma solidity 0.5.16; pragma experimental ABIEncoderV2; /// @title Opium.Lib.LibDerivative contract should be inherited by contracts that use Derivative structure and calculate derivativeHash contract LibDerivative { // Opium derivative structure (ticker) definition struct Derivative { // Margin parameter for syntheticId uint256 margin; // Maturity of derivative uint256 endTime; // Additional parameters for syntheticId uint256[] params; // oracleId of derivative address oracleId; // Margin token address of derivative address token; // syntheticId of derivative address syntheticId; } /// @notice Calculates hash of provided Derivative /// @param _derivative Derivative Instance of derivative to hash /// @return derivativeHash bytes32 Derivative hash function getDerivativeHash(Derivative memory _derivative) public pure returns (bytes32 derivativeHash) { derivativeHash = keccak256(abi.encodePacked( _derivative.margin, _derivative.endTime, _derivative.params, _derivative.oracleId, _derivative.token, _derivative.syntheticId )); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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"); } } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.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. */ contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: erc721o/contracts/Libs/LibPosition.sol pragma solidity ^0.5.4; library LibPosition { function getLongTokenId(bytes32 _hash) public pure returns (uint256 tokenId) { tokenId = uint256(keccak256(abi.encodePacked(_hash, "LONG"))); } function getShortTokenId(bytes32 _hash) public pure returns (uint256 tokenId) { tokenId = uint256(keccak256(abi.encodePacked(_hash, "SHORT"))); } } // File: contracts/Interface/IDerivativeLogic.sol pragma solidity 0.5.16; /// @title Opium.Interface.IDerivativeLogic contract is an interface that every syntheticId should implement contract IDerivativeLogic is LibDerivative { /// @notice Validates ticker /// @param _derivative Derivative Instance of derivative to validate /// @return Returns boolean whether ticker is valid function validateInput(Derivative memory _derivative) public view returns (bool); /// @notice Calculates margin required for derivative creation /// @param _derivative Derivative Instance of derivative /// @return buyerMargin uint256 Margin needed from buyer (LONG position) /// @return sellerMargin uint256 Margin needed from seller (SHORT position) function getMargin(Derivative memory _derivative) public view returns (uint256 buyerMargin, uint256 sellerMargin); /// @notice Calculates payout for derivative execution /// @param _derivative Derivative Instance of derivative /// @param _result uint256 Data retrieved from oracleId on the maturity /// @return buyerPayout uint256 Payout in ratio for buyer (LONG position holder) /// @return sellerPayout uint256 Payout in ratio for seller (SHORT position holder) function getExecutionPayout(Derivative memory _derivative, uint256 _result) public view returns (uint256 buyerPayout, uint256 sellerPayout); /// @notice Returns syntheticId author address for Opium commissions /// @return authorAddress address The address of syntheticId address function getAuthorAddress() public view returns (address authorAddress); /// @notice Returns syntheticId author commission in base of COMMISSION_BASE /// @return commission uint256 Author commission function getAuthorCommission() public view returns (uint256 commission); /// @notice Returns whether thirdparty could execute on derivative's owner's behalf /// @param _derivativeOwner address Derivative owner address /// @return Returns boolean whether _derivativeOwner allowed third party execution function thirdpartyExecutionAllowed(address _derivativeOwner) public view returns (bool); /// @notice Returns whether syntheticId implements pool logic /// @return Returns whether syntheticId implements pool logic function isPool() public view returns (bool); /// @notice Sets whether thirds parties are allowed or not to execute derivative's on msg.sender's behalf /// @param _allow bool Flag for execution allowance function allowThirdpartyExecution(bool _allow) public; // Event with syntheticId metadata JSON string (for DIB.ONE derivative explorer) event MetadataSet(string metadata); } // File: contracts/Errors/CoreErrors.sol pragma solidity 0.5.16; contract CoreErrors { string constant internal ERROR_CORE_NOT_POOL = "CORE:NOT_POOL"; string constant internal ERROR_CORE_CANT_BE_POOL = "CORE:CANT_BE_POOL"; string constant internal ERROR_CORE_TICKER_WAS_CANCELLED = "CORE:TICKER_WAS_CANCELLED"; string constant internal ERROR_CORE_SYNTHETIC_VALIDATION_ERROR = "CORE:SYNTHETIC_VALIDATION_ERROR"; string constant internal ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE = "CORE:NOT_ENOUGH_TOKEN_ALLOWANCE"; string constant internal ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH"; string constant internal ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH"; string constant internal ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED = "CORE:EXECUTION_BEFORE_MATURITY_NOT_ALLOWED"; string constant internal ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED = "CORE:SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED"; string constant internal ERROR_CORE_INSUFFICIENT_POOL_BALANCE = "CORE:INSUFFICIENT_POOL_BALANCE"; string constant internal ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID = "CORE:CANT_CANCEL_DUMMY_ORACLE_ID"; string constant internal ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED = "CORE:CANCELLATION_IS_NOT_ALLOWED"; string constant internal ERROR_CORE_UNKNOWN_POSITION_TYPE = "CORE:UNKNOWN_POSITION_TYPE"; } // File: contracts/Errors/RegistryErrors.sol pragma solidity 0.5.16; contract RegistryErrors { string constant internal ERROR_REGISTRY_ONLY_INITIALIZER = "REGISTRY:ONLY_INITIALIZER"; string constant internal ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED = "REGISTRY:ONLY_OPIUM_ADDRESS_ALLOWED"; string constant internal ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS = "REGISTRY:CANT_BE_ZERO_ADDRESS"; string constant internal ERROR_REGISTRY_ALREADY_SET = "REGISTRY:ALREADY_SET"; } // File: contracts/Registry.sol pragma solidity 0.5.16; /// @title Opium.Registry contract keeps addresses of deployed Opium contracts set to allow them route and communicate to each other contract Registry is RegistryErrors { // Address of Opium.TokenMinter contract address private minter; // Address of Opium.Core contract address private core; // Address of Opium.OracleAggregator contract address private oracleAggregator; // Address of Opium.SyntheticAggregator contract address private syntheticAggregator; // Address of Opium.TokenSpender contract address private tokenSpender; // Address of Opium commission receiver address private opiumAddress; // Address of Opium contract set deployer address public initializer; /// @notice This modifier restricts access to functions, which could be called only by initializer modifier onlyInitializer() { require(msg.sender == initializer, ERROR_REGISTRY_ONLY_INITIALIZER); _; } /// @notice Sets initializer constructor() public { initializer = msg.sender; } // SETTERS /// @notice Sets Opium.TokenMinter, Opium.Core, Opium.OracleAggregator, Opium.SyntheticAggregator, Opium.TokenSpender, Opium commission receiver addresses and allows to do it only once /// @param _minter address Address of Opium.TokenMinter /// @param _core address Address of Opium.Core /// @param _oracleAggregator address Address of Opium.OracleAggregator /// @param _syntheticAggregator address Address of Opium.SyntheticAggregator /// @param _tokenSpender address Address of Opium.TokenSpender /// @param _opiumAddress address Address of Opium commission receiver function init( address _minter, address _core, address _oracleAggregator, address _syntheticAggregator, address _tokenSpender, address _opiumAddress ) external onlyInitializer { require( minter == address(0) && core == address(0) && oracleAggregator == address(0) && syntheticAggregator == address(0) && tokenSpender == address(0) && opiumAddress == address(0), ERROR_REGISTRY_ALREADY_SET ); require( _minter != address(0) && _core != address(0) && _oracleAggregator != address(0) && _syntheticAggregator != address(0) && _tokenSpender != address(0) && _opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS ); minter = _minter; core = _core; oracleAggregator = _oracleAggregator; syntheticAggregator = _syntheticAggregator; tokenSpender = _tokenSpender; opiumAddress = _opiumAddress; } /// @notice Allows opium commission receiver address to change itself /// @param _opiumAddress address New opium commission receiver address function changeOpiumAddress(address _opiumAddress) external { require(opiumAddress == msg.sender, ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED); require(_opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS); opiumAddress = _opiumAddress; } // GETTERS /// @notice Returns address of Opium.TokenMinter /// @param result address Address of Opium.TokenMinter function getMinter() external view returns (address result) { return minter; } /// @notice Returns address of Opium.Core /// @param result address Address of Opium.Core function getCore() external view returns (address result) { return core; } /// @notice Returns address of Opium.OracleAggregator /// @param result address Address of Opium.OracleAggregator function getOracleAggregator() external view returns (address result) { return oracleAggregator; } /// @notice Returns address of Opium.SyntheticAggregator /// @param result address Address of Opium.SyntheticAggregator function getSyntheticAggregator() external view returns (address result) { return syntheticAggregator; } /// @notice Returns address of Opium.TokenSpender /// @param result address Address of Opium.TokenSpender function getTokenSpender() external view returns (address result) { return tokenSpender; } /// @notice Returns address of Opium commission receiver /// @param result address Address of Opium commission receiver function getOpiumAddress() external view returns (address result) { return opiumAddress; } } // File: contracts/Errors/UsingRegistryErrors.sol pragma solidity 0.5.16; contract UsingRegistryErrors { string constant internal ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED = "USING_REGISTRY:ONLY_CORE_ALLOWED"; } // File: contracts/Lib/UsingRegistry.sol pragma solidity 0.5.16; /// @title Opium.Lib.UsingRegistry contract should be inherited by contracts, that are going to use Opium.Registry contract UsingRegistry is UsingRegistryErrors { // Emitted when registry instance is set event RegistrySet(address registry); // Instance of Opium.Registry contract Registry internal registry; /// @notice This modifier restricts access to functions, which could be called only by Opium.Core modifier onlyCore() { require(msg.sender == registry.getCore(), ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED); _; } /// @notice Defines registry instance and emits appropriate event constructor(address _registry) public { registry = Registry(_registry); emit RegistrySet(_registry); } /// @notice Getter for registry variable /// @return address Address of registry set in current contract function getRegistry() external view returns (address) { return address(registry); } } // File: contracts/Lib/LibCommission.sol pragma solidity 0.5.16; /// @title Opium.Lib.LibCommission contract defines constants for Opium commissions contract LibCommission { // Represents 100% base for commissions calculation uint256 constant public COMMISSION_BASE = 10000; // Represents 100% base for Opium commission uint256 constant public OPIUM_COMMISSION_BASE = 10; // Represents which part of `syntheticId` author commissions goes to opium uint256 constant public OPIUM_COMMISSION_PART = 1; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. 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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: erc721o/contracts/Libs/UintArray.sol pragma solidity ^0.5.4; library UintArray { function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } function contains(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } function difference(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { uint256 e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } uint256[] memory newUints = new uint256[](count); uint256[] memory newUintsIdxs = new uint256[](count); uint256 j = 0; for (uint256 i = 0; i < length; i++) { if (includeMap[i]) { newUints[j] = A[i]; newUintsIdxs[j] = i; j++; } } return (newUints, newUintsIdxs); } function intersect(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory, uint256[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } uint256[] memory newUints = new uint256[](newLength); uint256[] memory newUintsAIdxs = new uint256[](newLength); uint256[] memory newUintsBIdxs = new uint256[](newLength); uint256 j = 0; for (uint256 i = 0; i < length; i++) { if (includeMap[i]) { newUints[j] = A[i]; newUintsAIdxs[j] = i; (newUintsBIdxs[j], ) = indexOf(B, A[i]); j++; } } return (newUints, newUintsAIdxs, newUintsBIdxs); } function isUnique(uint256[] memory A) internal pure returns (bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { (uint256 idx, bool isIn) = indexOf(A, A[i]); if (isIn && idx < i) { return false; } } return true; } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @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 () 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) external view 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 { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ 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); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; 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 safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: erc721o/contracts/Interfaces/IERC721O.sol pragma solidity ^0.5.4; contract IERC721O { // Token description function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() public view returns (uint256); function exists(uint256 _tokenId) public view returns (bool); function implementsERC721() public pure returns (bool); function tokenByIndex(uint256 _index) public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri); function getApproved(uint256 _tokenId) public view returns (address); function implementsERC721O() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address _owner); function balanceOf(address owner) public view returns (uint256); function balanceOf(address _owner, uint256 _tokenId) public view returns (uint256); function tokensOwned(address _owner) public view returns (uint256[] memory, uint256[] memory); // Non-Fungible Safe Transfer From function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public; // Non-Fungible Unsafe Transfer From function transferFrom(address _from, address _to, uint256 _tokenId) public; // Fungible Unsafe Transfer function transfer(address _to, uint256 _tokenId, uint256 _quantity) public; // Fungible Unsafe Transfer From function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _quantity) public; // Fungible Safe Transfer From function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public; // Fungible Safe Batch Transfer From function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public; function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data) public; // Fungible Unsafe Batch Transfer From function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public; // Approvals function setApprovalForAll(address _operator, bool _approved) public; function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator); function isApprovedOrOwner(address _spender, address _owner, uint256 _tokenId) public view returns (bool); function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external; // Composable function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public; function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public; function recompose(uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity) public; // Required Events event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event TransferWithQuantity(address indexed from, address indexed to, uint256 indexed tokenId, uint256 quantity); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event BatchTransfer(address indexed from, address indexed to, uint256[] tokenTypes, uint256[] amounts); event Composition(uint256 portfolioId, uint256[] tokenIds, uint256[] tokenRatio); } // File: erc721o/contracts/Interfaces/IERC721OReceiver.sol pragma solidity ^0.5.4; /** * @title ERC721O token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721O contracts. */ contract IERC721OReceiver { /** * @dev Magic value to be returned upon successful reception of an amount of ERC721O tokens * ERC721O_RECEIVED = `bytes4(keccak256("onERC721OReceived(address,address,uint256,uint256,bytes)"))` = 0xf891ffe0 * ERC721O_BATCH_RECEIVED = `bytes4(keccak256("onERC721OBatchReceived(address,address,uint256[],uint256[],bytes)"))` = 0xd0e17c0b */ bytes4 constant internal ERC721O_RECEIVED = 0xf891ffe0; bytes4 constant internal ERC721O_BATCH_RECEIVED = 0xd0e17c0b; function onERC721OReceived( address _operator, address _from, uint256 tokenId, uint256 amount, bytes memory data ) public returns(bytes4); function onERC721OBatchReceived( address _operator, address _from, uint256[] memory _types, uint256[] memory _amounts, bytes memory _data ) public returns (bytes4); } // File: erc721o/contracts/Libs/ObjectsLib.sol pragma solidity ^0.5.4; library ObjectLib { // Libraries using SafeMath for uint256; enum Operations { ADD, SUB, REPLACE } // Constants regarding bin or chunk sizes for balance packing uint256 constant TYPES_BITS_SIZE = 32; // Max size of each object uint256 constant TYPES_PER_UINT256 = 256 / TYPES_BITS_SIZE; // Number of types per uint256 // // Objects and Tokens Functions // /** * @dev Return the bin number and index within that bin where ID is * @param _tokenId Object type * @return (Bin number, ID's index within that bin) */ function getTokenBinIndex(uint256 _tokenId) internal pure returns (uint256 bin, uint256 index) { bin = _tokenId * TYPES_BITS_SIZE / 256; index = _tokenId % TYPES_PER_UINT256; return (bin, index); } /** * @dev update the balance of a type provided in _binBalances * @param _binBalances Uint256 containing the balances of objects * @param _index Index of the object in the provided bin * @param _amount Value to update the type balance * @param _operation Which operation to conduct : * Operations.REPLACE : Replace type balance with _amount * Operations.ADD : ADD _amount to type balance * Operations.SUB : Substract _amount from type balance */ function updateTokenBalance( uint256 _binBalances, uint256 _index, uint256 _amount, Operations _operation) internal pure returns (uint256 newBinBalance) { uint256 objectBalance; if (_operation == Operations.ADD) { objectBalance = getValueInBin(_binBalances, _index); newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.add(_amount)); } else if (_operation == Operations.SUB) { objectBalance = getValueInBin(_binBalances, _index); newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.sub(_amount)); } else if (_operation == Operations.REPLACE) { newBinBalance = writeValueInBin(_binBalances, _index, _amount); } else { revert("Invalid operation"); // Bad operation } return newBinBalance; } /* * @dev return value in _binValue at position _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index index at which to retrieve value * @return Value at given _index in _bin */ function getValueInBin(uint256 _binValue, uint256 _index) internal pure returns (uint256) { // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 rightShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue >> rightShift) & mask; } /** * @dev return the updated _binValue after writing _amount at _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index Index at which to retrieve value * @param _amount Value to store at _index in _bin * @return Value at given _index in _bin */ function writeValueInBin(uint256 _binValue, uint256 _index, uint256 _amount) internal pure returns (uint256) { require(_amount < 2**TYPES_BITS_SIZE, "Amount to write in bin is too large"); // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 leftShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue & ~(mask << leftShift) ) | (_amount << leftShift); } } // File: erc721o/contracts/ERC721OBase.sol pragma solidity ^0.5.4; contract ERC721OBase is IERC721O, ERC165, IERC721 { // Libraries using ObjectLib for ObjectLib.Operations; using ObjectLib for uint256; // Array with all tokenIds uint256[] internal allTokens; // Packed balances mapping(address => mapping(uint256 => uint256)) internal packedTokenBalance; // Operators mapping(address => mapping(address => bool)) internal operators; // Keeps aprovals for tokens from owner to approved address // tokenApprovals[tokenId][owner] = approved mapping (uint256 => mapping (address => address)) internal tokenApprovals; // Token Id state mapping(uint256 => uint256) internal tokenTypes; uint256 constant internal INVALID = 0; uint256 constant internal POSITION = 1; uint256 constant internal PORTFOLIO = 2; // Interface constants bytes4 internal constant INTERFACE_ID_ERC721O = 0x12345678; // EIP712 constants bytes32 public DOMAIN_SEPARATOR; bytes32 public PERMIT_TYPEHASH; // mapping holds nonces for approval permissions // nonces[holder] => nonce mapping (address => uint) public nonces; modifier isOperatorOrOwner(address _from) { require((msg.sender == _from) || operators[_from][msg.sender], "msg.sender is neither _from nor operator"); _; } constructor() public { _registerInterface(INTERFACE_ID_ERC721O); // Calculate EIP712 constants DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,address verifyingContract)"), keccak256(bytes("ERC721o")), keccak256(bytes("1")), address(this) )); PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); } function implementsERC721O() public pure returns (bool) { return true; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { return tokenTypes[_tokenId] != INVALID; } /** * @dev return the _tokenId type' balance of _address * @param _address Address to query balance of * @param _tokenId type to query balance of * @return Amount of objects of a given type ID */ function balanceOf(address _address, uint256 _tokenId) public view returns (uint256) { (uint256 bin, uint256 index) = _tokenId.getTokenBinIndex(); return packedTokenBalance[_address][bin].getValueInBin(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 Iterate through the list of existing tokens and return the indexes * and balances of the tokens owner by the user * @param _owner The adddress we are checking * @return indexes The tokenIds * @return balances The balances of each token */ function tokensOwned(address _owner) public view returns (uint256[] memory indexes, uint256[] memory balances) { uint256 numTokens = totalSupply(); uint256[] memory tokenIndexes = new uint256[](numTokens); uint256[] memory tempTokens = new uint256[](numTokens); uint256 count; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = allTokens[i]; if (balanceOf(_owner, tokenId) > 0) { tempTokens[count] = balanceOf(_owner, tokenId); tokenIndexes[count] = tokenId; count++; } } // copy over the data to a correct size array uint256[] memory _ownedTokens = new uint256[](count); uint256[] memory _ownedTokensIndexes = new uint256[](count); for (uint256 i = 0; i < count; i++) { _ownedTokens[i] = tempTokens[i]; _ownedTokensIndexes[i] = tokenIndexes[i]; } return (_ownedTokensIndexes, _ownedTokens); } /** * @dev Will set _operator operator status to true or false * @param _operator Address to changes operator status. * @param _approved _operator's new operator status (true or false) */ function setApprovalForAll(address _operator, bool _approved) public { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Approve for all by signature function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external { // Calculate hash bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode( PERMIT_TYPEHASH, _holder, _spender, _nonce, _expiry, _allowed )) )); // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly bytes32 r; bytes32 s; uint8 v; bytes memory signature = _signature; assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } address recoveredAddress; // If the version is correct return the signer address if (v != 27 && v != 28) { recoveredAddress = address(0); } else { // solium-disable-next-line arg-overflow recoveredAddress = ecrecover(digest, v, r, s); } require(_holder != address(0), "Holder can't be zero address"); require(_holder == recoveredAddress, "Signer address is invalid"); require(_expiry == 0 || now <= _expiry, "Permission expired"); require(_nonce == nonces[_holder]++, "Nonce is invalid"); // Update operator status operators[_holder][_spender] = _allowed; emit ApprovalForAll(_holder, _spender, _allowed); } /** * @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 { require(_to != msg.sender, "Can't approve to yourself"); tokenApprovals[_tokenId][msg.sender] = _to; emit Approval(msg.sender, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address) { return tokenApprovals[_tokenId][_tokenOwner]; } /** * @dev Function that verifies whether _operator is an authorized operator of _tokenHolder. * @param _operator The address of the operator to query status of * @param _owner Address of the tokenHolder * @return A uint256 specifying the amount of tokens still available for the spender. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { return operators[_owner][_operator]; } function isApprovedOrOwner( address _spender, address _owner, uint256 _tokenId ) public view returns (bool) { return ( _spender == _owner || getApproved(_tokenId, _owner) == _spender || isApprovedForAll(_owner, _spender) ); } function _updateTokenBalance( address _from, uint256 _tokenId, uint256 _amount, ObjectLib.Operations op ) internal { (uint256 bin, uint256 index) = _tokenId.getTokenBinIndex(); packedTokenBalance[_from][bin] = packedTokenBalance[_from][bin].updateTokenBalance( index, _amount, op ); } } // File: erc721o/contracts/ERC721OTransferable.sol pragma solidity ^0.5.4; contract ERC721OTransferable is ERC721OBase, ReentrancyGuard { // Libraries using Address for address; // safeTransfer constants bytes4 internal constant ERC721O_RECEIVED = 0xf891ffe0; bytes4 internal constant ERC721O_BATCH_RECEIVED = 0xd0e17c0b; function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public { // Batch Transfering _batchTransferFrom(_from, _to, _tokenIds, _amounts); } /** * @dev transfer objects from different tokenIds to specified address * @param _from The address to BatchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _tokenIds Array of tokenIds to update balance of * @param _amounts Array of amount of object per type to be transferred. * @param _data Data to pass to onERC721OReceived() function if recipient is contract * Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient). */ function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data ) public nonReentrant { // Batch Transfering _batchTransferFrom(_from, _to, _tokenIds, _amounts); // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC721OReceiver(_to).onERC721OBatchReceived( msg.sender, _from, _tokenIds, _amounts, _data ); require(retval == ERC721O_BATCH_RECEIVED); } } function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts ) public { safeBatchTransferFrom(_from, _to, _tokenIds, _amounts, ""); } function transfer(address _to, uint256 _tokenId, uint256 _amount) public { _transferFrom(msg.sender, _to, _tokenId, _amount); } function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public { _transferFrom(_from, _to, _tokenId, _amount); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public { safeTransferFrom(_from, _to, _tokenId, _amount, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public nonReentrant { _transferFrom(_from, _to, _tokenId, _amount); require( _checkAndCallSafeTransfer(_from, _to, _tokenId, _amount, _data), "Sent to a contract which is not an ERC721O receiver" ); } /** * @dev transfer objects from different tokenIds to specified address * @param _from The address to BatchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _tokenIds Array of tokenIds to update balance of * @param _amounts Array of amount of object per type to be transferred. * Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient). */ function _batchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts ) internal isOperatorOrOwner(_from) { // Requirements require(_tokenIds.length == _amounts.length, "Inconsistent array length between args"); require(_to != address(0), "Invalid to address"); // Number of transfers to execute uint256 nTransfer = _tokenIds.length; // Don't do useless calculations if (_from == _to) { for (uint256 i = 0; i < nTransfer; i++) { emit Transfer(_from, _to, _tokenIds[i]); emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]); } return; } for (uint256 i = 0; i < nTransfer; i++) { require(_amounts[i] <= balanceOf(_from, _tokenIds[i]), "Quantity greater than from balance"); _updateTokenBalance(_from, _tokenIds[i], _amounts[i], ObjectLib.Operations.SUB); _updateTokenBalance(_to, _tokenIds[i], _amounts[i], ObjectLib.Operations.ADD); emit Transfer(_from, _to, _tokenIds[i]); emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]); } // Emit batchTransfer event emit BatchTransfer(_from, _to, _tokenIds, _amounts); } function _transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) internal { require(isApprovedOrOwner(msg.sender, _from, _tokenId), "Not approved"); require(_amount <= balanceOf(_from, _tokenId), "Quantity greater than from balance"); require(_to != address(0), "Invalid to address"); _updateTokenBalance(_from, _tokenId, _amount, ObjectLib.Operations.SUB); _updateTokenBalance(_to, _tokenId, _amount, ObjectLib.Operations.ADD); emit Transfer(_from, _to, _tokenId); emit TransferWithQuantity(_from, _to, _tokenId, _amount); } function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC721OReceiver(_to).onERC721OReceived(msg.sender, _from, _tokenId, _amount, _data); return(retval == ERC721O_RECEIVED); } } // File: erc721o/contracts/ERC721OMintable.sol pragma solidity ^0.5.4; contract ERC721OMintable is ERC721OTransferable { // Libraries using LibPosition for bytes32; // Internal functions function _mint(uint256 _tokenId, address _to, uint256 _supply) internal { // If the token doesn't exist, add it to the tokens array if (!exists(_tokenId)) { tokenTypes[_tokenId] = POSITION; allTokens.push(_tokenId); } _updateTokenBalance(_to, _tokenId, _supply, ObjectLib.Operations.ADD); emit Transfer(address(0), _to, _tokenId); emit TransferWithQuantity(address(0), _to, _tokenId, _supply); } function _burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) internal { uint256 ownerBalance = balanceOf(_tokenOwner, _tokenId); require(ownerBalance >= _quantity, "TOKEN_MINTER:NOT_ENOUGH_POSITIONS"); _updateTokenBalance(_tokenOwner, _tokenId, _quantity, ObjectLib.Operations.SUB); emit Transfer(_tokenOwner, address(0), _tokenId); emit TransferWithQuantity(_tokenOwner, address(0), _tokenId, _quantity); } function _mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) internal { _mintLong(_buyer, _derivativeHash, _quantity); _mintShort(_seller, _derivativeHash, _quantity); } function _mintLong(address _buyer, bytes32 _derivativeHash, uint256 _quantity) internal { uint256 longTokenId = _derivativeHash.getLongTokenId(); _mint(longTokenId, _buyer, _quantity); } function _mintShort(address _seller, bytes32 _derivativeHash, uint256 _quantity) internal { uint256 shortTokenId = _derivativeHash.getShortTokenId(); _mint(shortTokenId, _seller, _quantity); } function _registerPortfolio(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio) internal { if (!exists(_portfolioId)) { tokenTypes[_portfolioId] = PORTFOLIO; emit Composition(_portfolioId, _tokenIds, _tokenRatio); } } } // File: erc721o/contracts/ERC721OComposable.sol pragma solidity ^0.5.4; contract ERC721OComposable is ERC721OMintable { // Libraries using UintArray for uint256[]; using SafeMath for uint256; function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public { require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); for (uint256 i = 0; i < _tokenIds.length; i++) { _burn(msg.sender, _tokenIds[i], _tokenRatio[i].mul(_quantity)); } uint256 portfolioId = uint256(keccak256(abi.encodePacked( _tokenIds, _tokenRatio ))); _registerPortfolio(portfolioId, _tokenIds, _tokenRatio); _mint(portfolioId, msg.sender, _quantity); } function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public { require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); uint256 portfolioId = uint256(keccak256(abi.encodePacked( _tokenIds, _tokenRatio ))); require(portfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID"); _burn(msg.sender, _portfolioId, _quantity); for (uint256 i = 0; i < _tokenIds.length; i++) { _mint(_tokenIds[i], msg.sender, _tokenRatio[i].mul(_quantity)); } } function recompose( uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) public { require(_initialTokenIds.length == _initialTokenRatio.length, "TOKEN_MINTER:INITIAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_finalTokenIds.length == _finalTokenRatio.length, "TOKEN_MINTER:FINAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_initialTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_finalTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_initialTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); require(_finalTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); uint256 oldPortfolioId = uint256(keccak256(abi.encodePacked( _initialTokenIds, _initialTokenRatio ))); require(oldPortfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID"); _burn(msg.sender, _portfolioId, _quantity); _removedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); _addedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); _keptIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); uint256 newPortfolioId = uint256(keccak256(abi.encodePacked( _finalTokenIds, _finalTokenRatio ))); _registerPortfolio(newPortfolioId, _finalTokenIds, _finalTokenRatio); _mint(newPortfolioId, msg.sender, _quantity); } function _removedIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory removedIds, uint256[] memory removedIdsIdxs) = _initialTokenIds.difference(_finalTokenIds); for (uint256 i = 0; i < removedIds.length; i++) { uint256 index = removedIdsIdxs[i]; _mint(_initialTokenIds[index], msg.sender, _initialTokenRatio[index].mul(_quantity)); } _finalTokenRatio; } function _addedIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory addedIds, uint256[] memory addedIdsIdxs) = _finalTokenIds.difference(_initialTokenIds); for (uint256 i = 0; i < addedIds.length; i++) { uint256 index = addedIdsIdxs[i]; _burn(msg.sender, _finalTokenIds[index], _finalTokenRatio[index].mul(_quantity)); } _initialTokenRatio; } function _keptIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory keptIds, uint256[] memory keptInitialIdxs, uint256[] memory keptFinalIdxs) = _initialTokenIds.intersect(_finalTokenIds); for (uint256 i = 0; i < keptIds.length; i++) { uint256 initialIndex = keptInitialIdxs[i]; uint256 finalIndex = keptFinalIdxs[i]; if (_initialTokenRatio[initialIndex] > _finalTokenRatio[finalIndex]) { uint256 diff = _initialTokenRatio[initialIndex] - _finalTokenRatio[finalIndex]; _mint(_initialTokenIds[initialIndex], msg.sender, diff.mul(_quantity)); } else if (_initialTokenRatio[initialIndex] < _finalTokenRatio[finalIndex]) { uint256 diff = _finalTokenRatio[finalIndex] - _initialTokenRatio[initialIndex]; _burn(msg.sender, _initialTokenIds[initialIndex], diff.mul(_quantity)); } } } } // File: erc721o/contracts/Libs/UintsLib.sol pragma solidity ^0.5.4; library UintsLib { function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } // File: erc721o/contracts/ERC721OBackwardCompatible.sol pragma solidity ^0.5.4; contract ERC721OBackwardCompatible is ERC721OComposable { using UintsLib for uint256; // Interface constants bytes4 internal constant INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 internal constant INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bytes4 internal constant INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; // Reciever constants bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; // Metadata URI string internal baseTokenURI; constructor(string memory _baseTokenURI) public ERC721OBase() { baseTokenURI = _baseTokenURI; _registerInterface(INTERFACE_ID_ERC721); _registerInterface(INTERFACE_ID_ERC721_ENUMERABLE); _registerInterface(INTERFACE_ID_ERC721_METADATA); } // ERC721 compatibility function implementsERC721() public pure returns (bool) { return true; } /** * @dev Gets the owner of a given NFT * @param _tokenId uint256 representing the unique token identifier * @return address the owner of the token */ function ownerOf(uint256 _tokenId) public view returns (address) { if (exists(_tokenId)) { return address(this); } return address(0); } /** * @dev Gets the number of tokens owned by the address we are checking * @param _owner The adddress we are checking * @return balance The unique amount of tokens owned */ function balanceOf(address _owner) public view returns (uint256 balance) { (, uint256[] memory tokens) = tokensOwned(_owner); return tokens.length; } // ERC721 - Enumerable compatibility /** * @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]; } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) { (, uint256[] memory tokens) = tokensOwned(_owner); require(_index < tokens.length); return tokens[_index]; } // ERC721 - Metadata compatibility function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri) { require(exists(_tokenId), "Token doesn't exist"); return string(abi.encodePacked( baseTokenURI, _tokenId.uint2str(), ".json" )); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { if (exists(_tokenId)) { return address(this); } return address(0); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public nonReentrant { _transferFrom(_from, _to, _tokenId, 1); require( _checkAndCallSafeTransfer(_from, _to, _tokenId, _data), "Sent to a contract which is not an ERC721 receiver" ); } function transferFrom(address _from, address _to, uint256 _tokenId) public { _transferFrom(_from, _to, _tokenId, 1); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data ); return (retval == ERC721_RECEIVED); } } // File: contracts/TokenMinter.sol pragma solidity 0.5.16; /// @title Opium.TokenMinter contract implements ERC721O token standard for minting, burning and transferring position tokens contract TokenMinter is ERC721OBackwardCompatible, UsingRegistry { /// @notice Calls constructors of super-contracts /// @param _baseTokenURI string URI for token explorers /// @param _registry address Address of Opium.registry constructor(string memory _baseTokenURI, address _registry) public ERC721OBackwardCompatible(_baseTokenURI) UsingRegistry(_registry) {} /// @notice Mints LONG and SHORT position tokens /// @param _buyer address Address of LONG position receiver /// @param _seller address Address of SHORT position receiver /// @param _derivativeHash bytes32 Hash of derivative (ticker) of position /// @param _quantity uint256 Quantity of positions to mint function mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mint(_buyer, _seller, _derivativeHash, _quantity); } /// @notice Mints only LONG position tokens for "pooled" derivatives /// @param _buyer address Address of LONG position receiver /// @param _derivativeHash bytes32 Hash of derivative (ticker) of position /// @param _quantity uint256 Quantity of positions to mint function mint(address _buyer, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mintLong(_buyer, _derivativeHash, _quantity); } /// @notice Burns position tokens /// @param _tokenOwner address Address of tokens owner /// @param _tokenId uint256 tokenId of positions to burn /// @param _quantity uint256 Quantity of positions to burn function burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) external onlyCore { _burn(_tokenOwner, _tokenId, _quantity); } /// @notice ERC721 interface compatible function for position token name retrieving /// @return Returns name of token function name() external view returns (string memory) { return "Opium Network Position Token"; } /// @notice ERC721 interface compatible function for position token symbol retrieving /// @return Returns symbol of token function symbol() external view returns (string memory) { return "ONP"; } /// VIEW FUNCTIONS /// @notice Checks whether _spender is approved to spend tokens on _owners behalf or owner itself /// @param _spender address Address of spender /// @param _owner address Address of owner /// @param _tokenId address tokenId of interest /// @return Returns whether _spender is approved to spend tokens function isApprovedOrOwner( address _spender, address _owner, uint256 _tokenId ) public view returns (bool) { return ( _spender == _owner || getApproved(_tokenId, _owner) == _spender || isApprovedForAll(_owner, _spender) || isOpiumSpender(_spender) ); } /// @notice Checks whether _spender is Opium.TokenSpender /// @return Returns whether _spender is Opium.TokenSpender function isOpiumSpender(address _spender) public view returns (bool) { return _spender == registry.getTokenSpender(); } } // File: contracts/Errors/OracleAggregatorErrors.sol pragma solidity 0.5.16; contract OracleAggregatorErrors { string constant internal ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER = "ORACLE_AGGREGATOR:NOT_ENOUGH_ETHER"; string constant internal ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE = "ORACLE_AGGREGATOR:QUERY_WAS_ALREADY_MADE"; string constant internal ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST = "ORACLE_AGGREGATOR:DATA_DOESNT_EXIST"; string constant internal ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST = "ORACLE_AGGREGATOR:DATA_ALREADY_EXIST"; } // File: contracts/Interface/IOracleId.sol pragma solidity 0.5.16; /// @title Opium.Interface.IOracleId contract is an interface that every oracleId should implement interface IOracleId { /// @notice Requests data from `oracleId` one time /// @param timestamp uint256 Timestamp at which data are needed function fetchData(uint256 timestamp) external payable; /// @notice Requests data from `oracleId` multiple times /// @param timestamp uint256 Timestamp at which data are needed for the first time /// @param period uint256 Period in seconds between multiple timestamps /// @param times uint256 How many timestamps are requested function recursivelyFetchData(uint256 timestamp, uint256 period, uint256 times) external payable; /// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view. /// @return fetchPrice uint256 Price of one data request in ETH function calculateFetchPrice() external returns (uint256 fetchPrice); // Event with oracleId metadata JSON string (for DIB.ONE derivative explorer) event MetadataSet(string metadata); } // File: contracts/OracleAggregator.sol pragma solidity 0.5.16; /// @title Opium.OracleAggregator contract requests and caches the data from `oracleId`s and provides them to the Core for positions execution contract OracleAggregator is OracleAggregatorErrors, ReentrancyGuard { using SafeMath for uint256; // Storage for the `oracleId` results // dataCache[oracleId][timestamp] => data mapping (address => mapping(uint256 => uint256)) public dataCache; // Flags whether data were provided // dataExist[oracleId][timestamp] => bool mapping (address => mapping(uint256 => bool)) public dataExist; // Flags whether data were requested // dataRequested[oracleId][timestamp] => bool mapping (address => mapping(uint256 => bool)) public dataRequested; // MODIFIERS /// @notice Checks whether enough ETH were provided withing data request to proceed /// @param oracleId address Address of the `oracleId` smart contract /// @param times uint256 How many times the `oracleId` is being requested modifier enoughEtherProvided(address oracleId, uint256 times) { // Calling Opium.IOracleId function to get the data fetch price per one request uint256 oneTimePrice = calculateFetchPrice(oracleId); // Checking if enough ether was provided for `times` amount of requests require(msg.value >= oneTimePrice.mul(times), ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER); _; } // PUBLIC FUNCTIONS /// @notice Requests data from `oracleId` one time /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are needed function fetchData(address oracleId, uint256 timestamp) public payable nonReentrant enoughEtherProvided(oracleId, 1) { // Check if was not requested before and mark as requested _registerQuery(oracleId, timestamp); // Call the `oracleId` contract and transfer ETH IOracleId(oracleId).fetchData.value(msg.value)(timestamp); } /// @notice Requests data from `oracleId` multiple times /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are needed for the first time /// @param period uint256 Period in seconds between multiple timestamps /// @param times uint256 How many timestamps are requested function recursivelyFetchData(address oracleId, uint256 timestamp, uint256 period, uint256 times) public payable nonReentrant enoughEtherProvided(oracleId, times) { // Check if was not requested before and mark as requested in loop for each timestamp for (uint256 i = 0; i < times; i++) { _registerQuery(oracleId, timestamp + period * i); } // Call the `oracleId` contract and transfer ETH IOracleId(oracleId).recursivelyFetchData.value(msg.value)(timestamp, period, times); } /// @notice Receives and caches data from `msg.sender` /// @param timestamp uint256 Timestamp of data /// @param data uint256 Data itself function __callback(uint256 timestamp, uint256 data) public { // Don't allow to push data twice require(!dataExist[msg.sender][timestamp], ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST); // Saving data dataCache[msg.sender][timestamp] = data; // Flagging that data were received dataExist[msg.sender][timestamp] = true; } /// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view. /// @param oracleId address Address of the `oracleId` smart contract /// @return fetchPrice uint256 Price of one data request in ETH function calculateFetchPrice(address oracleId) public returns(uint256 fetchPrice) { fetchPrice = IOracleId(oracleId).calculateFetchPrice(); } // PRIVATE FUNCTIONS /// @notice Checks if data was not requested and provided before and marks as requested /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are requested function _registerQuery(address oracleId, uint256 timestamp) private { // Check if data was not requested and provided yet require(!dataRequested[oracleId][timestamp] && !dataExist[oracleId][timestamp], ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE); // Mark as requested dataRequested[oracleId][timestamp] = true; } // VIEW FUNCTIONS /// @notice Returns cached data if they exist, or reverts with an error /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data were requested /// @return dataResult uint256 Cached data provided by `oracleId` function getData(address oracleId, uint256 timestamp) public view returns(uint256 dataResult) { // Check if Opium.OracleAggregator has data require(hasData(oracleId, timestamp), ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST); // Return cached data dataResult = dataCache[oracleId][timestamp]; } /// @notice Getter for dataExist mapping /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data were requested /// @param result bool Returns whether data were provided already function hasData(address oracleId, uint256 timestamp) public view returns(bool result) { return dataExist[oracleId][timestamp]; } } // File: contracts/Errors/SyntheticAggregatorErrors.sol pragma solidity 0.5.16; contract SyntheticAggregatorErrors { string constant internal ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH = "SYNTHETIC_AGGREGATOR:DERIVATIVE_HASH_NOT_MATCH"; string constant internal ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN = "SYNTHETIC_AGGREGATOR:WRONG_MARGIN"; string constant internal ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG = "SYNTHETIC_AGGREGATOR:COMMISSION_TOO_BIG"; } // File: contracts/SyntheticAggregator.sol pragma solidity 0.5.16; /// @notice Opium.SyntheticAggregator contract initialized, identifies and caches syntheticId sensitive data contract SyntheticAggregator is SyntheticAggregatorErrors, LibDerivative, LibCommission, ReentrancyGuard { // Emitted when new ticker is initialized event Create(Derivative derivative, bytes32 derivativeHash); // Enum for types of syntheticId // Invalid - syntheticId is not initialized yet // NotPool - syntheticId with p2p logic // Pool - syntheticId with pooled logic enum SyntheticTypes { Invalid, NotPool, Pool } // Cache of buyer margin by ticker // buyerMarginByHash[derivativeHash] = buyerMargin mapping (bytes32 => uint256) public buyerMarginByHash; // Cache of seller margin by ticker // sellerMarginByHash[derivativeHash] = sellerMargin mapping (bytes32 => uint256) public sellerMarginByHash; // Cache of type by ticker // typeByHash[derivativeHash] = type mapping (bytes32 => SyntheticTypes) public typeByHash; // Cache of commission by ticker // commissionByHash[derivativeHash] = commission mapping (bytes32 => uint256) public commissionByHash; // Cache of author addresses by ticker // authorAddressByHash[derivativeHash] = authorAddress mapping (bytes32 => address) public authorAddressByHash; // PUBLIC FUNCTIONS /// @notice Initializes ticker, if was not initialized and returns `syntheticId` author commission from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return commission uint256 Synthetic author commission function getAuthorCommission(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 commission) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); commission = commissionByHash[_derivativeHash]; } /// @notice Initializes ticker, if was not initialized and returns `syntheticId` author address from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return authorAddress address Synthetic author address function getAuthorAddress(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (address authorAddress) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); authorAddress = authorAddressByHash[_derivativeHash]; } /// @notice Initializes ticker, if was not initialized and returns buyer and seller margin from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return buyerMargin uint256 Margin of buyer /// @return sellerMargin uint256 Margin of seller function getMargin(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 buyerMargin, uint256 sellerMargin) { // If it's a pool, just return margin from syntheticId contract if (_isPool(_derivativeHash, _derivative)) { return IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative); } // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); // Check if margins for _derivativeHash were already cached buyerMargin = buyerMarginByHash[_derivativeHash]; sellerMargin = sellerMarginByHash[_derivativeHash]; } /// @notice Checks whether `syntheticId` implements pooled logic /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return result bool Returns whether synthetic implements pooled logic function isPool(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (bool result) { result = _isPool(_derivativeHash, _derivative); } // PRIVATE FUNCTIONS /// @notice Initializes ticker, if was not initialized and returns whether `syntheticId` implements pooled logic /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return result bool Returns whether synthetic implements pooled logic function _isPool(bytes32 _derivativeHash, Derivative memory _derivative) private returns (bool result) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); result = typeByHash[_derivativeHash] == SyntheticTypes.Pool; } /// @notice Initializes ticker: caches syntheticId type, margin, author address and commission /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself function _initDerivative(bytes32 _derivativeHash, Derivative memory _derivative) private { // Check if type for _derivativeHash was already cached SyntheticTypes syntheticType = typeByHash[_derivativeHash]; // Type could not be Invalid, thus this condition says us that type was not cached before if (syntheticType != SyntheticTypes.Invalid) { return; } // For security reasons we calculate hash of provided _derivative bytes32 derivativeHash = getDerivativeHash(_derivative); require(derivativeHash == _derivativeHash, ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH); // POOL // Get isPool from SyntheticId bool result = IDerivativeLogic(_derivative.syntheticId).isPool(); // Cache type returned from synthetic typeByHash[derivativeHash] = result ? SyntheticTypes.Pool : SyntheticTypes.NotPool; // MARGIN // Get margin from SyntheticId (uint256 buyerMargin, uint256 sellerMargin) = IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative); // We are not allowing both margins to be equal to 0 require(buyerMargin != 0 || sellerMargin != 0, ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN); // Cache margins returned from synthetic buyerMarginByHash[derivativeHash] = buyerMargin; sellerMarginByHash[derivativeHash] = sellerMargin; // AUTHOR ADDRESS // Cache author address returned from synthetic authorAddressByHash[derivativeHash] = IDerivativeLogic(_derivative.syntheticId).getAuthorAddress(); // AUTHOR COMMISSION // Get commission from syntheticId uint256 commission = IDerivativeLogic(_derivative.syntheticId).getAuthorCommission(); // Check if commission is not set > 100% require(commission <= COMMISSION_BASE, ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG); // Cache commission commissionByHash[derivativeHash] = commission; // If we are here, this basically means this ticker was not used before, so we emit an event for Dapps developers about new ticker (derivative) and it's hash emit Create(_derivative, derivativeHash); } } // File: contracts/Lib/Whitelisted.sol pragma solidity 0.5.16; /// @title Opium.Lib.Whitelisted contract implements whitelist with modifier to restrict access to only whitelisted addresses contract Whitelisted { // Whitelist array address[] internal whitelist; /// @notice This modifier restricts access to functions, which could be called only by whitelisted addresses modifier onlyWhitelisted() { // Allowance flag bool allowed = false; // Going through whitelisted addresses array uint256 whitelistLength = whitelist.length; for (uint256 i = 0; i < whitelistLength; i++) { // If `msg.sender` is met within whitelisted addresses, raise the flag and exit the loop if (whitelist[i] == msg.sender) { allowed = true; break; } } // Check if flag was raised require(allowed, "Only whitelisted allowed"); _; } /// @notice Getter for whitelisted addresses array /// @return Array of whitelisted addresses function getWhitelist() public view returns (address[] memory) { return whitelist; } } // File: contracts/Lib/WhitelistedWithGovernance.sol pragma solidity 0.5.16; /// @title Opium.Lib.WhitelistedWithGovernance contract implements Opium.Lib.Whitelisted and adds governance for whitelist controlling contract WhitelistedWithGovernance is Whitelisted { // Emitted when new governor is set event GovernorSet(address governor); // Emitted when new whitelist is proposed event Proposed(address[] whitelist); // Emitted when proposed whitelist is committed (set) event Committed(address[] whitelist); // Proposal life timelock interval uint256 public timeLockInterval; // Governor address address public governor; // Timestamp of last proposal uint256 public proposalTime; // Proposed whitelist address[] public proposedWhitelist; /// @notice This modifier restricts access to functions, which could be called only by governor modifier onlyGovernor() { require(msg.sender == governor, "Only governor allowed"); _; } /// @notice Contract constructor /// @param _timeLockInterval uint256 Initial value for timelock interval /// @param _governor address Initial value for governor constructor(uint256 _timeLockInterval, address _governor) public { timeLockInterval = _timeLockInterval; governor = _governor; emit GovernorSet(governor); } /// @notice Calling this function governor could propose new whitelist addresses array. Also it allows to initialize first whitelist if it was not initialized yet. function proposeWhitelist(address[] memory _whitelist) public onlyGovernor { // Restrict empty proposals require(_whitelist.length != 0, "Can't be empty"); // Consider empty whitelist as not initialized, as proposing of empty whitelists is not allowed // If whitelist has never been initialized, we set whitelist right away without proposal if (whitelist.length == 0) { whitelist = _whitelist; emit Committed(_whitelist); // Otherwise save current time as timestamp of proposal, save proposed whitelist and emit event } else { proposalTime = now; proposedWhitelist = _whitelist; emit Proposed(_whitelist); } } /// @notice Calling this function governor commits proposed whitelist if timelock interval of proposal was passed function commitWhitelist() public onlyGovernor { // Check if proposal was made require(proposalTime != 0, "Didn't proposed yet"); // Check if timelock interval was passed require((proposalTime + timeLockInterval) < now, "Can't commit yet"); // Set new whitelist and emit event whitelist = proposedWhitelist; emit Committed(whitelist); // Reset proposal time lock proposalTime = 0; } /// @notice This function allows governor to transfer governance to a new governor and emits event /// @param _governor address Address of new governor function setGovernor(address _governor) public onlyGovernor { require(_governor != address(0), "Can't set zero address"); governor = _governor; emit GovernorSet(governor); } } // File: contracts/Lib/WhitelistedWithGovernanceAndChangableTimelock.sol pragma solidity 0.5.16; /// @notice Opium.Lib.WhitelistedWithGovernanceAndChangableTimelock contract implements Opium.Lib.WhitelistedWithGovernance and adds possibility for governor to change timelock interval within timelock interval contract WhitelistedWithGovernanceAndChangableTimelock is WhitelistedWithGovernance { // Emitted when new timelock is proposed event Proposed(uint256 timelock); // Emitted when new timelock is committed (set) event Committed(uint256 timelock); // Timestamp of last timelock proposal uint256 public timeLockProposalTime; // Proposed timelock uint256 public proposedTimeLock; /// @notice Calling this function governor could propose new timelock /// @param _timelock uint256 New timelock value function proposeTimelock(uint256 _timelock) public onlyGovernor { timeLockProposalTime = now; proposedTimeLock = _timelock; emit Proposed(_timelock); } /// @notice Calling this function governor could commit previously proposed new timelock if timelock interval of proposal was passed function commitTimelock() public onlyGovernor { // Check if proposal was made require(timeLockProposalTime != 0, "Didn't proposed yet"); // Check if timelock interval was passed require((timeLockProposalTime + timeLockInterval) < now, "Can't commit yet"); // Set new timelock and emit event timeLockInterval = proposedTimeLock; emit Committed(proposedTimeLock); // Reset timelock time lock timeLockProposalTime = 0; } } // File: contracts/TokenSpender.sol pragma solidity 0.5.16; /// @title Opium.TokenSpender contract holds users ERC20 approvals and allows whitelisted contracts to use tokens contract TokenSpender is WhitelistedWithGovernanceAndChangableTimelock { using SafeERC20 for IERC20; // Initial timelock period uint256 public constant WHITELIST_TIMELOCK = 1 hours; /// @notice Calls constructors of super-contracts /// @param _governor address Address of governor, who is allowed to adjust whitelist constructor(address _governor) public WhitelistedWithGovernance(WHITELIST_TIMELOCK, _governor) {} /// @notice Using this function whitelisted contracts could call ERC20 transfers /// @param token IERC20 Instance of token /// @param from address Address from which tokens are transferred /// @param to address Address of tokens receiver /// @param amount uint256 Amount of tokens to be transferred function claimTokens(IERC20 token, address from, address to, uint256 amount) external onlyWhitelisted { token.safeTransferFrom(from, to, amount); } /// @notice Using this function whitelisted contracts could call ERC721O transfers /// @param token IERC721O Instance of token /// @param from address Address from which tokens are transferred /// @param to address Address of tokens receiver /// @param tokenId uint256 Token ID to be transferred /// @param amount uint256 Amount of tokens to be transferred function claimPositions(IERC721O token, address from, address to, uint256 tokenId, uint256 amount) external onlyWhitelisted { token.safeTransferFrom(from, to, tokenId, amount); } } // File: contracts/Core.sol pragma solidity 0.5.16; /// @title Opium.Core contract creates positions, holds and distributes margin at the maturity contract Core is LibDerivative, LibCommission, UsingRegistry, CoreErrors, ReentrancyGuard { using SafeMath for uint256; using LibPosition for bytes32; using SafeERC20 for IERC20; // Emitted when Core creates new position event Created(address buyer, address seller, bytes32 derivativeHash, uint256 quantity); // Emitted when Core executes positions event Executed(address tokenOwner, uint256 tokenId, uint256 quantity); // Emitted when Core cancels ticker for the first time event Canceled(bytes32 derivativeHash); // Period of time after which ticker could be canceled if no data was provided to the `oracleId` uint256 public constant NO_DATA_CANCELLATION_PERIOD = 2 weeks; // Vaults for pools // This mapping holds balances of pooled positions // poolVaults[syntheticAddress][tokenAddress] => availableBalance mapping (address => mapping(address => uint256)) public poolVaults; // Vaults for fees // This mapping holds balances of fee recipients // feesVaults[feeRecipientAddress][tokenAddress] => availableBalance mapping (address => mapping(address => uint256)) public feesVaults; // Hashes of cancelled tickers mapping (bytes32 => bool) public cancelled; /// @notice Calls Core.Lib.UsingRegistry constructor constructor(address _registry) public UsingRegistry(_registry) {} // PUBLIC FUNCTIONS /// @notice This function allows fee recipients to withdraw their fees /// @param _tokenAddress address Address of an ERC20 token to withdraw function withdrawFee(address _tokenAddress) public nonReentrant { uint256 balance = feesVaults[msg.sender][_tokenAddress]; feesVaults[msg.sender][_tokenAddress] = 0; IERC20(_tokenAddress).safeTransfer(msg.sender, balance); } /// @notice Creates derivative contracts (positions) /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of derivatives to be created /// @param _addresses address[2] Addresses of buyer and seller /// [0] - buyer address /// [1] - seller address - if seller is set to `address(0)`, consider as pooled position function create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) public nonReentrant { if (_addresses[1] == address(0)) { _createPooled(_derivative, _quantity, _addresses[0]); } else { _create(_derivative, _quantity, _addresses); } } /// @notice Executes several positions of `msg.sender` with same `tokenId` /// @param _tokenId uint256 `tokenId` of positions that needs to be executed /// @param _quantity uint256 Quantity of positions to execute /// @param _derivative Derivative Derivative definition function execute(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _execute(msg.sender, tokenIds, quantities, derivatives); } /// @notice Executes several positions of `_tokenOwner` with same `tokenId` /// @param _tokenOwner address Address of the owner of positions /// @param _tokenId uint256 `tokenId` of positions that needs to be executed /// @param _quantity uint256 Quantity of positions to execute /// @param _derivative Derivative Derivative definition function execute(address _tokenOwner, uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _execute(_tokenOwner, tokenIds, quantities, derivatives); } /// @notice Executes several positions of `msg.sender` with different `tokenId`s /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function execute(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _execute(msg.sender, _tokenIds, _quantities, _derivatives); } /// @notice Executes several positions of `_tokenOwner` with different `tokenId`s /// @param _tokenOwner address Address of the owner of positions /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _execute(_tokenOwner, _tokenIds, _quantities, _derivatives); } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenId uint256 `tokenId` of positions that needs to be canceled /// @param _quantity uint256 Quantity of positions to cancel /// @param _derivative Derivative Derivative definition function cancel(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _cancel(tokenIds, quantities, derivatives); } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled /// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _cancel(_tokenIds, _quantities, _derivatives); } // PRIVATE FUNCTIONS struct CreatePooledLocalVars { SyntheticAggregator syntheticAggregator; IDerivativeLogic derivativeLogic; IERC20 marginToken; TokenSpender tokenSpender; TokenMinter tokenMinter; } /// @notice This function creates pooled positions /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of positions to create /// @param _address address Address of position receiver function _createPooled(Derivative memory _derivative, uint256 _quantity, address _address) private { // Local variables CreatePooledLocalVars memory vars; // Create instance of Opium.SyntheticAggregator // Create instance of Opium.IDerivativeLogic // Create instance of margin token // Create instance of Opium.TokenSpender // Create instance of Opium.TokenMinter vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId); vars.marginToken = IERC20(_derivative.token); vars.tokenSpender = TokenSpender(registry.getTokenSpender()); vars.tokenMinter = TokenMinter(registry.getMinter()); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check with Opium.SyntheticAggregator if syntheticId is a pool require(vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_NOT_POOL); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); // Validate input data against Derivative logic (`syntheticId`) require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR); // Get cached margin required according to logic from Opium.SyntheticAggregator (uint256 margin, ) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative); // Check ERC20 tokens allowance: margin * quantity // `msg.sender` must provide margin for position creation require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margin.mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE); // Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margin.mul(_quantity)); // Since it's a pooled position, we add transferred margin to pool balance poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].add(margin.mul(_quantity)); // Mint LONG position tokens vars.tokenMinter.mint(_address, derivativeHash, _quantity); emit Created(_address, address(0), derivativeHash, _quantity); } struct CreateLocalVars { SyntheticAggregator syntheticAggregator; IDerivativeLogic derivativeLogic; IERC20 marginToken; TokenSpender tokenSpender; TokenMinter tokenMinter; } /// @notice This function creates p2p positions /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of positions to create /// @param _addresses address[2] Addresses of buyer and seller /// [0] - buyer address /// [1] - seller address function _create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) private { // Local variables CreateLocalVars memory vars; // Create instance of Opium.SyntheticAggregator // Create instance of Opium.IDerivativeLogic // Create instance of margin token // Create instance of Opium.TokenSpender // Create instance of Opium.TokenMinter vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId); vars.marginToken = IERC20(_derivative.token); vars.tokenSpender = TokenSpender(registry.getTokenSpender()); vars.tokenMinter = TokenMinter(registry.getMinter()); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check with Opium.SyntheticAggregator if syntheticId is not a pool require(!vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_CANT_BE_POOL); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); // Validate input data against Derivative logic (`syntheticId`) require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR); uint256[2] memory margins; // Get cached margin required according to logic from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative); // Check ERC20 tokens allowance: (margins[0] + margins[1]) * quantity // `msg.sender` must provide margin for position creation require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margins[0].add(margins[1]).mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE); // Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margins[0].add(margins[1]).mul(_quantity)); // Mint LONG and SHORT positions tokens vars.tokenMinter.mint(_addresses[0], _addresses[1], derivativeHash, _quantity); emit Created(_addresses[0], _addresses[1], derivativeHash, _quantity); } struct ExecuteAndCancelLocalVars { TokenMinter tokenMinter; OracleAggregator oracleAggregator; SyntheticAggregator syntheticAggregator; } /// @notice Executes several positions of `_tokenOwner` with different `tokenId`s /// @param _tokenOwner address Address of the owner of positions /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function _execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private { require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH); require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH); // Local variables ExecuteAndCancelLocalVars memory vars; // Create instance of Opium.TokenMinter // Create instance of Opium.OracleAggregator // Create instance of Opium.SyntheticAggregator vars.tokenMinter = TokenMinter(registry.getMinter()); vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator()); vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); for (uint256 i; i < _tokenIds.length; i++) { // Check if execution is performed after endTime require(now > _derivatives[i].endTime, ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED); // Checking whether execution is performed by `_tokenOwner` or `_tokenOwner` allowed third party executions on it's behalf require( _tokenOwner == msg.sender || IDerivativeLogic(_derivatives[i].syntheticId).thirdpartyExecutionAllowed(_tokenOwner), ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED ); // Returns payout for all positions uint256 payout = _getPayout(_derivatives[i], _tokenIds[i], _quantities[i], vars); // Transfer payout if (payout > 0) { IERC20(_derivatives[i].token).safeTransfer(_tokenOwner, payout); } // Burn executed position tokens vars.tokenMinter.burn(_tokenOwner, _tokenIds[i], _quantities[i]); emit Executed(_tokenOwner, _tokenIds[i], _quantities[i]); } } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled /// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function _cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private { require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH); require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH); // Local variables ExecuteAndCancelLocalVars memory vars; // Create instance of Opium.TokenMinter // Create instance of Opium.OracleAggregator // Create instance of Opium.SyntheticAggregator vars.tokenMinter = TokenMinter(registry.getMinter()); vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator()); vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); for (uint256 i; i < _tokenIds.length; i++) { // Don't allow to cancel tickers with "dummy" oracleIds require(_derivatives[i].oracleId != address(0), ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID); // Check if cancellation is called after `NO_DATA_CANCELLATION_PERIOD` and `oracleId` didn't provided data require( _derivatives[i].endTime + NO_DATA_CANCELLATION_PERIOD <= now && !vars.oracleAggregator.hasData(_derivatives[i].oracleId, _derivatives[i].endTime), ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED ); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivatives[i]); // Emit `Canceled` event only once and mark ticker as canceled if (!cancelled[derivativeHash]) { cancelled[derivativeHash] = true; emit Canceled(derivativeHash); } uint256[2] memory margins; // Get cached margin required according to logic from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivatives[i]); uint256 payout; // Check if `_tokenId` is an ID of LONG position if (derivativeHash.getLongTokenId() == _tokenIds[i]) { // Set payout to buyerPayout payout = margins[0]; // Check if `_tokenId` is an ID of SHORT position } else if (derivativeHash.getShortTokenId() == _tokenIds[i]) { // Set payout to sellerPayout payout = margins[1]; } else { // Either portfolioId, hack or bug revert(ERROR_CORE_UNKNOWN_POSITION_TYPE); } // Transfer payout * _quantities[i] if (payout > 0) { IERC20(_derivatives[i].token).safeTransfer(msg.sender, payout.mul(_quantities[i])); } // Burn canceled position tokens vars.tokenMinter.burn(msg.sender, _tokenIds[i], _quantities[i]); } } /// @notice Calculates payout for position and gets fees /// @param _derivative Derivative Derivative definition /// @param _tokenId uint256 `tokenId` of positions /// @param _quantity uint256 Quantity of positions /// @param _vars ExecuteAndCancelLocalVars Helping local variables /// @return payout uint256 Payout for all tokens function _getPayout(Derivative memory _derivative, uint256 _tokenId, uint256 _quantity, ExecuteAndCancelLocalVars memory _vars) private returns (uint256 payout) { // Trying to getData from Opium.OracleAggregator, could be reverted // Opium allows to use "dummy" oracleIds, in this case data is set to `0` uint256 data; if (_derivative.oracleId != address(0)) { data = _vars.oracleAggregator.getData(_derivative.oracleId, _derivative.endTime); } else { data = 0; } uint256[2] memory payoutRatio; // Get payout ratio from Derivative logic // payoutRatio[0] - buyerPayout // payoutRatio[1] - sellerPayout (payoutRatio[0], payoutRatio[1]) = IDerivativeLogic(_derivative.syntheticId).getExecutionPayout(_derivative, data); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); uint256[2] memory margins; // Get cached total margin required from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = _vars.syntheticAggregator.getMargin(derivativeHash, _derivative); uint256[2] memory payouts; // Calculate payouts from ratio // payouts[0] -> buyerPayout = (buyerMargin + sellerMargin) * buyerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio) // payouts[1] -> sellerPayout = (buyerMargin + sellerMargin) * sellerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio) payouts[0] = margins[0].add(margins[1]).mul(payoutRatio[0]).div(payoutRatio[0].add(payoutRatio[1])); payouts[1] = margins[0].add(margins[1]).mul(payoutRatio[1]).div(payoutRatio[0].add(payoutRatio[1])); // Check if `_tokenId` is an ID of LONG position if (derivativeHash.getLongTokenId() == _tokenId) { // Check if it's a pooled position if (_vars.syntheticAggregator.isPool(derivativeHash, _derivative)) { // Pooled position payoutRatio is considered as full payout, not as payoutRatio payout = payoutRatio[0]; // Multiply payout by quantity payout = payout.mul(_quantity); // Check sufficiency of syntheticId balance in poolVaults require( poolVaults[_derivative.syntheticId][_derivative.token] >= payout , ERROR_CORE_INSUFFICIENT_POOL_BALANCE ); // Subtract paid out margin from poolVault poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].sub(payout); } else { // Set payout to buyerPayout payout = payouts[0]; // Multiply payout by quantity payout = payout.mul(_quantity); } // Take fees only from profit makers // Check: payout > buyerMargin * quantity if (payout > margins[0].mul(_quantity)) { // Get Opium and `syntheticId` author fees and subtract it from payout payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[0].mul(_quantity))); } // Check if `_tokenId` is an ID of SHORT position } else if (derivativeHash.getShortTokenId() == _tokenId) { // Set payout to sellerPayout payout = payouts[1]; // Multiply payout by quantity payout = payout.mul(_quantity); // Take fees only from profit makers // Check: payout > sellerMargin * quantity if (payout > margins[1].mul(_quantity)) { // Get Opium fees and subtract it from payout payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[1].mul(_quantity))); } } else { // Either portfolioId, hack or bug revert(ERROR_CORE_UNKNOWN_POSITION_TYPE); } } /// @notice Calculates `syntheticId` author and opium fees from profit makers /// @param _syntheticAggregator SyntheticAggregator Instance of Opium.SyntheticAggregator /// @param _derivativeHash bytes32 Derivative hash /// @param _derivative Derivative Derivative definition /// @param _profit uint256 payout of one position /// @return fee uint256 Opium and `syntheticId` author fee function _getFees(SyntheticAggregator _syntheticAggregator, bytes32 _derivativeHash, Derivative memory _derivative, uint256 _profit) private returns (uint256 fee) { // Get cached `syntheticId` author address from Opium.SyntheticAggregator address authorAddress = _syntheticAggregator.getAuthorAddress(_derivativeHash, _derivative); // Get cached `syntheticId` fee percentage from Opium.SyntheticAggregator uint256 commission = _syntheticAggregator.getAuthorCommission(_derivativeHash, _derivative); // Calculate fee // fee = profit * commission / COMMISSION_BASE fee = _profit.mul(commission).div(COMMISSION_BASE); // If commission is zero, finish if (fee == 0) { return 0; } // Calculate opium fee // opiumFee = fee * OPIUM_COMMISSION_PART / OPIUM_COMMISSION_BASE uint256 opiumFee = fee.mul(OPIUM_COMMISSION_PART).div(OPIUM_COMMISSION_BASE); // Calculate author fee // authorFee = fee - opiumFee uint256 authorFee = fee.sub(opiumFee); // Get opium address address opiumAddress = registry.getOpiumAddress(); // Update feeVault for Opium team // feesVault[opium][token] += opiumFee feesVaults[opiumAddress][_derivative.token] = feesVaults[opiumAddress][_derivative.token].add(opiumFee); // Update feeVault for `syntheticId` author // feeVault[author][token] += authorFee feesVaults[authorAddress][_derivative.token] = feesVaults[authorAddress][_derivative.token].add(authorFee); } } // File: contracts/Errors/MatchingErrors.sol pragma solidity 0.5.16; contract MatchingErrors { string constant internal ERROR_MATCH_CANCELLATION_NOT_ALLOWED = "MATCH:CANCELLATION_NOT_ALLOWED"; string constant internal ERROR_MATCH_ALREADY_CANCELED = "MATCH:ALREADY_CANCELED"; string constant internal ERROR_MATCH_ORDER_WAS_CANCELED = "MATCH:ORDER_WAS_CANCELED"; string constant internal ERROR_MATCH_TAKER_ADDRESS_WRONG = "MATCH:TAKER_ADDRESS_WRONG"; string constant internal ERROR_MATCH_ORDER_IS_EXPIRED = "MATCH:ORDER_IS_EXPIRED"; string constant internal ERROR_MATCH_SENDER_ADDRESS_WRONG = "MATCH:SENDER_ADDRESS_WRONG"; string constant internal ERROR_MATCH_SIGNATURE_NOT_VERIFIED = "MATCH:SIGNATURE_NOT_VERIFIED"; string constant internal ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES = "MATCH:NOT_ENOUGH_ALLOWED_FEES"; } // File: contracts/Lib/LibEIP712.sol pragma solidity 0.5.16; /// @title Opium.Lib.LibEIP712 contract implements the domain of EIP712 for meta transactions contract LibEIP712 { // EIP712Domain structure // name - protocol name // version - protocol version // verifyingContract - signed message verifying contract struct EIP712Domain { string name; string version; address verifyingContract; } // Calculate typehash of ERC712Domain bytes32 constant internal EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); // solhint-disable-next-line var-name-mixedcase bytes32 internal DOMAIN_SEPARATOR; // Calculate domain separator at creation constructor () public { DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256("Opium Network"), keccak256("1"), address(this) )); } /// @notice Hashes EIP712Message /// @param hashStruct bytes32 Hash of structured message /// @return result bytes32 Hash of EIP712Message function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { bytes32 domainSeparator = DOMAIN_SEPARATOR; assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), domainSeparator) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // File: contracts/Matching/Match/LibOrder.sol pragma solidity 0.5.16; /// @title Opium.Matching.Match.LibOrder contract implements EIP712 signed Order for Opium.Matching.Match contract LibOrder is LibEIP712 { /** Structure of order Description should be considered from the order signer (maker) perspective makerMarginAddress - address of token that maker is willing to pay with takerMarginAddress - address of token that maker is willing to receive makerAddress - address of maker takerAddress - address of counterparty (taker). If zero address, then taker could be anyone senderAddress - address which is allowed to settle the order on-chain. If zero address, then anyone could settle relayerAddress - address of the relayer fee recipient affiliateAddress - address of the affiliate fee recipient feeTokenAddress - address of token which is used for fees makerTokenId - tokenId of position, that maker is willing to pay makerTokenAmount - amount of position tokens that maker is willing to pay makerMarginAmount - amount of margin token that maker is willing to pay takerTokenId - tokenId of position, that maker wants to receive. Create new derivative with this tokenId in case of calling Match.create(). Swap to this tokenId in case Match.swap() is called. takerTokenAmount - amount of tokens that maker wants to receive takerMarginAmount - amount of margin that maker wants to receive relayerFee - amount of fee in feeToken that should be paid to relayer affiliateFee - amount of fee in feeToken that should be paid to affiliate nonce - unique order ID expiresAt - UNIX timestamp of order expiration. Zero for Good-Till-Cancel order signature - Signature of EIP712 message. Not used in hash, but then set for order processing purposes */ struct Order { address makerMarginAddress; address takerMarginAddress; address makerAddress; address takerAddress; address senderAddress; address relayerAddress; address affiliateAddress; address feeTokenAddress; uint256 makerTokenId; uint256 makerTokenAmount; uint256 makerMarginAmount; uint256 takerTokenId; uint256 takerTokenAmount; uint256 takerMarginAmount; uint256 relayerFee; uint256 affiliateFee; uint256 nonce; uint256 expiresAt; // Not used in hash bytes signature; } // Calculate typehash of Order bytes32 constant internal EIP712_ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "address makerMarginAddress,", "address takerMarginAddress,", "address makerAddress,", "address takerAddress,", "address senderAddress,", "address relayerAddress,", "address affiliateAddress,", "address feeTokenAddress,", "uint256 makerTokenId,", "uint256 makerTokenAmount,", "uint256 makerMarginAmount,", "uint256 takerTokenId,", "uint256 takerTokenAmount,", "uint256 takerMarginAmount,", "uint256 relayerFee,", "uint256 affiliateFee,", "uint256 nonce,", "uint256 expiresAt", ")" )); /// @notice Hashes the order /// @param _order Order Order to hash /// @return hash bytes32 Order hash function hashOrder(Order memory _order) public pure returns (bytes32 hash) { hash = keccak256( abi.encodePacked( abi.encodePacked( EIP712_ORDER_TYPEHASH, uint256(_order.makerMarginAddress), uint256(_order.takerMarginAddress), uint256(_order.makerAddress), uint256(_order.takerAddress), uint256(_order.senderAddress), uint256(_order.relayerAddress), uint256(_order.affiliateAddress), uint256(_order.feeTokenAddress) ), abi.encodePacked( _order.makerTokenId, _order.makerTokenAmount, _order.makerMarginAmount, _order.takerTokenId, _order.takerTokenAmount, _order.takerMarginAmount ), abi.encodePacked( _order.relayerFee, _order.affiliateFee, _order.nonce, _order.expiresAt ) ) ); } /// @notice Verifies order signature /// @param _hash bytes32 Hash of the order /// @param _signature bytes Signature of the order /// @param _address address Address of the order signer /// @return bool Returns whether `_signature` is valid and was created by `_address` function verifySignature(bytes32 _hash, bytes memory _signature, address _address) internal view returns (bool) { require(_signature.length == 65, "ORDER:INVALID_SIGNATURE_LENGTH"); bytes32 digest = hashEIP712Message(_hash); address recovered = retrieveAddress(digest, _signature); return _address == recovered; } /// @notice Helping function to recover signer address /// @param _hash bytes32 Hash for signature /// @param _signature bytes Signature /// @return address Returns address of signature creator function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(_hash, v, r, s); } } } // File: contracts/Matching/Match/MatchLogic.sol pragma solidity 0.5.16; /// @title Opium.Matching.MatchLogic contract implements logic for order validation and cancelation contract MatchLogic is MatchingErrors, LibOrder, UsingRegistry, ReentrancyGuard { using SafeMath for uint256; using LibPosition for bytes32; using SafeERC20 for IERC20; // Emmitted when order was canceled event Canceled(bytes32 orderHash); // Base value for 100% value of token/margin amount uint256 public constant PERCENTAGE_BASE = 10**30; // Canceled orders // This mapping holds hashes of canceled orders // canceled[orderHash] => canceled mapping (bytes32 => bool) public canceled; // Verified orders // This mapping holds hashes of verified orders to verify only once // verified[orderHash] => verified mapping (bytes32 => bool) public verified; // Orders filling percentage // This mapping holds orders filled percentage in base of PERCENTAGE_BASE // filled[orderHash] => filled mapping (bytes32 => uint256) public filled; // Vaults for fees // This mapping holds balances of relayers and affiliates fees to withdraw // balances[feeRecipientAddress][tokenAddress] => balances mapping (address => mapping (address => uint256)) public balances; // Keeps whether fee was already taken mapping (bytes32 => bool) public feeTaken; /// @notice Calling this function maker of the order could cancel it on-chain /// @param _order Order function cancel(Order memory _order) public { require(msg.sender == _order.makerAddress, ERROR_MATCH_CANCELLATION_NOT_ALLOWED); bytes32 orderHash = hashOrder(_order); require(!canceled[orderHash], ERROR_MATCH_ALREADY_CANCELED); canceled[orderHash] = true; emit Canceled(orderHash); } /// @notice Function to withdraw fees from orders for relayer and affiliates /// @param _token IERC20 Instance of token to withdraw function withdraw(IERC20 _token) public nonReentrant { uint256 balance = balances[msg.sender][address(_token)]; balances[msg.sender][address(_token)] = 0; _token.safeTransfer(msg.sender, balance); } /// @notice This function checks whether order was canceled /// @param _hash bytes32 Hash of the order function validateNotCanceled(bytes32 _hash) internal view { require(!canceled[_hash], ERROR_MATCH_ORDER_WAS_CANCELED); } /// @notice This function validates takerAddress of _leftOrder. It should match either with _rightOrder.makerAddress or be set to zero address /// @param _leftOrder Order Left order /// @param _rightOrder Order Right order function validateTakerAddress(Order memory _leftOrder, Order memory _rightOrder) internal pure { require( _leftOrder.takerAddress == address(0) || _leftOrder.takerAddress == _rightOrder.makerAddress, ERROR_MATCH_TAKER_ADDRESS_WRONG ); } /// @notice This function validates whether order was expired or it's `expiresAt` is set to zero /// @param _order Order function validateExpiration(Order memory _order) internal view { require( _order.expiresAt == 0 || _order.expiresAt > now, ERROR_MATCH_ORDER_IS_EXPIRED ); } /// @notice This function validates whether sender address equals to `msg.sender` or set to zero address /// @param _order Order function validateSenderAddress(Order memory _order) internal view { require( _order.senderAddress == address(0) || _order.senderAddress == msg.sender, ERROR_MATCH_SENDER_ADDRESS_WRONG ); } /// @notice This function validates order signature if not validated before /// @param orderHash bytes32 Hash of the order /// @param _order Order function validateSignature(bytes32 orderHash, Order memory _order) internal { if (verified[orderHash]) { return; } bool result = verifySignature(orderHash, _order.signature, _order.makerAddress); require(result, ERROR_MATCH_SIGNATURE_NOT_VERIFIED); verified[orderHash] = true; } /// @notice This function is responsible for taking relayer and affiliate fees, if they were not taken already /// @param _orderHash bytes32 Hash of the order /// @param _order Order Order itself function takeFees(bytes32 _orderHash, Order memory _order) internal { // Check if fee was already taken if (feeTaken[_orderHash]) { return; } // Check if feeTokenAddress is not set to zero address if (_order.feeTokenAddress == address(0)) { return; } // Calculate total amount of fees needs to be transfered uint256 fees = _order.relayerFee.add(_order.affiliateFee); // If total amount of fees is non-zero if (fees == 0) { return; } // Create instance of fee token IERC20 feeToken = IERC20(_order.feeTokenAddress); // Create instance of TokenSpender TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Check if user has enough token approval to pay the fees require(feeToken.allowance(_order.makerAddress, address(tokenSpender)) >= fees, ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES); // Transfer fee tokenSpender.claimTokens(feeToken, _order.makerAddress, address(this), fees); // Get opium address address opiumAddress = registry.getOpiumAddress(); // Add commission to relayer balance, or to opium balance if relayer is not set if (_order.relayerAddress != address(0)) { balances[_order.relayerAddress][_order.feeTokenAddress] = balances[_order.relayerAddress][_order.feeTokenAddress].add(_order.relayerFee); } else { balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.relayerFee); } // Add commission to affiliate balance, or to opium balance if affiliate is not set if (_order.affiliateAddress != address(0)) { balances[_order.affiliateAddress][_order.feeTokenAddress] = balances[_order.affiliateAddress][_order.feeTokenAddress].add(_order.affiliateFee); } else { balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.affiliateFee); } // Mark the fee of token as taken feeTaken[_orderHash] = true; } /// @notice Helper to get minimal of two integers /// @param _a uint256 First integer /// @param _b uint256 Second integer /// @return uint256 Minimal integer function min(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } /// @notice Helper to get percentage of division in base of PERCENTAGE_BASE /// devP = numerator / denominator * 100% /// @param _numerator uint256 Numerator of division /// @param _denominator uint256 Denominator of division /// @return divisionPercentage uint256 Percentage of division function getDivisionPercentage(uint256 _numerator, uint256 _denominator) internal pure returns (uint256 divisionPercentage) { divisionPercentage = _numerator.mul(PERCENTAGE_BASE).div(_denominator).add(1); // In case of numerator > denominator consider as 100% if (divisionPercentage > PERCENTAGE_BASE) { divisionPercentage = PERCENTAGE_BASE; } } /// @notice Helper to recover numerator from percentage of division in base of PERCENTAGE_BASE /// numerator = devP * denominator / 100% /// @param _divisionPercentage Percentage of division /// @param _denominator uint256 Denominator of division /// @return numerator uint256 Recovered numerator function getInitialPercentageValue(uint256 _divisionPercentage, uint256 _denominator) internal pure returns (uint256 numerator) { numerator = _divisionPercentage.mul(_denominator).div(PERCENTAGE_BASE); } } // File: contracts/Matching/Match/MatchCreate.sol pragma solidity 0.5.16; /// @title Opium.Matching.MatchCreate contract implements create() function to settle a pair of orders and create derivatives for order makers contract MatchCreate is MatchLogic, LibDerivative { // Emmitted when new order pair was successfully settled event Create(bytes32 derivativeHash, address buyerPremiumAddress, uint256 buyerPremiumAmount, address sellerPremiumAddress, uint256 sellerPremiumAmount, uint256 filled); /// @notice This function receives buy and sell orders, derivative related to it and information whether buy order was first in orderbook (maker) /// @param _buyOrder Order Order of derivative buyer /// @param _sellOrder Order Order of derivative seller /// @param _derivative Derivative Data of derivative for validation and calculation purposes /// @param _buyerIsMaker bool Indicates whether buyer order came to orderbook first function create(Order memory _buyOrder, Order memory _sellOrder, Derivative memory _derivative, bool _buyerIsMaker) public nonReentrant { // New deals must not offer tokenIds require( _buyOrder.makerTokenId == _sellOrder.makerTokenId && _sellOrder.makerTokenId == 0, "MATCH:NOT_CREATION" ); // Check if it's not pooled positions require(!IDerivativeLogic(_derivative.syntheticId).isPool(), "MATCH:CANT_BE_POOL"); // Validate taker if set validateTakerAddress(_buyOrder, _sellOrder); validateTakerAddress(_sellOrder, _buyOrder); // Validate sender if set validateSenderAddress(_buyOrder); validateSenderAddress(_sellOrder); // Validate expiration if set validateExpiration(_buyOrder); validateExpiration(_sellOrder); // Validate orders signatures and if orders were canceled // orderHashes[0] - buyOrderHash // orderHashes[1] - sellOrderHash bytes32[2] memory orderHashes; orderHashes[0] = hashOrder(_buyOrder); validateNotCanceled(orderHashes[0]); validateSignature(orderHashes[0], _buyOrder); orderHashes[1] = hashOrder(_sellOrder); validateNotCanceled(orderHashes[1]); validateSignature(orderHashes[1], _sellOrder); // Validates counterparty tokens and margin // Calculates available premiums // margins[0] - buyerMargin // margins[1] - sellerMargin (uint256[2] memory margins, bytes32 derivativeHash) = _validateDerivativeAndCalculateMargin(_buyOrder, _sellOrder, _derivative); // Premiums // premiums[0] - buyerReceivePremium // premiums[1] - sellerReceivePremium uint256[2] memory premiums; // If buyer requires premium on creation, should match with seller's margin token address // If buyer requires premium on creation, seller should provide at least the same premium or more // Returns buyer's premium for each contract premiums[0] = _validatePremium(_buyOrder, _sellOrder, margins[1], _buyerIsMaker); // If seller requires premium on creation, should match with buyer's margin token address // If seller requires premium on creation, buyer should provide at least the same premium or more // Returns seller's premium for each contract premiums[1] = _validatePremium(_sellOrder, _buyOrder, margins[0], !_buyerIsMaker); // Fill orders as much as possible // Returns available amount of positions to be filled uint256 fillPositions = _fillCreate(_buyOrder, orderHashes[0], _sellOrder, orderHashes[1]); // Take fees takeFees(orderHashes[0], _buyOrder); takeFees(orderHashes[1], _sellOrder); // Distribute margin and premium _distributeFunds(_buyOrder, _sellOrder, _derivative, margins, premiums, fillPositions); // Settle contracts Core(registry.getCore()).create(_derivative, fillPositions, [_buyOrder.makerAddress, _sellOrder.makerAddress]); emit Create(derivativeHash, _buyOrder.takerMarginAddress, premiums[0], _sellOrder.takerMarginAddress, premiums[1], fillPositions); } // PRIVATE FUNCTIONS /// @notice Validates derivative, tokenIds and gets required cached margin /// @param _buyOrder Order Order of derivative buyer /// @param _sellOrder Order Order of derivative seller /// @param _derivative Derivative Data of derivative for validation and calculation purposes /// @return margins uint256[2] buyer and seller margin array /// @return derivativeHash bytes32 Hash of derivative function _validateDerivativeAndCalculateMargin(Order memory _buyOrder, Order memory _sellOrder, Derivative memory _derivative) private returns (uint256[2] memory margins, bytes32 derivativeHash) { // Calculate derivative related data for validation derivativeHash = getDerivativeHash(_derivative); uint256 longTokenId = derivativeHash.getLongTokenId(); uint256 shortTokenId = derivativeHash.getShortTokenId(); // New deals must request opposite position tokens require( _buyOrder.takerTokenId != _sellOrder.takerTokenId && _buyOrder.takerTokenId == longTokenId && _sellOrder.takerTokenId == shortTokenId, "MATCH:DERIVATIVE_NOT_MATCH" ); // Get cached total margin required according to logic // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = SyntheticAggregator(registry.getSyntheticAggregator()).getMargin(derivativeHash, _derivative); // Validate that provided margin token is the same as derivative margin token require( margins[0] == 0 || _buyOrder.makerMarginAddress == _derivative.token , "MATCH:PROVIDED_MARGIN_CURRENCY_WRONG" ); require( margins[1] == 0 || _sellOrder.makerMarginAddress == _derivative.token , "MATCH:PROVIDED_MARGIN_CURRENCY_WRONG" ); // Validate that provided margin is enough for creating new positions require( _buyOrder.makerMarginAmount >= _buyOrder.takerTokenAmount.mul(margins[0]) && _sellOrder.makerMarginAmount >= _sellOrder.takerTokenAmount.mul(margins[1]), "MATCH:PROVIDED_MARGIN_NOT_ENOUGH" ); } /// @notice Calculates and validates premium /// @param _leftOrder Order Order for which we calculate premium /// @param _rightOrder Order Counterparty order /// @param _rightOrderMargin uint256 Margin of counterparty order /// @param _leftIsMaker bool Whether left order first came to orderbook /// @return Returns left order premium function _validatePremium(Order memory _leftOrder, Order memory _rightOrder, uint256 _rightOrderMargin, bool _leftIsMaker) private pure returns(uint256) { // If order doesn't require premium, exit if (_leftOrder.takerMarginAmount == 0) { return 0; // leftReceivePremium is 0 } // Validate premium/margin token address require( _leftOrder.takerMarginAddress == _rightOrder.makerMarginAddress, "MATCH:MARGIN_ADDRESS_NOT_MATCH" ); // Calculate how much left order maker wants premium for each contract uint256 leftWantsPremium = _leftOrder.takerMarginAmount.div(_leftOrder.takerTokenAmount); // Calculate how much right order maker offers premium excluding margin required for derivative uint256 rightOffersPremium = _rightOrder.makerMarginAmount.div(_rightOrder.takerTokenAmount).sub(_rightOrderMargin); // Check if right order offers enough premium for left order require( leftWantsPremium <= rightOffersPremium, "MATCH:PREMIUM_IS_NOT_ENOUGH" ); // Take premium of order, who first came to orderbook return _leftIsMaker ? leftWantsPremium : rightOffersPremium; } /// @notice Calculates orders fillability (available positions to fill) and validates /// @param _leftOrder Order /// @param _leftOrderHash bytes32 /// @param _rightOrder Order /// @param _rightOrderHash bytes32 /// @return fillPositions uint256 Available amount of positions to be filled function _fillCreate(Order memory _leftOrder, bytes32 _leftOrderHash, Order memory _rightOrder, bytes32 _rightOrderHash) private returns (uint256 fillPositions) { // Keep initial orders takerTokenAmount values uint256 leftInitial = _leftOrder.takerTokenAmount; uint256 rightInitial = _rightOrder.takerTokenAmount; // Calcualte already filled part uint256 leftAlreadyFilled = getInitialPercentageValue(filled[_leftOrderHash], _leftOrder.takerTokenAmount); uint256 rightAlreadyFilled = getInitialPercentageValue(filled[_rightOrderHash], _rightOrder.takerTokenAmount); // Subtract already filled part and calculate left order and right order available part (uint256 leftAvailable, uint256 rightAvailable) = ( _leftOrder.takerTokenAmount.sub(leftAlreadyFilled), _rightOrder.takerTokenAmount.sub(rightAlreadyFilled) ); // We could only fill minimum available of both counterparties fillPositions = min(leftAvailable, rightAvailable); require(fillPositions > 0, "MATCH:NO_FILLABLE_POSITIONS"); // Update filled // If initial takerTokenAmount was 0, set filled to 100% // Otherwise calculate new filled percetage -> (alreadyFilled + fill) / initial * 100% filled[_leftOrderHash] = leftInitial == 0 ? PERCENTAGE_BASE : getDivisionPercentage(leftAlreadyFilled.add(fillPositions), leftInitial); filled[_rightOrderHash] = rightInitial == 0 ? PERCENTAGE_BASE : getDivisionPercentage(rightAlreadyFilled.add(fillPositions), rightInitial); } /// @notice This function distributes premiums, takes margin and approves it to Core /// @param _buyOrder Order Order of derivative buyer /// @param _sellOrder Order Order of derivative seller /// @param _derivative Derivative Data of derivative for validation and calculation purposes /// @param margins uint256[2] Margins of buyer and seller /// @param premiums uint256[2] Premiums of buyer and seller /// @param fillPositions uint256 Quantity of positions to fill function _distributeFunds( Order memory _buyOrder, Order memory _sellOrder, Derivative memory _derivative, uint256[2] memory margins, uint256[2] memory premiums, uint256 fillPositions ) private { IERC20 marginToken = IERC20(_derivative.token); TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Transfer margin + premium from buyer to Match and distribute if (margins[0].add(premiums[1]) != 0) { // Check allowance for premiums + margins require(marginToken.allowance(_buyOrder.makerAddress, address(tokenSpender)) >= margins[0].add(premiums[1]).mul(fillPositions), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); if (premiums[1] != 0) { // Transfer premium to seller tokenSpender.claimTokens(marginToken, _buyOrder.makerAddress, _sellOrder.makerAddress, premiums[1].mul(fillPositions)); } if (margins[0] != 0) { // Transfer margins from buyer to Match tokenSpender.claimTokens(marginToken, _buyOrder.makerAddress, address(this), margins[0].mul(fillPositions)); } } // Transfer margin + premium from seller to Match and distribute if (margins[1].add(premiums[0]) != 0) { // Check allowance for premiums + margin require(marginToken.allowance(_sellOrder.makerAddress, address(tokenSpender)) >= margins[1].add(premiums[0]).mul(fillPositions), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); if (premiums[0] != 0) { // Transfer premium to buyer tokenSpender.claimTokens(marginToken, _sellOrder.makerAddress, _buyOrder.makerAddress, premiums[0].mul(fillPositions)); } if (margins[1] != 0) { // Transfer margins from seller to Match tokenSpender.claimTokens(marginToken, _sellOrder.makerAddress, address(this), margins[1].mul(fillPositions)); } } if (margins[0].add(margins[1]) != 0) { // Approve margin to Core for derivative creation require(marginToken.approve(address(tokenSpender), margins[0].add(margins[1]).mul(fillPositions)), "MATCH:COULDNT_APPROVE_MARGIN_FOR_CORE"); } } } // File: contracts/Matching/Match/MatchSwap.sol pragma solidity 0.5.16; /// @title Opium.Matching.MatchSwap contract implements swap() function to make TMtm swap /// TMtm swap is swaps of Token + Margin to Token + MArgin contract MatchSwap is MatchLogic { // Emmited when swap is made event Swap( uint256 leftMakerTokenId, uint256 leftMakerTokenAmount, address leftMakerMarginAddress, uint256 leftMakerMarginAmount, uint256 rightMakerTokenId, uint256 rightMakerTokenAmount, address rightMakerMarginAddress, uint256 rightMakerMarginAmount ); /// @notice This function receives left and right orders, and performs swap of Token + Margin to Token + Margin swaps /// @param _leftOrder Order /// @param _rightOrder Order function swap(Order memory _leftOrder, Order memory _rightOrder) public nonReentrant { // Validate taker if set validateTakerAddress(_leftOrder, _rightOrder); validateTakerAddress(_rightOrder, _leftOrder); // Validate sender if set validateSenderAddress(_leftOrder); validateSenderAddress(_rightOrder); // Validate expiration if set validateExpiration(_leftOrder); validateExpiration(_rightOrder); // Validate if was canceled // orderHashes[0] - leftOrderHash // orderHashes[1] - rightOrderHash bytes32[2] memory orderHashes; orderHashes[0] = hashOrder(_leftOrder); validateNotCanceled(orderHashes[0]); validateSignature(orderHashes[0], _leftOrder); orderHashes[1] = hashOrder(_rightOrder); validateNotCanceled(orderHashes[1]); validateSignature(orderHashes[1], _rightOrder); // Validate if values are correct // Fill orders as much as possible // leftFill[0] - Tokens that left sends to right // leftFill[1] - Margin that left sends to right // rightFill[0] - Tokens that right sends to left // rightFill[1] - Margin that right sends to left (uint256[2] memory leftFill, uint256[2] memory rightFill) = _validateOffersAndFillSwap(_leftOrder, orderHashes[0], _rightOrder, orderHashes[1]); // Take fees takeFees(orderHashes[0], _leftOrder); takeFees(orderHashes[1], _rightOrder); // Validate if swap is possible and make it _validateAndMakeSwap(_leftOrder, leftFill, _rightOrder, rightFill); } /// @notice Validates Orders according to TMtm logic and calculates fillability /// @param _leftOrder Order /// @param _leftOrderHash bytes32 /// @param _rightOrder Order /// @param _rightOrderHash bytes32 /// @return leftFill uint256[2] Left fillability /// @return rightFill uint256[2] Right fillability function _validateOffersAndFillSwap(Order memory _leftOrder, bytes32 _leftOrderHash, Order memory _rightOrder, bytes32 _rightOrderHash) private returns (uint256[2] memory leftFill, uint256[2] memory rightFill) { // Keep initial order takerTokenAmount and takerMarginAmount values uint256[2] memory leftInitial; uint256[2] memory rightInitial; leftInitial[0] = _leftOrder.takerTokenAmount; leftInitial[1] = _leftOrder.takerMarginAmount; rightInitial[0] = _rightOrder.takerTokenAmount; rightInitial[1] = _rightOrder.takerMarginAmount; // Calculates already filled part uint256[2] memory leftAlreadyFilled; leftAlreadyFilled[0] = getInitialPercentageValue(filled[_leftOrderHash], _leftOrder.takerTokenAmount); leftAlreadyFilled[1] = getInitialPercentageValue(filled[_leftOrderHash], _leftOrder.takerMarginAmount); _leftOrder.takerTokenAmount = _leftOrder.takerTokenAmount.sub(leftAlreadyFilled[0]); _leftOrder.takerMarginAmount = _leftOrder.takerMarginAmount.sub(leftAlreadyFilled[1]); // Subtract already filled part uint256[2] memory rightAlreadyFilled; rightAlreadyFilled[0] = getInitialPercentageValue(filled[_rightOrderHash], _rightOrder.takerTokenAmount); rightAlreadyFilled[1] = getInitialPercentageValue(filled[_rightOrderHash], _rightOrder.takerMarginAmount); _rightOrder.takerTokenAmount = _rightOrder.takerTokenAmount.sub(rightAlreadyFilled[0]); _rightOrder.takerMarginAmount = _rightOrder.takerMarginAmount.sub(rightAlreadyFilled[1]); // Calculate if swap is possible uint256[4] memory left; uint256[4] memory right; left[0] = _leftOrder.makerTokenAmount.mul(_rightOrder.makerTokenAmount); right[0] = _leftOrder.takerTokenAmount.mul(_rightOrder.takerTokenAmount); left[1] = _leftOrder.makerTokenAmount.mul(_rightOrder.makerMarginAmount); right[1] = _leftOrder.takerMarginAmount.mul(_rightOrder.takerTokenAmount); left[2] = _leftOrder.makerMarginAmount.mul(_rightOrder.makerTokenAmount); right[2] = _leftOrder.takerTokenAmount.mul(_rightOrder.takerMarginAmount); left[3] = _leftOrder.makerMarginAmount.mul(_rightOrder.makerMarginAmount); right[3] = _leftOrder.takerMarginAmount.mul(_rightOrder.takerMarginAmount); require( left[0] >= right[0] && left[1] >= right[1] && left[2] >= right[2] && left[3] >= right[3], "MATCH:OFFERS_CONDITIONS_ARE_NOT_MET" ); // Calculate fillable values leftFill[0] = min(_leftOrder.makerTokenAmount, _rightOrder.takerTokenAmount); leftFill[1] = min(_leftOrder.makerMarginAmount, _rightOrder.takerMarginAmount); rightFill[0] = min(_leftOrder.takerTokenAmount, _rightOrder.makerTokenAmount); rightFill[1] = min(_leftOrder.takerMarginAmount, _rightOrder.makerMarginAmount); require( leftFill[0] != 0 || leftFill[1] != 0 || rightFill[0] != 0 || rightFill[1] != 0 , "MATCH:NO_FILLABLE_POSITIONS"); // Update filled // See Match.create() uint256[2] memory leftFilledPercents; leftFilledPercents[0] = leftInitial[0] == 0 ? PERCENTAGE_BASE : getDivisionPercentage(leftAlreadyFilled[0].add(rightFill[0]), leftInitial[0]); leftFilledPercents[1] = leftInitial[1] == 0 ? PERCENTAGE_BASE : getDivisionPercentage(leftAlreadyFilled[1].add(rightFill[1]), leftInitial[1]); filled[_leftOrderHash] = min(leftFilledPercents[0], leftFilledPercents[1]); uint256[2] memory rightFilledPercents; rightFilledPercents[0] = rightInitial[0] == 0 ? PERCENTAGE_BASE : getDivisionPercentage(rightAlreadyFilled[0].add(leftFill[0]), rightInitial[0]); rightFilledPercents[1] = rightInitial[1] == 0 ? PERCENTAGE_BASE : getDivisionPercentage(rightAlreadyFilled[1].add(leftFill[1]), rightInitial[1]); filled[_rightOrderHash] = min(rightFilledPercents[0], rightFilledPercents[1]); } /// @notice Validate order properties and distribute tokens and margins /// @param _leftOrder Order /// @param leftFill uint256[2] Left order fillability /// @param _rightOrder Order /// @param rightFill uint256[2] Right order fillability function _validateAndMakeSwap(Order memory _leftOrder, uint256[2] memory leftFill, Order memory _rightOrder, uint256[2] memory rightFill) private { TokenMinter tm = TokenMinter(registry.getMinter()); TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Transfer positions left -> right if needed if (leftFill[0] != 0) { require(_leftOrder.makerTokenId == _rightOrder.takerTokenId, "MATCH:NOT_VALID_SWAP"); require(tm.isApprovedOrOwner(address(tokenSpender), _leftOrder.makerAddress, _leftOrder.makerTokenId), "MATCH:NOT_ALLOWED_POSITION"); tokenSpender.claimPositions(tm, _leftOrder.makerAddress, _rightOrder.makerAddress, _leftOrder.makerTokenId, leftFill[0]); } // Transfer positions right -> left if needed if (rightFill[0] != 0) { require(_leftOrder.takerTokenId == _rightOrder.makerTokenId, "MATCH:NOT_VALID_SWAP"); require(tm.isApprovedOrOwner(address(tokenSpender), _rightOrder.makerAddress, _rightOrder.makerTokenId), "MATCH:NOT_ALLOWED_POSITION"); tokenSpender.claimPositions(tm, _rightOrder.makerAddress, _leftOrder.makerAddress, _rightOrder.makerTokenId, rightFill[0]); } // Transfer margin left -> right if needed if (leftFill[1] != 0) { require(_leftOrder.makerMarginAddress == _rightOrder.takerMarginAddress, "MATCH:NOT_VALID_SWAP"); IERC20 makerMarginToken = IERC20(_leftOrder.makerMarginAddress); require(makerMarginToken.allowance(_leftOrder.makerAddress, address(tokenSpender)) >= leftFill[1], "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); tokenSpender.claimTokens(makerMarginToken, _leftOrder.makerAddress, _rightOrder.makerAddress, leftFill[1]); } // Transfer margin right -> left if needed if (rightFill[1] != 0) { require(_leftOrder.takerMarginAddress == _rightOrder.makerMarginAddress, "MATCH:NOT_VALID_SWAP"); IERC20 takerMarginToken = IERC20(_leftOrder.takerMarginAddress); require(takerMarginToken.allowance(_rightOrder.makerAddress, address(tokenSpender)) >= rightFill[1], "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); tokenSpender.claimTokens(takerMarginToken, _rightOrder.makerAddress, _leftOrder.makerAddress, rightFill[1]); } emit Swap( _leftOrder.makerTokenId, leftFill[0], _leftOrder.makerMarginAddress, leftFill[1], _rightOrder.makerTokenId, rightFill[0], _rightOrder.makerMarginAddress, rightFill[1] ); } } // File: contracts/Matching/Match/Match.sol pragma solidity 0.5.16; /// @title Opium.Matching.Match contract combines Opium.Matching.MatchCreate and Opium.Matching.MatchSwap into one contract contract Match is MatchCreate, MatchSwap { /// @notice Calls constructors of super-contracts /// @param _registry address Address of Opium.registry constructor (address _registry) public UsingRegistry(_registry) {} }
This function is responsible for taking relayer and affiliate fees, if they were not taken already _orderHash bytes32 Hash of the order _order Order Order itself Check if fee was already taken Check if feeTokenAddress is not set to zero address If total amount of fees is non-zero Add commission to relayer balance, or to opium balance if relayer is not set Add commission to affiliate balance, or to opium balance if affiliate is not set
function takeFees(bytes32 _orderHash, Order memory _order) internal { if (feeTaken[_orderHash]) { return; } if (_order.feeTokenAddress == address(0)) { return; } if (fees == 0) { return; } if (_order.relayerAddress != address(0)) { balances[_order.relayerAddress][_order.feeTokenAddress] = balances[_order.relayerAddress][_order.feeTokenAddress].add(_order.relayerFee); balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.relayerFee); } if (_order.affiliateAddress != address(0)) { balances[_order.affiliateAddress][_order.feeTokenAddress] = balances[_order.affiliateAddress][_order.feeTokenAddress].add(_order.affiliateFee); balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.affiliateFee); } }
10,467,003
// SPDX-License-Identifier: MIT pragma solidity ^0.7.1; pragma experimental ABIEncoderV2; import "./interfaces/IDiamondCut.sol"; import "./Diamond.sol"; import "./facets/DiamondCutFacet.sol"; import "./facets/DiamondLoupeFacet.sol"; import "./facets/OwnershipFacet.sol"; contract Diamantaire { event DiamondCreated(Diamond diamond); IDiamondCut.FacetCut[] internal _builtinDiamondCut; constructor() { bytes4[] memory functionSelectors; // ------------------------------------------------------------------------- // adding diamondCut function // ------------------------------------------------------------------------- DiamondCutFacet diamondCutFacet = new DiamondCutFacet(); functionSelectors = new bytes4[](1); functionSelectors[0] = DiamondCutFacet.diamondCut.selector; _builtinDiamondCut.push(IDiamondCut.FacetCut({ facetAddress:address(diamondCutFacet), action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors })); // ------------------------------------------------------------------------- // adding diamond loupe functions // ------------------------------------------------------------------------- DiamondLoupeFacet diamondLoupeFacet = new DiamondLoupeFacet(); functionSelectors = new bytes4[](5); functionSelectors[0] = DiamondLoupeFacet.facetFunctionSelectors.selector; functionSelectors[1] = DiamondLoupeFacet.facets.selector; functionSelectors[2] = DiamondLoupeFacet.facetAddress.selector; functionSelectors[3] = DiamondLoupeFacet.facetAddresses.selector; functionSelectors[4] = DiamondLoupeFacet.supportsInterface.selector; _builtinDiamondCut.push(IDiamondCut.FacetCut({ facetAddress:address(diamondLoupeFacet), action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors })); // ------------------------------------------------------------------------- // adding ownership functions // ------------------------------------------------------------------------- OwnershipFacet ownershipFacet = new OwnershipFacet(); functionSelectors = new bytes4[](2); functionSelectors[0] = OwnershipFacet.transferOwnership.selector; functionSelectors[1] = OwnershipFacet.owner.selector; _builtinDiamondCut.push(IDiamondCut.FacetCut({ facetAddress:address(ownershipFacet), action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors })); } function createDiamond( address owner, IDiamondCut.FacetCut[] calldata _diamondCut, bytes calldata data, bytes32 salt ) external payable returns (Diamond diamond) { if (salt != 0x0000000000000000000000000000000000000000000000000000000000000000) { salt = keccak256(abi.encodePacked(salt, owner)); diamond = new Diamond{value: msg.value, salt: salt}( _builtinDiamondCut, Diamond.DiamondArgs({owner:address(this)}) ); } else { diamond = new Diamond{value: msg.value}(_builtinDiamondCut, Diamond.DiamondArgs({owner:address(this)})); } emit DiamondCreated(diamond); IDiamondCut(address(diamond)).diamondCut(_diamondCut, data.length > 0 ? address(diamond) : address(0), data); IERC173(address(diamond)).transferOwnership(owner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 * * Implementation of a diamond. /******************************************************************************/ import "./libraries/LibDiamond.sol"; import "./interfaces/IDiamondLoupe.sol"; import "./interfaces/IDiamondCut.sol"; import "./interfaces/IERC173.sol"; import "./interfaces/IERC165.sol"; contract Diamond { // more arguments are added to this struct // this avoids stack too deep errors struct DiamondArgs { address owner; } constructor(IDiamondCut.FacetCut[] memory _diamondCut, DiamondArgs memory _args) payable { LibDiamond.diamondCut(_diamondCut, address(0), new bytes(0)); LibDiamond.setContractOwner(_args.owner); LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); // adding ERC165 data ds.supportedInterfaces[type(IERC165).interfaceId] = true; ds.supportedInterfaces[type(IDiamondCut).interfaceId] = true; ds.supportedInterfaces[type(IDiamondLoupe).interfaceId] = true; ds.supportedInterfaces[type(IERC173).interfaceId] = true; } // Find facet for function that is called and execute the // function if a facet is found and return any value. fallback() external payable { LibDiamond.DiamondStorage storage ds; bytes32 position = LibDiamond.DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress; require(facet != address(0), "Diamond: Function does not exist"); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import "../interfaces/IDiamondCut.sol"; import "../libraries/LibDiamond.sol"; contract DiamondCutFacet is IDiamondCut { /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { LibDiamond.enforceIsContractOwner(); LibDiamond.diamondCut(_diamondCut, _init, _calldata); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import "../libraries/LibDiamond.sol"; import "../interfaces/IDiamondCut.sol"; import "../interfaces/IDiamondLoupe.sol"; import "../interfaces/IERC165.sol"; contract DiamondLoupeFacet is IDiamondLoupe, IERC165 { // Diamond Loupe Functions //////////////////////////////////////////////////////////////////// /// These functions are expected to be called frequently by tools. // // struct Facet { // address facetAddress; // bytes4[] functionSelectors; // } /// @notice Gets all facets and their selectors. /// @return facets_ Facet function facets() external override view returns (Facet[] memory facets_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); uint256 numFacets = ds.facetAddresses.length; facets_ = new Facet[](numFacets); for (uint256 i; i < numFacets; i++) { address facetAddress_ = ds.facetAddresses[i]; facets_[i].facetAddress = facetAddress_; facets_[i].functionSelectors = ds.facetFunctionSelectors[facetAddress_].functionSelectors; } } /// @notice Gets all the function selectors provided by a facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external override view returns (bytes4[] memory facetFunctionSelectors_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); facetFunctionSelectors_ = ds.facetFunctionSelectors[_facet].functionSelectors; } /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external override view returns (address[] memory facetAddresses_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); facetAddresses_ = ds.facetAddresses; } /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external override view returns (address facetAddress_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); facetAddress_ = ds.selectorToFacetAndPosition[_functionSelector].facetAddress; } // This implements ERC-165. function supportsInterface(bytes4 _interfaceId) external override view returns (bool) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); return ds.supportedInterfaces[_interfaceId]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../libraries/LibDiamond.sol"; import "../interfaces/IERC173.sol"; contract OwnershipFacet is IERC173 { function transferOwnership(address _newOwner) external override { LibDiamond.enforceIsContractOwner(); LibDiamond.setContractOwner(_newOwner); } function owner() external override view returns (address owner_) { owner_ = LibDiamond.contractOwner(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ // A loupe is a small magnifying glass used to look at diamonds. // These functions look at diamonds interface IDiamondLoupe { /// These functions are expected to be called frequently /// by tools. struct Facet { address facetAddress; bytes4[] functionSelectors; } /// @notice Gets all facet addresses and their four byte function selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory facets_); /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_); /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory facetAddresses_); /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; 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. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; /// @title ERC-173 Contract Ownership Standard /// Note: the ERC-165 identifier for this interface is 0x7f5828d0 /* is ERC165 */ interface IERC173 { /// @dev This emits when ownership of a contract changes. event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice Get the address of the owner /// @return owner_ The address of the owner. function owner() external view returns (address owner_); /// @notice Set the address of the new owner of the contract /// @dev Set _newOwner to address(0) to renounce any ownership. /// @param _newOwner The address of the new owner of the contract function transferOwnership(address _newOwner) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import "../interfaces/IDiamondCut.sol"; library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct FacetAddressAndPosition { address facetAddress; uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint16 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the selector in the facetFunctionSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } function enforceIsContractOwner() internal view { require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner"); } event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata); // Internal function version of diamondCut function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) { IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action; if (action == IDiamondCut.FacetCutAction.Add) { addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else if (action == IDiamondCut.FacetCutAction.Replace) { replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else if (action == IDiamondCut.FacetCutAction.Remove) { removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); // uint16 selectorCount = uint16(diamondStorage().selectors.length); require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); uint16 selectorPosition = uint16(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length); // add new facet address if it does not exist if (selectorPosition == 0) { enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code"); ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = uint16(ds.facetAddresses.length); ds.facetAddresses.push(_facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists"); ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(selector); ds.selectorToFacetAndPosition[selector].facetAddress = _facetAddress; ds.selectorToFacetAndPosition[selector].functionSelectorPosition = selectorPosition; selectorPosition++; } } function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)"); uint16 selectorPosition = uint16(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length); // add new facet address if it does not exist if (selectorPosition == 0) { enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code"); ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = uint16(ds.facetAddresses.length); ds.facetAddresses.push(_facetAddress); } for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require(oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function"); removeFunction(oldFacetAddress, selector); // add function ds.selectorToFacetAndPosition[selector].functionSelectorPosition = selectorPosition; ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(selector); ds.selectorToFacetAndPosition[selector].facetAddress = _facetAddress; selectorPosition++; } } function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal { require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut"); DiamondStorage storage ds = diamondStorage(); // if function does not exist then do nothing and return require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)"); for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; removeFunction(oldFacetAddress, selector); } } function removeFunction(address _facetAddress, bytes4 _selector) internal { DiamondStorage storage ds = diamondStorage(); require(_facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist"); // an immutable function is a function defined directly in a diamond require(_facetAddress != address(this), "LibDiamondCut: Can't remove immutable function"); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1; // if not the same then replace _selector with lastSelector if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector; ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint16(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = uint16(facetAddressPosition); } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty"); } else { require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)"); if (_init != address(this)) { enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error revert(string(error)); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode(address _contract, string memory _errorMessage) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } }
Get all the facet addresses used by a diamond. return facetAddresses_
function facetAddresses() external override view returns (address[] memory facetAddresses_) { LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage(); facetAddresses_ = ds.facetAddresses; }
564,921
./partial_match/1/0x8139A938dD63BD698e134D7D845629115e4f5cbF/sources/GASTK.sol
Function used during the public mint quantity Amount to mint. checkState to check sale state.
function Mint(uint64 quantity) external payable checkState(SaleStates.PUBLIC) { uint256 price = publicPrice; uint256 freeMintCount = _freeMintedCount[msg.sender]; if(quantity<=(maxFreeMint-freeMintCount)){ price=0; _freeMintedCount[msg.sender] = freeMintCount + quantity; } if (whitelist[msg.sender]) { price=whitelistPrice; if(quantity<=(whitelistMint-freeMintCount)){ price=0; _freeMintedCount[msg.sender] = freeMintCount + quantity; } } if (msg.value < quantity * price) revert InvalidEtherAmount(); if ((_numberMinted(msg.sender) - _getAux(msg.sender)) + quantity > WALLET_MAX) revert WalletLimitExceeded(); if (_totalMinted() + quantity > maxSupply) revert SupplyExceeded(); if(price!=0){ require(success, "WITHDRAW FAILED!"); } if(quantity>=10){ _mintERC2309(msg.sender, quantity); } else { _mint(msg.sender, quantity); } emit Minted(msg.sender, quantity); }
4,243,740
/** *Submitted for verification at Etherscan.io on 2022-04-20 */ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); } /// @author RetreebInc /// @title Interface Staking Platform with fixed APY and lockup interface IStakingPlatform { /** * @notice function that start the staking * @dev set `startPeriod` to the current current `block.timestamp` * set `lockupPeriod` which is `block.timestamp` + `lockupDuration` * and `endPeriod` which is `startPeriod` + `stakingDuration` */ function startStaking() external; /** * @notice function that allows a user to deposit tokens * @dev user must first approve the amount to deposit before calling this function, * cannot exceed the `maxAmountStaked` * @param amount, the amount to be deposited * @dev `endPeriod` to equal 0 (Staking didn't started yet), * or `endPeriod` more than current `block.timestamp` (staking not finished yet) * @dev `totalStaked + amount` must be less than `stakingMax` * @dev that the amount deposited should greater than 0 */ function deposit(uint amount) external; /** * @notice function that allows a user to withdraw its initial deposit * @dev must be called only when `block.timestamp` >= `endPeriod` * @dev `block.timestamp` higher than `lockupPeriod` (lockupPeriod finished) * withdraw reset all states variable for the `msg.sender` to 0, and claim rewards * if rewards to claim */ function withdrawAll() external; /** * @notice function that allows a user to withdraw its initial deposit * @param amount, amount to withdraw * @dev `block.timestamp` must be higher than `lockupPeriod` (lockupPeriod finished) * @dev `amount` must be higher than `0` * @dev `amount` must be lower or equal to the amount staked * withdraw reset all states variable for the `msg.sender` to 0, and claim rewards * if rewards to claim */ function withdraw(uint amount) external; /** * @notice function that returns the amount of total Staked tokens * for a specific user * @param stakeHolder, address of the user to check * @return uint amount of the total deposited Tokens by the caller */ function amountStaked(address stakeHolder) external view returns (uint); /** * @notice function that returns the amount of total Staked tokens * on the smart contract * @return uint amount of the total deposited Tokens */ function totalDeposited() external view returns (uint); /** * @notice function that returns the amount of pending rewards * that can be claimed by the user * @param stakeHolder, address of the user to be checked * @return uint amount of claimable rewards */ function rewardOf(address stakeHolder) external view returns (uint); /** * @notice function that claims pending rewards * @dev transfer the pending rewards to the `msg.sender` */ function claimRewards() external; /** * @dev Emitted when `amount` tokens are deposited into * staking platform */ event Deposit(address indexed owner, uint amount); /** * @dev Emitted when user withdraw deposited `amount` */ event Withdraw(address indexed owner, uint amount); /** * @dev Emitted when `stakeHolder` claim rewards */ event Claim(address indexed stakeHolder, uint amount); /** * @dev Emitted when staking has started */ event StartStaking(uint startPeriod, uint lockupPeriod, uint endingPeriod); } // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @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); } } // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) // OpenZeppelin Contracts (last updated v4.5.0) (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 * ==== * * [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); } } } } /** * @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"); } } } /// @author RetreebInc /// @title Staking Platform with fixed APY and lockup contract StakingPlatform is IStakingPlatform, Ownable { using SafeERC20 for IERC20; IERC20 public immutable token; IERC20 public immutable tokenExtra; uint256 public immutable fixedAPY; uint public immutable stakingDuration; uint public immutable lockupDuration; uint public immutable stakingMax; uint public startPeriod; uint public lockupPeriod; uint public endPeriod; uint private _totalStaked; uint internal _precision = 1E6; mapping(address => uint) public staked; mapping(address => uint) private _rewardsToClaim; mapping(address => uint) public _userStartTime; /** * @notice constructor contains all the parameters of the staking platform * @dev all parameters are immutable */ constructor(address _token, address _tokenExtra, uint256 _fixedAPY, uint _durationInDays, uint _lockDurationInDays, uint _maxAmountStaked) { stakingDuration = _durationInDays * 1 days; lockupDuration = _lockDurationInDays * 1 days; token = IERC20(_token); tokenExtra = IERC20(_tokenExtra); fixedAPY = _fixedAPY; stakingMax = _maxAmountStaked; } /** * @notice function that start the staking * @dev set `startPeriod` to the current current `block.timestamp` * set `lockupPeriod` which is `block.timestamp` + `lockupDuration` * and `endPeriod` which is `startPeriod` + `stakingDuration` */ function startStaking() external override onlyOwner { require(startPeriod == 0, "Staking has already started"); startPeriod = block.timestamp; lockupPeriod = block.timestamp + lockupDuration; endPeriod = block.timestamp + stakingDuration; emit StartStaking(startPeriod, lockupDuration, endPeriod); } /** * @notice function that allows a user to deposit tokens * @dev user must first approve the amount to deposit before calling this function, * cannot exceed the `maxAmountStaked` * @param amount, the amount to be deposited * @dev `endPeriod` to equal 0 (Staking didn't started yet), * or `endPeriod` more than current `block.timestamp` (staking not finished yet) * @dev `totalStaked + amount` must be less than `stakingMax` * @dev that the amount deposited should greater than 0 */ function deposit(uint amount) external override { require(endPeriod == 0 || endPeriod > block.timestamp, "Staking period ended"); require(_totalStaked + amount <= stakingMax, "Amount staked exceeds MaxStake"); require(amount > 0, "Amount must be greater than 0"); if (_userStartTime[_msgSender()] == 0) { _userStartTime[_msgSender()] = block.timestamp; } _updateRewards(); staked[_msgSender()] += amount; _totalStaked += amount; token.safeTransferFrom(_msgSender(), address(this), amount); emit Deposit(_msgSender(), amount); } /** * @notice function that allows a user to withdraw its initial deposit * @param amount, amount to withdraw * @dev `block.timestamp` must be higher than `lockupPeriod` (lockupPeriod finished) * @dev `amount` must be higher than `0` * @dev `amount` must be lower or equal to the amount staked * withdraw reset all states variable for the `msg.sender` to 0, and claim rewards * if rewards to claim */ function withdraw(uint amount) external override { require(block.timestamp >= lockupPeriod, "No withdraw until lockup ends"); require(amount > 0, "Amount must be greater than 0"); require(amount <= staked[_msgSender()], "Amount higher than stakedAmount"); _updateRewards(); if (_rewardsToClaim[_msgSender()] > 0) { _claimRewards(); } _totalStaked -= amount; staked[_msgSender()] -= amount; token.safeTransfer(_msgSender(), amount); emit Withdraw(_msgSender(), amount); } /** * @notice function that allows a user to withdraw its initial deposit * @dev must be called only when `block.timestamp` >= `lockupPeriod` * @dev `block.timestamp` higher than `lockupPeriod` (lockupPeriod finished) * withdraw reset all states variable for the `msg.sender` to 0, and claim rewards * if rewards to claim */ function withdrawAll() external override { require(block.timestamp >= lockupPeriod, "No withdraw until lockup ends"); _updateRewards(); if (_rewardsToClaim[_msgSender()] > 0) { _claimRewards(); } _userStartTime[_msgSender()] = 0; _totalStaked -= staked[_msgSender()]; uint stakedBalance = staked[_msgSender()]; staked[_msgSender()] = 0; token.safeTransfer(_msgSender(), stakedBalance); emit Withdraw(_msgSender(), stakedBalance); } /** * @notice claim all remaining balance on the contract * Residual balance is all the remaining tokens that have not been distributed * (e.g, in case the number of stakeholders is not sufficient) * @dev Can only be called one year after the end of the staking period * Cannot claim initial stakeholders deposit */ function withdrawResidualBalance() external onlyOwner { uint balance = token.balanceOf(address(this)); uint residualBalance = balance - (_totalStaked); require(residualBalance > 0, "No residual Balance to withdraw"); token.safeTransfer(owner(), residualBalance); } function withdrawResidualBalanceExtra() external onlyOwner { uint balanceExtra = tokenExtra.balanceOf(address(this)); require(balanceExtra > 0, "No residual Balance to withdraw"); tokenExtra.safeTransfer(owner(), balanceExtra); } /** * @notice function that returns the amount of total Staked tokens * for a specific user * @param stakeHolder, address of the user to check * @return uint amount of the total deposited Tokens by the caller */ function amountStaked(address stakeHolder) external view override returns (uint){ return staked[stakeHolder]; } /** * @notice function that returns the amount of total Staked tokens * on the smart contract * @return uint amount of the total deposited Tokens */ function totalDeposited() external view override returns (uint) { return _totalStaked; } /** * @notice function that returns the amount of pending rewards * that can be claimed by the user * @param stakeHolder, address of the user to be checked * @return uint amount of claimable rewards */ function rewardOf(address stakeHolder) external view override returns (uint){ return _calculateRewards(stakeHolder); } /** * @notice function that claims pending rewards * @dev transfer the pending rewards to the `msg.sender` */ function claimRewards() external override { _claimRewards(); } /** * @notice calculate rewards based on the `fixedAPY`, `_percentageTimeRemaining()` * @dev the higher is the precision and the more the time remaining will be precise * @param stakeHolder, address of the user to be checked * @return uint amount of claimable tokens of the specified address */ function _calculateRewards(address stakeHolder) internal view returns (uint){ if (startPeriod == 0 || staked[stakeHolder] == 0) { return 0; } return (((staked[stakeHolder] * fixedAPY) * _percentageTimeRemaining(stakeHolder)) / (_precision * 100)) + _rewardsToClaim[stakeHolder]; } /** * @notice function that returns the remaining time in seconds of the staking period * @dev the higher is the precision and the more the time remaining will be precise * @param stakeHolder, address of the user to be checked * @return uint percentage of time remaining * precision */ function _percentageTimeRemaining(address stakeHolder) internal view returns (uint){ bool early = startPeriod > _userStartTime[stakeHolder]; uint startTime; if (endPeriod > block.timestamp) { startTime = early ? startPeriod : _userStartTime[stakeHolder]; uint timeRemaining = stakingDuration - (block.timestamp - startTime); return (_precision * (stakingDuration - timeRemaining)) / stakingDuration; } startTime = early ? 0 : stakingDuration - (endPeriod - _userStartTime[stakeHolder]); return (_precision * (stakingDuration - startTime)) / stakingDuration; } /** * @notice internal function that claims pending rewards * @dev transfer the pending rewards to the user address */ function _claimRewards() private { _updateRewards(); uint rewardsToClaim = _rewardsToClaim[_msgSender()]; require(rewardsToClaim > 0, "Nothing to claim"); _rewardsToClaim[_msgSender()] = 0; token.safeTransfer(_msgSender(), rewardsToClaim); //Transfer main token. tokenExtra.safeTransfer(_msgSender(), rewardsToClaim); //Transfer extra token. emit Claim(_msgSender(), rewardsToClaim); } /** * @notice function that update pending rewards * and shift them to rewardsToClaim * @dev update rewards claimable * and check the time spent since deposit for the `msg.sender` */ function _updateRewards() private { _rewardsToClaim[_msgSender()] = _calculateRewards(_msgSender()); _userStartTime[_msgSender()] = (block.timestamp >= endPeriod) ? endPeriod : block.timestamp; } }
calculate rewards based on the `fixedAPY`, `_percentageTimeRemaining()` the higher is the precision and the more the time remaining will be precise stakeHolder, address of the user to be checked return uint amount of claimable tokens of the specified address/
function _calculateRewards(address stakeHolder) internal view returns (uint){ if (startPeriod == 0 || staked[stakeHolder] == 0) { return 0; } return (((staked[stakeHolder] * fixedAPY) * _percentageTimeRemaining(stakeHolder)) / (_precision * 100)) + _rewardsToClaim[stakeHolder]; }
10,678,993
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; //import "hardhat/console.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {FixedPointMath} from "./libraries/FixedPointMath.sol"; import {IMintableERC20} from "./interfaces/IMintableERC20.sol"; import {Pool} from "./libraries/pools/Pool.sol"; import {Stake} from "./libraries/pools/Stake.sol"; import {StakingPools} from "./StakingPools.sol"; import "hardhat/console.sol"; /// @title StakingPools /// @dev A contract which allows users to stake to farm tokens. /// /// This contract is copied from Alchemix https://github.com/alchemix-finance/alchemix-protocol contract StakingPools is ReentrancyGuard { using FixedPointMath for FixedPointMath.FixedDecimal; using Pool for Pool.Data; using Pool for Pool.List; using SafeERC20 for IERC20; using SafeMath for uint256; using Stake for Stake.Data; event PendingGovernanceUpdated( address pendingGovernance ); event GovernanceUpdated( address governance ); event RewardRateUpdated( uint256 rewardRate ); event PoolRewardWeightUpdated( uint256 indexed poolId, uint256 rewardWeight ); event PoolCreated( uint256 indexed poolId, IERC20 indexed token ); event TokensDeposited( address indexed user, uint256 indexed poolId, uint256 amount ); event TokensWithdrawn( address indexed user, uint256 indexed poolId, uint256 amount ); event TokensClaimed( address indexed user, uint256 indexed poolId, uint256 amount ); /// @dev The token which will be minted as a reward for staking. IMintableERC20 public reward; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; address public pendingGovernance; /// @dev address of the vesting contract address public vesting; /// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool /// will return an identifier of zero. mapping(IERC20 => uint256) public tokenPoolIds; /// @dev The context shared between the pools. Pool.Context private _ctx; /// @dev A list of all of the pools. Pool.List private _pools; /// @dev A mapping of all of the user stakes mapped first by pool and then by address. mapping(address => mapping(uint256 => Stake.Data)) private _stakes; /// @dev like _stakes but for vesting based staking mapping(address => mapping(uint256 => Stake.Data)) private _vestingStakes; constructor( IMintableERC20 _reward, address _governance ) { require(_governance != address(0), "StakingPools: governance address cannot be 0x0"); reward = _reward; governance = _governance; } /// @dev A modifier which reverts when the caller is not the governance. modifier onlyGovernance() { require(msg.sender == governance, "StakingPools: only governance"); _; } modifier onlyVesting() { require(msg.sender == vesting, "StakingPools: only vesting"); _; } /// @dev Sets the governance. /// /// This function can only called by the current governance. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGovernance { require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev used to set the vesting contract address function setVesting(address _vesting) external onlyGovernance { vesting = _vesting; } function acceptGovernance() external { require(msg.sender == pendingGovernance, "StakingPools: only pending governance"); address _pendingGovernance = pendingGovernance; governance = _pendingGovernance; emit GovernanceUpdated(_pendingGovernance); } /// @dev Sets the distribution reward rate. /// /// This will update all of the pools. /// /// @param _rewardRate The number of tokens to distribute per second. function setRewardRate(uint256 _rewardRate) external onlyGovernance { _updatePools(); _ctx.rewardRate = _rewardRate; emit RewardRateUpdated(_rewardRate); } /// @dev Creates a new pool. /// /// The created pool will need to have its reward weight initialized before it begins generating rewards. /// /// @param _token The token the pool will accept for staking. /// /// @return the identifier for the newly created pool. function createPool(IERC20 _token) external onlyGovernance returns (uint256) { require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool"); uint256 _poolId = _pools.length(); _pools.push(Pool.Data({ token: _token, totalDeposited: 0, rewardWeight: 0, accumulatedRewardWeight: FixedPointMath.FixedDecimal(0), lastUpdatedBlock: block.number })); tokenPoolIds[_token] = _poolId + 1; emit PoolCreated(_poolId, _token); return _poolId; } /// @dev Sets the reward weights of all of the pools. /// /// @param _rewardWeights The reward weights of all of the pools. function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance { require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch"); _updatePools(); uint256 _totalRewardWeight = _ctx.totalRewardWeight; for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) { Pool.Data storage _pool = _pools.get(_poolId); uint256 _currentRewardWeight = _pool.rewardWeight; if (_currentRewardWeight == _rewardWeights[_poolId]) { continue; } // FIXME _totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]); _pool.rewardWeight = _rewardWeights[_poolId]; emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]); } _ctx.totalRewardWeight = _totalRewardWeight; } /// @dev like deposit but used to enbale staking of vested tokens /// @notice the vesting account must not be used for staking outside of the vesting contract saking function depositVesting( address _account, uint256 _poolId, uint256 _depositAmount ) external onlyVesting nonReentrant returns (bool) { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _vestingStakes[_account][_poolId]; _stake.update(_pool, _ctx); _pool.totalDeposited = _pool.totalDeposited.add(_depositAmount); _stake.totalDeposited = _stake.totalDeposited.add(_depositAmount); // we need to transfer the tokens from the vesting address to this contract _pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount); emit TokensDeposited(_account, _poolId, _depositAmount); return true; } /// @dev allows the vesting contract to eithr withdraw, claim, or exit staking /// @dev if you want to claim provide `false` for both `_doWithdraw` and `_doExit` /// @dev if you want to completely exit provide `true` for both `_doWithdraw` and `_doExit` /// @dev for exiting you may supply a value of `0` for _withdrawAmount function withdrawOrClaimOrExitVesting( address _account, uint256 _poolId, uint256 _withdrawAmount, bool _doWithdraw, bool _doExit ) external onlyVesting nonReentrant // (ok, amountClaimed) returns (bool, uint256) { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _vestingStakes[_account][_poolId]; _stake.update(_pool, _ctx); // claim uint256 _claimAmount = _stake.totalUnclaimed; _stake.totalUnclaimed = 0; // make sure to mint to the vesting contract reward.mint(msg.sender, _claimAmount); emit TokensClaimed(_account, _poolId, _claimAmount); if (_doWithdraw) { // if exit withdraw all staked amount if (_doExit) { _withdrawAmount = _stake.totalDeposited; } // if the amount they are attempting to withdraw is more // than the amount they have staked, just withdraw total deposited if (_withdrawAmount > _stake.totalDeposited) { _withdrawAmount = _stake.totalDeposited; } _pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount); _stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount); // make sure to transfer to the vesting contract _pool.token.safeTransfer(msg.sender, _withdrawAmount); emit TokensWithdrawn(_account, _poolId, _withdrawAmount); } return (true, _claimAmount); } /// @dev Stakes tokens into a pool. /// /// @param _poolId the pool to deposit tokens into. /// @param _depositAmount the amount of tokens to deposit. function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _deposit(msg.sender, _poolId, _depositAmount); } /// @dev Withdraws staked tokens from a pool. /// /// @param _poolId The pool to withdraw staked tokens from. /// @param _withdrawAmount The number of tokens to withdraw. function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(msg.sender, _poolId); _withdraw(msg.sender, _poolId, _withdrawAmount); } /// @dev Claims all rewarded tokens from a pool. /// /// @param _poolId The pool to claim rewards from. /// /// @notice use this function to claim the tokens from a corresponding pool by ID. function claim(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(msg.sender, _poolId); } /// @dev Claims all rewards from a pool and then withdraws all staked tokens. /// /// @param _poolId the pool to exit from. function exit(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(msg.sender, _poolId); _withdraw(msg.sender,_poolId, _stake.totalDeposited); } /// @dev Gets the rate at which tokens are minted to stakers for all pools. /// /// @return the reward rate. function rewardRate() external view returns (uint256) { return _ctx.rewardRate; } /// @dev Gets the total reward weight between all the pools. /// /// @return the total reward weight. function totalRewardWeight() external view returns (uint256) { return _ctx.totalRewardWeight; } /// @dev Gets the number of pools that exist. /// /// @return the pool count. function poolCount() external view returns (uint256) { return _pools.length(); } /// @dev Gets the token a pool accepts. /// /// @param _poolId the identifier of the pool. /// /// @return the token. function getPoolToken(uint256 _poolId) external view returns (IERC20) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.token; } /// @dev Gets the total amount of funds staked in a pool. /// /// @param _poolId the identifier of the pool. /// /// @return the total amount of staked or deposited tokens. function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.totalDeposited; } /// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block. /// /// @param _poolId the identifier of the pool. /// /// @return the pool reward weight. function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.rewardWeight; } /// @dev Gets the amount of tokens per block being distributed to stakers for a pool. /// /// @param _poolId the identifier of the pool. /// /// @return the pool reward rate. function getPoolRewardRate(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.getRewardRate(_ctx); } /// @dev Gets the number of tokens a user has staked into a pool. /// /// @param _account The account to query. /// @param _poolId the identifier of the pool. /// /// @return the amount of deposited tokens. function getStakeTotalDeposited(address _account, uint256 _poolId, bool _vesting) external view returns (uint256) { if (_vesting) { Stake.Data storage _stake = _vestingStakes[_account][_poolId]; return _stake.totalDeposited; } else { Stake.Data storage _stake = _stakes[_account][_poolId]; return _stake.totalDeposited; } } /// @dev Gets the number of unclaimed reward tokens a user can claim from a pool. /// /// @param _account The account to get the unclaimed balance of. /// @param _poolId The pool to check for unclaimed rewards. /// /// @return the amount of unclaimed reward tokens a user has in a pool. function getStakeTotalUnclaimed(address _account, uint256 _poolId, bool _vesting) external view returns (uint256) { if (_vesting) { Stake.Data storage _stake = _vestingStakes[_account][_poolId]; return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx); } else { Stake.Data storage _stake = _stakes[_account][_poolId]; return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx); } } /// @dev Updates all of the pools. function _updatePools() internal { for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); } } /// @dev Stakes tokens into a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId the pool to deposit tokens into. /// @param _depositAmount the amount of tokens to deposit. function _deposit(address _account, uint256 _poolId, uint256 _depositAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[_account][_poolId]; _pool.totalDeposited = _pool.totalDeposited.add(_depositAmount); _stake.totalDeposited = _stake.totalDeposited.add(_depositAmount); _pool.token.safeTransferFrom(_account, address(this), _depositAmount); emit TokensDeposited(_account, _poolId, _depositAmount); } /// @dev Withdraws staked tokens from a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId The pool to withdraw staked tokens from. /// @param _withdrawAmount The number of tokens to withdraw. function _withdraw(address _account, uint256 _poolId, uint256 _withdrawAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[_account][_poolId]; _pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount); _stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount); _pool.token.safeTransfer(_account, _withdrawAmount); emit TokensWithdrawn(_account, _poolId, _withdrawAmount); } /// @dev Claims all rewarded tokens from a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId The pool to claim rewards from. /// /// @notice use this function to claim the tokens from a corresponding pool by ID. function _claim(address _account, uint256 _poolId) internal { Stake.Data storage _stake = _stakes[_account][_poolId]; uint256 _claimAmount = _stake.totalUnclaimed; _stake.totalUnclaimed = 0; reward.mint(_account, _claimAmount); emit TokensClaimed(_account, _poolId, _claimAmount); } } // 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 "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.7.0; library FixedPointMath { uint256 public constant DECIMALS = 18; uint256 public constant SCALAR = 10**DECIMALS; struct FixedDecimal { uint256 x; } function fromU256(uint256 value) internal pure returns (FixedDecimal memory) { uint256 x; require(value == 0 || (x = value * SCALAR) / SCALAR == value); return FixedDecimal(x); } function maximumValue() internal pure returns (FixedDecimal memory) { return FixedDecimal(uint256(-1)); } function add(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (FixedDecimal memory) { uint256 x; require((x = self.x + value.x) >= self.x); return FixedDecimal(x); } function add(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { return add(self, fromU256(value)); } function sub(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (FixedDecimal memory) { uint256 x; require((x = self.x - value.x) <= self.x); return FixedDecimal(x); } function sub(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { return sub(self, fromU256(value)); } function mul(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { uint256 x; require(value == 0 || (x = self.x * value) / value == self.x); return FixedDecimal(x); } function div(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { require(value != 0); return FixedDecimal(self.x / value); } function cmp(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (int256) { if (self.x < value.x) { return -1; } if (self.x > value.x) { return 1; } return 0; } function decode(FixedDecimal memory self) internal pure returns (uint256) { return self.x / SCALAR; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.7.0; import {IDetailedERC20} from "./IDetailedERC20.sol"; interface IMintableERC20 is IDetailedERC20{ function mint(address _recipient, uint256 _amount) external; function burnFrom(address account, uint256 amount) external; function lowerHasMinted(uint256 amount)external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../FixedPointMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; import "hardhat/console.sol"; /// @title Pool /// /// @dev A library which provides the Pool data struct and associated functions. library Pool { using FixedPointMath for FixedPointMath.FixedDecimal; using Pool for Pool.Data; using Pool for Pool.List; using SafeMath for uint256; struct Context { uint256 rewardRate; uint256 totalRewardWeight; } struct Data { IERC20 token; uint256 totalDeposited; uint256 rewardWeight; FixedPointMath.FixedDecimal accumulatedRewardWeight; uint256 lastUpdatedBlock; } struct List { Data[] elements; } /// @dev Updates the pool. /// /// @param _ctx the pool context. function update(Data storage _data, Context storage _ctx) internal { _data.accumulatedRewardWeight = _data.getUpdatedAccumulatedRewardWeight(_ctx); _data.lastUpdatedBlock = block.number; } /// @dev Gets the rate at which the pool will distribute rewards to stakers. /// /// @param _ctx the pool context. /// /// @return the reward rate of the pool in tokens per block. function getRewardRate(Data storage _data, Context storage _ctx) internal view returns (uint256) { // console.log("get reward rate"); // console.log(uint(_data.rewardWeight)); // console.log(uint(_ctx.totalRewardWeight)); // console.log(uint(_ctx.rewardRate)); return _ctx.rewardRate.mul(_data.rewardWeight).div(_ctx.totalRewardWeight); } /// @dev Gets the accumulated reward weight of a pool. /// /// @param _ctx the pool context. /// /// @return the accumulated reward weight. function getUpdatedAccumulatedRewardWeight(Data storage _data, Context storage _ctx) internal view returns (FixedPointMath.FixedDecimal memory) { if (_data.totalDeposited == 0) { return _data.accumulatedRewardWeight; } uint256 _elapsedTime = block.number.sub(_data.lastUpdatedBlock); if (_elapsedTime == 0) { return _data.accumulatedRewardWeight; } uint256 _rewardRate = _data.getRewardRate(_ctx); uint256 _distributeAmount = _rewardRate.mul(_elapsedTime); if (_distributeAmount == 0) { return _data.accumulatedRewardWeight; } FixedPointMath.FixedDecimal memory _rewardWeight = FixedPointMath.fromU256(_distributeAmount).div(_data.totalDeposited); return _data.accumulatedRewardWeight.add(_rewardWeight); } /// @dev Adds an element to the list. /// /// @param _element the element to add. function push(List storage _self, Data memory _element) internal { _self.elements.push(_element); } /// @dev Gets an element from the list. /// /// @param _index the index in the list. /// /// @return the element at the specified index. function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; } /// @dev Gets the last element in the list. /// /// This function will revert if there are no elements in the list. ///ck /// @return the last element in the list. function last(List storage _self) internal view returns (Data storage) { return _self.elements[_self.lastIndex()]; } /// @dev Gets the index of the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the index of the last element. function lastIndex(List storage _self) internal view returns (uint256) { uint256 _length = _self.length(); return _length.sub(1, "Pool.List: list is empty"); } /// @dev Gets the number of elements in the list. /// /// @return the number of elements. function length(List storage _self) internal view returns (uint256) { return _self.elements.length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../FixedPointMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; import {Pool} from "./Pool.sol"; import "hardhat/console.sol"; /// @title Stake /// /// @dev A library which provides the Stake data struct and associated functions. library Stake { using FixedPointMath for FixedPointMath.FixedDecimal; using Pool for Pool.Data; using SafeMath for uint256; using Stake for Stake.Data; struct Data { uint256 totalDeposited; uint256 totalUnclaimed; FixedPointMath.FixedDecimal lastAccumulatedWeight; } function update(Data storage _self, Pool.Data storage _pool, Pool.Context storage _ctx) internal { _self.totalUnclaimed = _self.getUpdatedTotalUnclaimed(_pool, _ctx); _self.lastAccumulatedWeight = _pool.getUpdatedAccumulatedRewardWeight(_ctx); } function getUpdatedTotalUnclaimed(Data storage _self, Pool.Data storage _pool, Pool.Context storage _ctx) internal view returns (uint256) { FixedPointMath.FixedDecimal memory _currentAccumulatedWeight = _pool.getUpdatedAccumulatedRewardWeight(_ctx); FixedPointMath.FixedDecimal memory _lastAccumulatedWeight = _self.lastAccumulatedWeight; if (_currentAccumulatedWeight.cmp(_lastAccumulatedWeight) == 0) { return _self.totalUnclaimed; } uint256 _distributedAmount = _currentAccumulatedWeight .sub(_lastAccumulatedWeight) .mul(_self.totalDeposited) .decode(); return _self.totalUnclaimed.add(_distributedAmount); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.7.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDetailedERC20 is IERC20 { function name() external returns (string memory); function symbol() external returns (string memory); function decimals() external returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } }
Claims all rewarded tokens from a pool. _poolId The pool to claim rewards from. use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(msg.sender, _poolId); }
6,987,520
./partial_match/1/0x2087bA763238C4E5fd04211DA69AA7b129432579/sources/DeviantsCrimsonPass.sol
Returns the state of the Phase1 sale (true if is open, false if is closed)/
function getPhase1Status() public view returns(bool){ if((block.timestamp >= startPhase1 && block.timestamp <= endPhase1) || !pausePhase1) { return true; return false; } }
2,826,433
./partial_match/1313161554/0x2921Cc3377C717B600468cfaB437a83C2dE5039d/sources/contracts/NonfungiblePositionManager.sol
@inheritdoc INonfungiblePositionManager allow collecting to the nft position manager address with address 0 trigger an update of the position fees owed and fee growth snapshots if it has any liquidity
function collect(CollectParams calldata params) external payable override isAuthorizedForToken(params.tokenId) returns (uint256 amount0, uint256 amount1) { require(params.amount0Max > 0 || params.amount1Max > 0); address recipient = params.recipient == address(0) ? address(this) : params.recipient; Position storage position = _positions[params.tokenId]; PoolAddress.PoolKey memory poolKey = _poolIdToPoolKey[position.poolId]; IDonaswapV3Pool pool = IDonaswapV3Pool(PoolAddress.computeAddress(deployer, poolKey)); (uint128 tokensOwed0, uint128 tokensOwed1) = (position.tokensOwed0, position.tokensOwed1); if (position.liquidity > 0) { pool.burn(position.tickLower, position.tickUpper, 0); (, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(PositionKey.compute(address(this), position.tickLower, position.tickUpper)); tokensOwed0 += uint128( FullMath.mulDiv( feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128, position.liquidity, FixedPoint128.Q128 ) ); tokensOwed1 += uint128( FullMath.mulDiv( feeGrowthInside1LastX128 - position.feeGrowthInside1LastX128, position.liquidity, FixedPoint128.Q128 ) ); position.feeGrowthInside0LastX128 = feeGrowthInside0LastX128; position.feeGrowthInside1LastX128 = feeGrowthInside1LastX128; } ( params.amount0Max > tokensOwed0 ? tokensOwed0 : params.amount0Max, params.amount1Max > tokensOwed1 ? tokensOwed1 : params.amount1Max ); recipient, position.tickLower, position.tickUpper, amount0Collect, amount1Collect ); emit Collect(params.tokenId, recipient, amount0Collect, amount1Collect); }
16,944,119