file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
//pragma solidity ^0.3.6; contract Token { function balanceOf(address user) constant returns (uint256 balance); function transfer(address receiver, uint amount) returns(bool); } // A Sub crowdfunding contract. Its only purpose is to redirect ether it receives to the // main crowdfunding contract. This mecanism is usefull to know the sponsor to // reward for an indirect donation. You can't give for someone else when you give through // these contracts contract AltCrowdfunding { Crowdfunding mainCf ; // Referenre to the main crowdfunding contract function AltCrowdfunding(address cf){ // Construct the altContract with a reference to the main one mainCf = Crowdfunding(cf); } function(){ mainCf.giveFor.value(msg.value)(msg.sender); // Relay Ether sent to the main crowndfunding contract } } contract Crowdfunding { struct Backer { uint weiGiven; // Amount of Ether given uint ungivenNxc ; // (pending) If the first goal of the crowdfunding is not reached yet the NxC are stored here } struct Sponsor { uint nxcDirected; // How much milli Nxc this sponsor sold for us uint earnedNexium; // How much milli Nxc this sponsor earned by solding Nexiums for us address sponsorAddress; // Where Nexiums earned by a sponsor are sent uint sponsorBonus; uint backerBonus; } //Every public variable can be read by everyone from the blockchain Token public nexium; // Nexium contract reference address public owner; // Contract admin (beyond the void) address public beyond; // Address that will receive ether when the first step is be reached address public bitCrystalEscrow; // Our escrow for Bitcrystals (ie EverdreamSoft) uint public startingEtherValue; // How much milli Nxc are sent by ether uint public stepEtherValue; // For every stage of the crowdfunding, the number of Nexium sent by ether is decreased by this number uint public collectedEth; // Collected ether in wei uint public nxcSold; // How much milli Nxc were sold uint public perStageNxc; // How much milli Nxc we much sell for each stage uint public nxcPerBcy; // How much milli Nxc we give for each Bitcrystal uint public collectedBcy; // Collected Bitcrystals uint public minInvest; // Minimum to invest (in wei) uint public startDate; // crowndfunding startdate uint public endDate; // crowndfunding enddate bool public isLimitReached; // Tell if the first stage of the CrowdFunding is reached, false when not set address[] public backerList; // Addresses of all backers address[] public altList; // List of alternative contracts for sponsoring (useless for this contract) mapping(address => Sponsor) public sponsorList; // The sponsor linked to an alternative contract mapping(address => Backer) public backers; // The Backer for a given address modifier onlyBy(address a){ if (msg.sender != a) throw; // Auth modifier, if the msg.sender isn't the expected address, throw. _ } event Gave(address); // //--------------------------------------\\ function Crowdfunding() { // Constructor of the contract. set the different variables nexium = Token(0x45e42d659d9f9466cd5df622506033145a9b89bc); // Nexium contract address beyond = 0x89E7a245d5267ECd5Bf4cA4C1d9D4D5A14bbd130 ; owner = msg.sender; minInvest = 10 finney; startingEtherValue = 700*1000; stepEtherValue = 25*1000; nxcPerBcy = 14; perStageNxc = 5000000 * 1000; startDate = 1478012400 ; endDate = 1480604400 ; bitCrystalEscrow = 0x72037bf2a3fc312cde40c7f7cd7d2cef3ad8c193; } //--------------------------------------\\ // Use this function to buy Nexiums for someone (can be you of course) function giveFor(address beneficiary){ if (msg.value < minInvest) throw; // Throw when the minimum to invest isn't reached if (endDate < now || (now < startDate && now > startDate - 3 hours )) throw; // Check if the crowdfunding is started and not already over // Computing the current amount of Nxc we send per ether. uint currentEtherValue = getCurrEthValue(); //it's possible to invest before the begining of the crowdfunding but the price is x10. //Allow backers to test the contract before the begining. if(now < startDate) currentEtherValue /= 10; // Computing the number of milli Nxc we will send to the beneficiary uint givenNxc = (msg.value * currentEtherValue)/(1 ether); nxcSold += givenNxc; //Updating the sold Nxc amount if (nxcSold >= perStageNxc) isLimitReached = true ; Sponsor sp = sponsorList[msg.sender]; //Check if the user gives through a sponsor contract if (sp.sponsorAddress != 0x0000000000000000000000000000000000000000) { sp.nxcDirected += givenNxc; // Update the number of milli Nxc this sponsor sold for us // This part compute the bonus rate NxC the sponsor will have depending on the total of Nxc he sold. uint bonusRate = sp.nxcDirected / 80000000; if (bonusRate > sp.sponsorBonus) bonusRate = sp.sponsorBonus; // Giving to the sponsor the amount of Nxc he earned by this last donation uint sponsorNxc = (sp.nxcDirected * bonusRate)/100 - sp.earnedNexium; if (!giveNxc(sp.sponsorAddress, sponsorNxc))throw; sp.earnedNexium += sponsorNxc; // Update the number of milli Nxc this sponsor earned givenNxc = (givenNxc*(100 + sp.backerBonus))/100; // Increase by x% the number of Nxc we will give to the backer } if (!giveNxc(beneficiary, givenNxc))throw; // Give to the Backer the Nxc he just earned // Add the new Backer to the list, if he gave for the first time Backer backer = backers[beneficiary]; if (backer.weiGiven == 0){ backerList[backerList.length++] = beneficiary; } backer.weiGiven += msg.value; // Update the gave wei of this Backer collectedEth += msg.value; // Update the total wei collcted during the crowdfunding Gave(beneficiary); // Trigger an event } // If you gave ether before the first stage is reached you might have some ungiven // Nxc for your address. This function, if called, will give you the nexiums you didn't // received. /!\ Nexium bonuses for your partner rank will not be given during the crowdfunding function claimNxc(){ if (!isLimitReached) throw; address to = msg.sender; nexium.transfer(to, backers[to].ungivenNxc); backers[to].ungivenNxc = 0; } // This function can be called after the crowdfunding if the first goal is not reached // It gives back the ethers of the specified address function getBackEther(){ getBackEtherFor(msg.sender); } function getBackEtherFor(address account){ if (now > endDate && !isLimitReached){ uint sentBack = backers[account].weiGiven; backers[account].weiGiven = 0; // No DAO style re entrance ;) if(!account.send(sentBack))throw; } else throw ; } // The anonymous function automatically make a donation for the person who gave ethers function(){ giveFor(msg.sender); } //--------------------------------------\\ //Create a new sponsoring contract function addAlt(address sponsor, uint _sponsorBonus, uint _backerBonus) onlyBy(owner){ if (_sponsorBonus > 10 || _backerBonus > 10 || _sponsorBonus + _backerBonus > 15) throw; altList[altList.length++] = address(new AltCrowdfunding(this)); sponsorList[altList[altList.length -1]] = Sponsor(0, 0, sponsor, _sponsorBonus, _backerBonus); } // Set the value of BCY gave by the SOG network. Only our BCY escrow can modify it. function setBCY(uint newValue) onlyBy(bitCrystalEscrow){ if (now < startDate || now > endDate) throw; if (newValue != 0 && newValue < 714285714) collectedBcy = newValue; // 714285714 * 14 ~= 10 000 000 000 mili Nxc maximum to avoid wrong value else throw; } // If the minimum goal is reached, beyond the void can have the ethers stored on the contract function withdrawEther(address to, uint amount) onlyBy(owner){ if (!isLimitReached) throw; var r = to.send(amount); } function withdrawNxc(address to, uint amount) onlyBy(owner){ nexium.transfer(to, amount); } //If there are still Nexiums or Ethers on the contract after 100 days after the end of the crowdfunding //This function send all of it to the multi sig of the beyond the void team (emergency case) function blackBox(){ if (now < endDate + 100 days)throw; nexium.transfer(beyond, nexium.balanceOf(this)); var r = beyond.send(this.balance); } // Each time this contract send Nxc this function is called. It check if // the minimum goal is reached before sending any nexiums out. function giveNxc(address to, uint amount) internal returns (bool){ bool res; if (isLimitReached){ if (nexium.transfer(to, amount)){ // If there is some ungiven Nxc remaining for this address, send it. if (backers[to].ungivenNxc != 0){ res = nexium.transfer(to, backers[to].ungivenNxc); backers[to].ungivenNxc = 0; } else { res = true; } } else { res = false; } // If the limit is not reached yet, the nexiums are not sent but stored in the contract waiting this goal being reached. // They are released when the same backer gives ether while the limit is reached, or by claiming them after the minimal goal is reached . } else { backers[to].ungivenNxc += amount; res = true; } return res; } //--------------------------------------\\ function getCurrEthValue() returns(uint){ return startingEtherValue - stepEtherValue * ((nxcSold + collectedBcy * nxcPerBcy)/perStageNxc); } }
How much milli Nxc this sponsor earned by solding Nexiums for us
uint earnedNexium;
7,313,824
[ 1, 44, 543, 9816, 312, 16607, 423, 6511, 333, 272, 500, 2467, 425, 1303, 329, 635, 272, 1673, 310, 423, 338, 5077, 87, 364, 584, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 565, 2254, 425, 1303, 329, 50, 338, 5077, 31, 4766, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xE0Df94523C3CC81b8818ea97bcd326aA466A91dF/sources/GovernanceProxy.sol
* @author Balancer Labs @title Factor out the weight updates/ Type declarations
library SmartPoolManager { pragma experimental ABIEncoderV2; struct NewTokenParams { address addr; bool isCommitted; uint commitBlock; uint denorm; uint balance; } struct GradualUpdateParams { uint startBlock; uint endBlock; uint[] startWeights; uint[] endWeights; } function updateWeight( IConfigurableRightsPool self, IBPool bPool, address token, uint newWeight ) external { require(newWeight >= BalancerConstants.MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(newWeight <= BalancerConstants.MAX_WEIGHT, "ERR_MAX_WEIGHT"); uint currentWeight = bPool.getDenormalizedWeight(token); if (currentWeight == newWeight) { return; } uint currentBalance = bPool.getBalance(token); uint totalSupply = self.totalSupply(); uint totalWeight = bPool.getTotalDenormalizedWeight(); uint poolShares; uint deltaBalance; uint deltaWeight; uint newBalance; if (newWeight < currentWeight) { deltaWeight = BalancerSafeMath.bsub(currentWeight, newWeight); poolShares = BalancerSafeMath.bmul(totalSupply, BalancerSafeMath.bdiv(deltaWeight, totalWeight)); deltaBalance = BalancerSafeMath.bmul(currentBalance, BalancerSafeMath.bdiv(deltaWeight, currentWeight)); newBalance = BalancerSafeMath.bsub(currentBalance, deltaBalance); require(newBalance >= BalancerConstants.MIN_BALANCE, "ERR_MIN_BALANCE"); bPool.rebind(token, newBalance, newWeight); bool xfer = IERC20(token).transfer(msg.sender, deltaBalance); require(xfer, "ERR_ERC20_FALSE"); self.pullPoolShareFromLib(msg.sender, poolShares); self.burnPoolShareFromLib(poolShares); } else { deltaWeight = BalancerSafeMath.bsub(newWeight, currentWeight); require(BalancerSafeMath.badd(totalWeight, deltaWeight) <= BalancerConstants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); poolShares = BalancerSafeMath.bmul(totalSupply, BalancerSafeMath.bdiv(deltaWeight, totalWeight)); deltaBalance = BalancerSafeMath.bmul(currentBalance, BalancerSafeMath.bdiv(deltaWeight, currentWeight)); bool xfer = IERC20(token).transferFrom(msg.sender, address(this), deltaBalance); require(xfer, "ERR_ERC20_FALSE"); bPool.rebind(token, BalancerSafeMath.badd(currentBalance, deltaBalance), newWeight); self.mintPoolShareFromLib(poolShares); self.pushPoolShareFromLib(msg.sender, poolShares); } } function updateWeight( IConfigurableRightsPool self, IBPool bPool, address token, uint newWeight ) external { require(newWeight >= BalancerConstants.MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(newWeight <= BalancerConstants.MAX_WEIGHT, "ERR_MAX_WEIGHT"); uint currentWeight = bPool.getDenormalizedWeight(token); if (currentWeight == newWeight) { return; } uint currentBalance = bPool.getBalance(token); uint totalSupply = self.totalSupply(); uint totalWeight = bPool.getTotalDenormalizedWeight(); uint poolShares; uint deltaBalance; uint deltaWeight; uint newBalance; if (newWeight < currentWeight) { deltaWeight = BalancerSafeMath.bsub(currentWeight, newWeight); poolShares = BalancerSafeMath.bmul(totalSupply, BalancerSafeMath.bdiv(deltaWeight, totalWeight)); deltaBalance = BalancerSafeMath.bmul(currentBalance, BalancerSafeMath.bdiv(deltaWeight, currentWeight)); newBalance = BalancerSafeMath.bsub(currentBalance, deltaBalance); require(newBalance >= BalancerConstants.MIN_BALANCE, "ERR_MIN_BALANCE"); bPool.rebind(token, newBalance, newWeight); bool xfer = IERC20(token).transfer(msg.sender, deltaBalance); require(xfer, "ERR_ERC20_FALSE"); self.pullPoolShareFromLib(msg.sender, poolShares); self.burnPoolShareFromLib(poolShares); } else { deltaWeight = BalancerSafeMath.bsub(newWeight, currentWeight); require(BalancerSafeMath.badd(totalWeight, deltaWeight) <= BalancerConstants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); poolShares = BalancerSafeMath.bmul(totalSupply, BalancerSafeMath.bdiv(deltaWeight, totalWeight)); deltaBalance = BalancerSafeMath.bmul(currentBalance, BalancerSafeMath.bdiv(deltaWeight, currentWeight)); bool xfer = IERC20(token).transferFrom(msg.sender, address(this), deltaBalance); require(xfer, "ERR_ERC20_FALSE"); bPool.rebind(token, BalancerSafeMath.badd(currentBalance, deltaBalance), newWeight); self.mintPoolShareFromLib(poolShares); self.pushPoolShareFromLib(msg.sender, poolShares); } } function updateWeight( IConfigurableRightsPool self, IBPool bPool, address token, uint newWeight ) external { require(newWeight >= BalancerConstants.MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(newWeight <= BalancerConstants.MAX_WEIGHT, "ERR_MAX_WEIGHT"); uint currentWeight = bPool.getDenormalizedWeight(token); if (currentWeight == newWeight) { return; } uint currentBalance = bPool.getBalance(token); uint totalSupply = self.totalSupply(); uint totalWeight = bPool.getTotalDenormalizedWeight(); uint poolShares; uint deltaBalance; uint deltaWeight; uint newBalance; if (newWeight < currentWeight) { deltaWeight = BalancerSafeMath.bsub(currentWeight, newWeight); poolShares = BalancerSafeMath.bmul(totalSupply, BalancerSafeMath.bdiv(deltaWeight, totalWeight)); deltaBalance = BalancerSafeMath.bmul(currentBalance, BalancerSafeMath.bdiv(deltaWeight, currentWeight)); newBalance = BalancerSafeMath.bsub(currentBalance, deltaBalance); require(newBalance >= BalancerConstants.MIN_BALANCE, "ERR_MIN_BALANCE"); bPool.rebind(token, newBalance, newWeight); bool xfer = IERC20(token).transfer(msg.sender, deltaBalance); require(xfer, "ERR_ERC20_FALSE"); self.pullPoolShareFromLib(msg.sender, poolShares); self.burnPoolShareFromLib(poolShares); } else { deltaWeight = BalancerSafeMath.bsub(newWeight, currentWeight); require(BalancerSafeMath.badd(totalWeight, deltaWeight) <= BalancerConstants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); poolShares = BalancerSafeMath.bmul(totalSupply, BalancerSafeMath.bdiv(deltaWeight, totalWeight)); deltaBalance = BalancerSafeMath.bmul(currentBalance, BalancerSafeMath.bdiv(deltaWeight, currentWeight)); bool xfer = IERC20(token).transferFrom(msg.sender, address(this), deltaBalance); require(xfer, "ERR_ERC20_FALSE"); bPool.rebind(token, BalancerSafeMath.badd(currentBalance, deltaBalance), newWeight); self.mintPoolShareFromLib(poolShares); self.pushPoolShareFromLib(msg.sender, poolShares); } } function updateWeight( IConfigurableRightsPool self, IBPool bPool, address token, uint newWeight ) external { require(newWeight >= BalancerConstants.MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(newWeight <= BalancerConstants.MAX_WEIGHT, "ERR_MAX_WEIGHT"); uint currentWeight = bPool.getDenormalizedWeight(token); if (currentWeight == newWeight) { return; } uint currentBalance = bPool.getBalance(token); uint totalSupply = self.totalSupply(); uint totalWeight = bPool.getTotalDenormalizedWeight(); uint poolShares; uint deltaBalance; uint deltaWeight; uint newBalance; if (newWeight < currentWeight) { deltaWeight = BalancerSafeMath.bsub(currentWeight, newWeight); poolShares = BalancerSafeMath.bmul(totalSupply, BalancerSafeMath.bdiv(deltaWeight, totalWeight)); deltaBalance = BalancerSafeMath.bmul(currentBalance, BalancerSafeMath.bdiv(deltaWeight, currentWeight)); newBalance = BalancerSafeMath.bsub(currentBalance, deltaBalance); require(newBalance >= BalancerConstants.MIN_BALANCE, "ERR_MIN_BALANCE"); bPool.rebind(token, newBalance, newWeight); bool xfer = IERC20(token).transfer(msg.sender, deltaBalance); require(xfer, "ERR_ERC20_FALSE"); self.pullPoolShareFromLib(msg.sender, poolShares); self.burnPoolShareFromLib(poolShares); } else { deltaWeight = BalancerSafeMath.bsub(newWeight, currentWeight); require(BalancerSafeMath.badd(totalWeight, deltaWeight) <= BalancerConstants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); poolShares = BalancerSafeMath.bmul(totalSupply, BalancerSafeMath.bdiv(deltaWeight, totalWeight)); deltaBalance = BalancerSafeMath.bmul(currentBalance, BalancerSafeMath.bdiv(deltaWeight, currentWeight)); bool xfer = IERC20(token).transferFrom(msg.sender, address(this), deltaBalance); require(xfer, "ERR_ERC20_FALSE"); bPool.rebind(token, BalancerSafeMath.badd(currentBalance, deltaBalance), newWeight); self.mintPoolShareFromLib(poolShares); self.pushPoolShareFromLib(msg.sender, poolShares); } } function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external { if (gradualUpdate.startBlock == 0) { return; } if (block.number > gradualUpdate.endBlock) { currentBlock = gradualUpdate.endBlock; } else { currentBlock = block.number; } uint blockPeriod = BalancerSafeMath.bsub(gradualUpdate.endBlock, gradualUpdate.startBlock); uint blocksElapsed = BalancerSafeMath.bsub(currentBlock, gradualUpdate.startBlock); uint weightDelta; uint deltaPerBlock; uint newWeight; address[] memory tokens = bPool.getCurrentTokens(); for (uint i = 0; i < tokens.length; i++) { if (gradualUpdate.startWeights[i] != gradualUpdate.endWeights[i]) { if (gradualUpdate.endWeights[i] < gradualUpdate.startWeights[i]) { weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } else { weightDelta = BalancerSafeMath.bsub(gradualUpdate.endWeights[i], gradualUpdate.startWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.badd(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } uint bal = bPool.getBalance(tokens[i]); bPool.rebind(tokens[i], bal, newWeight); } } if (block.number >= gradualUpdate.endBlock) { gradualUpdate.startBlock = 0; } } function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external { if (gradualUpdate.startBlock == 0) { return; } if (block.number > gradualUpdate.endBlock) { currentBlock = gradualUpdate.endBlock; } else { currentBlock = block.number; } uint blockPeriod = BalancerSafeMath.bsub(gradualUpdate.endBlock, gradualUpdate.startBlock); uint blocksElapsed = BalancerSafeMath.bsub(currentBlock, gradualUpdate.startBlock); uint weightDelta; uint deltaPerBlock; uint newWeight; address[] memory tokens = bPool.getCurrentTokens(); for (uint i = 0; i < tokens.length; i++) { if (gradualUpdate.startWeights[i] != gradualUpdate.endWeights[i]) { if (gradualUpdate.endWeights[i] < gradualUpdate.startWeights[i]) { weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } else { weightDelta = BalancerSafeMath.bsub(gradualUpdate.endWeights[i], gradualUpdate.startWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.badd(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } uint bal = bPool.getBalance(tokens[i]); bPool.rebind(tokens[i], bal, newWeight); } } if (block.number >= gradualUpdate.endBlock) { gradualUpdate.startBlock = 0; } } require(block.number >= gradualUpdate.startBlock, "ERR_CANT_POKE_YET"); uint currentBlock; function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external { if (gradualUpdate.startBlock == 0) { return; } if (block.number > gradualUpdate.endBlock) { currentBlock = gradualUpdate.endBlock; } else { currentBlock = block.number; } uint blockPeriod = BalancerSafeMath.bsub(gradualUpdate.endBlock, gradualUpdate.startBlock); uint blocksElapsed = BalancerSafeMath.bsub(currentBlock, gradualUpdate.startBlock); uint weightDelta; uint deltaPerBlock; uint newWeight; address[] memory tokens = bPool.getCurrentTokens(); for (uint i = 0; i < tokens.length; i++) { if (gradualUpdate.startWeights[i] != gradualUpdate.endWeights[i]) { if (gradualUpdate.endWeights[i] < gradualUpdate.startWeights[i]) { weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } else { weightDelta = BalancerSafeMath.bsub(gradualUpdate.endWeights[i], gradualUpdate.startWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.badd(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } uint bal = bPool.getBalance(tokens[i]); bPool.rebind(tokens[i], bal, newWeight); } } if (block.number >= gradualUpdate.endBlock) { gradualUpdate.startBlock = 0; } } function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external { if (gradualUpdate.startBlock == 0) { return; } if (block.number > gradualUpdate.endBlock) { currentBlock = gradualUpdate.endBlock; } else { currentBlock = block.number; } uint blockPeriod = BalancerSafeMath.bsub(gradualUpdate.endBlock, gradualUpdate.startBlock); uint blocksElapsed = BalancerSafeMath.bsub(currentBlock, gradualUpdate.startBlock); uint weightDelta; uint deltaPerBlock; uint newWeight; address[] memory tokens = bPool.getCurrentTokens(); for (uint i = 0; i < tokens.length; i++) { if (gradualUpdate.startWeights[i] != gradualUpdate.endWeights[i]) { if (gradualUpdate.endWeights[i] < gradualUpdate.startWeights[i]) { weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } else { weightDelta = BalancerSafeMath.bsub(gradualUpdate.endWeights[i], gradualUpdate.startWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.badd(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } uint bal = bPool.getBalance(tokens[i]); bPool.rebind(tokens[i], bal, newWeight); } } if (block.number >= gradualUpdate.endBlock) { gradualUpdate.startBlock = 0; } } function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external { if (gradualUpdate.startBlock == 0) { return; } if (block.number > gradualUpdate.endBlock) { currentBlock = gradualUpdate.endBlock; } else { currentBlock = block.number; } uint blockPeriod = BalancerSafeMath.bsub(gradualUpdate.endBlock, gradualUpdate.startBlock); uint blocksElapsed = BalancerSafeMath.bsub(currentBlock, gradualUpdate.startBlock); uint weightDelta; uint deltaPerBlock; uint newWeight; address[] memory tokens = bPool.getCurrentTokens(); for (uint i = 0; i < tokens.length; i++) { if (gradualUpdate.startWeights[i] != gradualUpdate.endWeights[i]) { if (gradualUpdate.endWeights[i] < gradualUpdate.startWeights[i]) { weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } else { weightDelta = BalancerSafeMath.bsub(gradualUpdate.endWeights[i], gradualUpdate.startWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.badd(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } uint bal = bPool.getBalance(tokens[i]); bPool.rebind(tokens[i], bal, newWeight); } } if (block.number >= gradualUpdate.endBlock) { gradualUpdate.startBlock = 0; } } function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external { if (gradualUpdate.startBlock == 0) { return; } if (block.number > gradualUpdate.endBlock) { currentBlock = gradualUpdate.endBlock; } else { currentBlock = block.number; } uint blockPeriod = BalancerSafeMath.bsub(gradualUpdate.endBlock, gradualUpdate.startBlock); uint blocksElapsed = BalancerSafeMath.bsub(currentBlock, gradualUpdate.startBlock); uint weightDelta; uint deltaPerBlock; uint newWeight; address[] memory tokens = bPool.getCurrentTokens(); for (uint i = 0; i < tokens.length; i++) { if (gradualUpdate.startWeights[i] != gradualUpdate.endWeights[i]) { if (gradualUpdate.endWeights[i] < gradualUpdate.startWeights[i]) { weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } else { weightDelta = BalancerSafeMath.bsub(gradualUpdate.endWeights[i], gradualUpdate.startWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.badd(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } uint bal = bPool.getBalance(tokens[i]); bPool.rebind(tokens[i], bal, newWeight); } } if (block.number >= gradualUpdate.endBlock) { gradualUpdate.startBlock = 0; } } function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external { if (gradualUpdate.startBlock == 0) { return; } if (block.number > gradualUpdate.endBlock) { currentBlock = gradualUpdate.endBlock; } else { currentBlock = block.number; } uint blockPeriod = BalancerSafeMath.bsub(gradualUpdate.endBlock, gradualUpdate.startBlock); uint blocksElapsed = BalancerSafeMath.bsub(currentBlock, gradualUpdate.startBlock); uint weightDelta; uint deltaPerBlock; uint newWeight; address[] memory tokens = bPool.getCurrentTokens(); for (uint i = 0; i < tokens.length; i++) { if (gradualUpdate.startWeights[i] != gradualUpdate.endWeights[i]) { if (gradualUpdate.endWeights[i] < gradualUpdate.startWeights[i]) { weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } else { weightDelta = BalancerSafeMath.bsub(gradualUpdate.endWeights[i], gradualUpdate.startWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.badd(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } uint bal = bPool.getBalance(tokens[i]); bPool.rebind(tokens[i], bal, newWeight); } } if (block.number >= gradualUpdate.endBlock) { gradualUpdate.startBlock = 0; } } function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external { if (gradualUpdate.startBlock == 0) { return; } if (block.number > gradualUpdate.endBlock) { currentBlock = gradualUpdate.endBlock; } else { currentBlock = block.number; } uint blockPeriod = BalancerSafeMath.bsub(gradualUpdate.endBlock, gradualUpdate.startBlock); uint blocksElapsed = BalancerSafeMath.bsub(currentBlock, gradualUpdate.startBlock); uint weightDelta; uint deltaPerBlock; uint newWeight; address[] memory tokens = bPool.getCurrentTokens(); for (uint i = 0; i < tokens.length; i++) { if (gradualUpdate.startWeights[i] != gradualUpdate.endWeights[i]) { if (gradualUpdate.endWeights[i] < gradualUpdate.startWeights[i]) { weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } else { weightDelta = BalancerSafeMath.bsub(gradualUpdate.endWeights[i], gradualUpdate.startWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.badd(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } uint bal = bPool.getBalance(tokens[i]); bPool.rebind(tokens[i], bal, newWeight); } } if (block.number >= gradualUpdate.endBlock) { gradualUpdate.startBlock = 0; } } function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external { if (gradualUpdate.startBlock == 0) { return; } if (block.number > gradualUpdate.endBlock) { currentBlock = gradualUpdate.endBlock; } else { currentBlock = block.number; } uint blockPeriod = BalancerSafeMath.bsub(gradualUpdate.endBlock, gradualUpdate.startBlock); uint blocksElapsed = BalancerSafeMath.bsub(currentBlock, gradualUpdate.startBlock); uint weightDelta; uint deltaPerBlock; uint newWeight; address[] memory tokens = bPool.getCurrentTokens(); for (uint i = 0; i < tokens.length; i++) { if (gradualUpdate.startWeights[i] != gradualUpdate.endWeights[i]) { if (gradualUpdate.endWeights[i] < gradualUpdate.startWeights[i]) { weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } else { weightDelta = BalancerSafeMath.bsub(gradualUpdate.endWeights[i], gradualUpdate.startWeights[i]); deltaPerBlock = BalancerSafeMath.bdiv(weightDelta, blockPeriod); newWeight = BalancerSafeMath.badd(gradualUpdate.startWeights[i], BalancerSafeMath.bmul(blocksElapsed, deltaPerBlock)); } uint bal = bPool.getBalance(tokens[i]); bPool.rebind(tokens[i], bal, newWeight); } } if (block.number >= gradualUpdate.endBlock) { gradualUpdate.startBlock = 0; } } function commitAddToken( IBPool bPool, address token, uint balance, uint denormalizedWeight, NewTokenParams storage newToken ) external { require(!bPool.isBound(token), "ERR_IS_BOUND"); require(denormalizedWeight <= BalancerConstants.MAX_WEIGHT, "ERR_WEIGHT_ABOVE_MAX"); require(denormalizedWeight >= BalancerConstants.MIN_WEIGHT, "ERR_WEIGHT_BELOW_MIN"); require(BalancerSafeMath.badd(bPool.getTotalDenormalizedWeight(), denormalizedWeight) <= BalancerConstants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); require(balance >= BalancerConstants.MIN_BALANCE, "ERR_BALANCE_BELOW_MIN"); newToken.addr = token; newToken.balance = balance; newToken.denorm = denormalizedWeight; newToken.commitBlock = block.number; newToken.isCommitted = true; } function applyAddToken( IConfigurableRightsPool self, IBPool bPool, uint addTokenTimeLockInBlocks, NewTokenParams storage newToken ) external { require(newToken.isCommitted, "ERR_NO_TOKEN_COMMIT"); require(BalancerSafeMath.bsub(block.number, newToken.commitBlock) >= addTokenTimeLockInBlocks, "ERR_TIMELOCK_STILL_COUNTING"); uint totalSupply = self.totalSupply(); uint poolShares = BalancerSafeMath.bdiv(BalancerSafeMath.bmul(totalSupply, newToken.denorm), bPool.getTotalDenormalizedWeight()); newToken.isCommitted = false; bool returnValue = IERC20(newToken.addr).transferFrom(self.getController(), address(self), newToken.balance); require(returnValue, "ERR_ERC20_FALSE"); returnValue = SafeApprove.safeApprove(IERC20(newToken.addr), address(bPool), BalancerConstants.MAX_UINT); require(returnValue, "ERR_ERC20_FALSE"); bPool.bind(newToken.addr, newToken.balance, newToken.denorm); self.mintPoolShareFromLib(poolShares); self.pushPoolShareFromLib(msg.sender, poolShares); } function removeToken( IConfigurableRightsPool self, IBPool bPool, address token ) external { uint totalSupply = self.totalSupply(); uint poolShares = BalancerSafeMath.bdiv(BalancerSafeMath.bmul(totalSupply, bPool.getDenormalizedWeight(token)), bPool.getTotalDenormalizedWeight()); uint balance = bPool.getBalance(token); bPool.unbind(token); bool xfer = IERC20(token).transfer(self.getController(), balance); require(xfer, "ERR_ERC20_FALSE"); self.pullPoolShareFromLib(self.getController(), poolShares); self.burnPoolShareFromLib(poolShares); } function verifyTokenCompliance(address token) external { verifyTokenComplianceInternal(token); } function verifyTokenCompliance(address[] calldata tokens) external { for (uint i = 0; i < tokens.length; i++) { verifyTokenComplianceInternal(tokens[i]); } } function verifyTokenCompliance(address[] calldata tokens) external { for (uint i = 0; i < tokens.length; i++) { verifyTokenComplianceInternal(tokens[i]); } } function updateWeightsGradually( IBPool bPool, GradualUpdateParams storage gradualUpdate, uint[] calldata newWeights, uint startBlock, uint endBlock, uint minimumWeightChangeBlockPeriod ) external { require(block.number < endBlock, "ERR_GRADUAL_UPDATE_TIME_TRAVEL"); if (block.number > startBlock) { gradualUpdate.startBlock = block.number; } else{ gradualUpdate.startBlock = startBlock; } "ERR_WEIGHT_CHANGE_TIME_BELOW_MIN"); address[] memory tokens = bPool.getCurrentTokens(); uint weightsSum = 0; gradualUpdate.startWeights = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { require(newWeights[i] <= BalancerConstants.MAX_WEIGHT, "ERR_WEIGHT_ABOVE_MAX"); require(newWeights[i] >= BalancerConstants.MIN_WEIGHT, "ERR_WEIGHT_BELOW_MIN"); weightsSum = BalancerSafeMath.badd(weightsSum, newWeights[i]); gradualUpdate.startWeights[i] = bPool.getDenormalizedWeight(tokens[i]); } require(weightsSum <= BalancerConstants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); gradualUpdate.endBlock = endBlock; gradualUpdate.endWeights = newWeights; } function updateWeightsGradually( IBPool bPool, GradualUpdateParams storage gradualUpdate, uint[] calldata newWeights, uint startBlock, uint endBlock, uint minimumWeightChangeBlockPeriod ) external { require(block.number < endBlock, "ERR_GRADUAL_UPDATE_TIME_TRAVEL"); if (block.number > startBlock) { gradualUpdate.startBlock = block.number; } else{ gradualUpdate.startBlock = startBlock; } "ERR_WEIGHT_CHANGE_TIME_BELOW_MIN"); address[] memory tokens = bPool.getCurrentTokens(); uint weightsSum = 0; gradualUpdate.startWeights = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { require(newWeights[i] <= BalancerConstants.MAX_WEIGHT, "ERR_WEIGHT_ABOVE_MAX"); require(newWeights[i] >= BalancerConstants.MIN_WEIGHT, "ERR_WEIGHT_BELOW_MIN"); weightsSum = BalancerSafeMath.badd(weightsSum, newWeights[i]); gradualUpdate.startWeights[i] = bPool.getDenormalizedWeight(tokens[i]); } require(weightsSum <= BalancerConstants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); gradualUpdate.endBlock = endBlock; gradualUpdate.endWeights = newWeights; } function updateWeightsGradually( IBPool bPool, GradualUpdateParams storage gradualUpdate, uint[] calldata newWeights, uint startBlock, uint endBlock, uint minimumWeightChangeBlockPeriod ) external { require(block.number < endBlock, "ERR_GRADUAL_UPDATE_TIME_TRAVEL"); if (block.number > startBlock) { gradualUpdate.startBlock = block.number; } else{ gradualUpdate.startBlock = startBlock; } "ERR_WEIGHT_CHANGE_TIME_BELOW_MIN"); address[] memory tokens = bPool.getCurrentTokens(); uint weightsSum = 0; gradualUpdate.startWeights = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { require(newWeights[i] <= BalancerConstants.MAX_WEIGHT, "ERR_WEIGHT_ABOVE_MAX"); require(newWeights[i] >= BalancerConstants.MIN_WEIGHT, "ERR_WEIGHT_BELOW_MIN"); weightsSum = BalancerSafeMath.badd(weightsSum, newWeights[i]); gradualUpdate.startWeights[i] = bPool.getDenormalizedWeight(tokens[i]); } require(weightsSum <= BalancerConstants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); gradualUpdate.endBlock = endBlock; gradualUpdate.endWeights = newWeights; } require(BalancerSafeMath.bsub(endBlock, gradualUpdate.startBlock) >= minimumWeightChangeBlockPeriod, require(newWeights.length == tokens.length, "ERR_START_WEIGHTS_MISMATCH"); function updateWeightsGradually( IBPool bPool, GradualUpdateParams storage gradualUpdate, uint[] calldata newWeights, uint startBlock, uint endBlock, uint minimumWeightChangeBlockPeriod ) external { require(block.number < endBlock, "ERR_GRADUAL_UPDATE_TIME_TRAVEL"); if (block.number > startBlock) { gradualUpdate.startBlock = block.number; } else{ gradualUpdate.startBlock = startBlock; } "ERR_WEIGHT_CHANGE_TIME_BELOW_MIN"); address[] memory tokens = bPool.getCurrentTokens(); uint weightsSum = 0; gradualUpdate.startWeights = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { require(newWeights[i] <= BalancerConstants.MAX_WEIGHT, "ERR_WEIGHT_ABOVE_MAX"); require(newWeights[i] >= BalancerConstants.MIN_WEIGHT, "ERR_WEIGHT_BELOW_MIN"); weightsSum = BalancerSafeMath.badd(weightsSum, newWeights[i]); gradualUpdate.startWeights[i] = bPool.getDenormalizedWeight(tokens[i]); } require(weightsSum <= BalancerConstants.MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); gradualUpdate.endBlock = endBlock; gradualUpdate.endWeights = newWeights; } function joinPool( IConfigurableRightsPool self, IBPool bPool, uint poolAmountOut, uint[] calldata maxAmountsIn ) external view returns (uint[] memory actualAmountsIn) { address[] memory tokens = bPool.getCurrentTokens(); require(maxAmountsIn.length == tokens.length, "ERR_AMOUNTS_MISMATCH"); uint poolTotal = self.totalSupply(); uint ratio = BalancerSafeMath.bdiv(poolAmountOut, BalancerSafeMath.bsub(poolTotal, 1)); require(ratio != 0, "ERR_MATH_APPROX"); actualAmountsIn = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { address t = tokens[i]; uint bal = bPool.getBalance(t); uint tokenAmountIn = BalancerSafeMath.bmul(ratio, BalancerSafeMath.badd(bal, 1)); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN"); actualAmountsIn[i] = tokenAmountIn; } } function joinPool( IConfigurableRightsPool self, IBPool bPool, uint poolAmountOut, uint[] calldata maxAmountsIn ) external view returns (uint[] memory actualAmountsIn) { address[] memory tokens = bPool.getCurrentTokens(); require(maxAmountsIn.length == tokens.length, "ERR_AMOUNTS_MISMATCH"); uint poolTotal = self.totalSupply(); uint ratio = BalancerSafeMath.bdiv(poolAmountOut, BalancerSafeMath.bsub(poolTotal, 1)); require(ratio != 0, "ERR_MATH_APPROX"); actualAmountsIn = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { address t = tokens[i]; uint bal = bPool.getBalance(t); uint tokenAmountIn = BalancerSafeMath.bmul(ratio, BalancerSafeMath.badd(bal, 1)); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN"); actualAmountsIn[i] = tokenAmountIn; } } function exitPool( IConfigurableRightsPool self, IBPool bPool, uint poolAmountIn, uint[] calldata minAmountsOut ) external view returns (uint exitFee, uint pAiAfterExitFee, uint[] memory actualAmountsOut) { address[] memory tokens = bPool.getCurrentTokens(); require(minAmountsOut.length == tokens.length, "ERR_AMOUNTS_MISMATCH"); uint poolTotal = self.totalSupply(); exitFee = BalancerSafeMath.bmul(poolAmountIn, BalancerConstants.EXIT_FEE); pAiAfterExitFee = BalancerSafeMath.bsub(poolAmountIn, exitFee); uint ratio = BalancerSafeMath.bdiv(pAiAfterExitFee, BalancerSafeMath.badd(poolTotal, 1)); require(ratio != 0, "ERR_MATH_APPROX"); actualAmountsOut = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { address t = tokens[i]; uint bal = bPool.getBalance(t); uint tokenAmountOut = BalancerSafeMath.bmul(ratio, BalancerSafeMath.bsub(bal, 1)); require(tokenAmountOut != 0, "ERR_MATH_APPROX"); require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT"); actualAmountsOut[i] = tokenAmountOut; } } function exitPool( IConfigurableRightsPool self, IBPool bPool, uint poolAmountIn, uint[] calldata minAmountsOut ) external view returns (uint exitFee, uint pAiAfterExitFee, uint[] memory actualAmountsOut) { address[] memory tokens = bPool.getCurrentTokens(); require(minAmountsOut.length == tokens.length, "ERR_AMOUNTS_MISMATCH"); uint poolTotal = self.totalSupply(); exitFee = BalancerSafeMath.bmul(poolAmountIn, BalancerConstants.EXIT_FEE); pAiAfterExitFee = BalancerSafeMath.bsub(poolAmountIn, exitFee); uint ratio = BalancerSafeMath.bdiv(pAiAfterExitFee, BalancerSafeMath.badd(poolTotal, 1)); require(ratio != 0, "ERR_MATH_APPROX"); actualAmountsOut = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { address t = tokens[i]; uint bal = bPool.getBalance(t); uint tokenAmountOut = BalancerSafeMath.bmul(ratio, BalancerSafeMath.bsub(bal, 1)); require(tokenAmountOut != 0, "ERR_MATH_APPROX"); require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT"); actualAmountsOut[i] = tokenAmountOut; } } function joinswapExternAmountIn( IConfigurableRightsPool self, IBPool bPool, address tokenIn, uint tokenAmountIn, uint minPoolAmountOut ) external view returns (uint poolAmountOut) { require(bPool.isBound(tokenIn), "ERR_NOT_BOUND"); require(tokenAmountIn <= BalancerSafeMath.bmul(bPool.getBalance(tokenIn), BalancerConstants.MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); poolAmountOut = bPool.calcPoolOutGivenSingleIn( bPool.getBalance(tokenIn), bPool.getDenormalizedWeight(tokenIn), self.totalSupply(), bPool.getTotalDenormalizedWeight(), tokenAmountIn, bPool.getSwapFee() ); require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT"); } function joinswapPoolAmountOut( IConfigurableRightsPool self, IBPool bPool, address tokenIn, uint poolAmountOut, uint maxAmountIn ) external view returns (uint tokenAmountIn) { require(bPool.isBound(tokenIn), "ERR_NOT_BOUND"); tokenAmountIn = bPool.calcSingleInGivenPoolOut( bPool.getBalance(tokenIn), bPool.getDenormalizedWeight(tokenIn), self.totalSupply(), bPool.getTotalDenormalizedWeight(), poolAmountOut, bPool.getSwapFee() ); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); require(tokenAmountIn <= BalancerSafeMath.bmul(bPool.getBalance(tokenIn), BalancerConstants.MAX_IN_RATIO), "ERR_MAX_IN_RATIO"); } function exitswapPoolAmountIn( IConfigurableRightsPool self, IBPool bPool, address tokenOut, uint poolAmountIn, uint minAmountOut ) external view returns (uint exitFee, uint tokenAmountOut) { require(bPool.isBound(tokenOut), "ERR_NOT_BOUND"); tokenAmountOut = bPool.calcSingleOutGivenPoolIn( bPool.getBalance(tokenOut), bPool.getDenormalizedWeight(tokenOut), self.totalSupply(), bPool.getTotalDenormalizedWeight(), poolAmountIn, bPool.getSwapFee() ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require(tokenAmountOut <= BalancerSafeMath.bmul(bPool.getBalance(tokenOut), BalancerConstants.MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO"); exitFee = BalancerSafeMath.bmul(poolAmountIn, BalancerConstants.EXIT_FEE); } function exitswapExternAmountOut( IConfigurableRightsPool self, IBPool bPool, address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn ) external view returns (uint exitFee, uint poolAmountIn) { require(bPool.isBound(tokenOut), "ERR_NOT_BOUND"); require(tokenAmountOut <= BalancerSafeMath.bmul(bPool.getBalance(tokenOut), BalancerConstants.MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO"); poolAmountIn = bPool.calcPoolInGivenSingleOut( bPool.getBalance(tokenOut), bPool.getDenormalizedWeight(tokenOut), self.totalSupply(), bPool.getTotalDenormalizedWeight(), tokenAmountOut, bPool.getSwapFee() ); require(poolAmountIn != 0, "ERR_MATH_APPROX"); require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN"); exitFee = BalancerSafeMath.bmul(poolAmountIn, BalancerConstants.EXIT_FEE); } function verifyTokenComplianceInternal(address token) internal { bool returnValue = IERC20(token).transfer(msg.sender, 0); require(returnValue, "ERR_NONCONFORMING_TOKEN"); } }
3,358,205
[ 1, 6444, 511, 5113, 225, 26400, 596, 326, 3119, 4533, 19, 1412, 12312, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 19656, 2864, 1318, 288, 203, 203, 203, 683, 9454, 23070, 10336, 45, 7204, 58, 22, 31, 203, 203, 565, 1958, 1166, 1345, 1370, 288, 203, 3639, 1758, 3091, 31, 203, 3639, 1426, 353, 27813, 31, 203, 3639, 2254, 3294, 1768, 31, 203, 3639, 2254, 5545, 535, 31, 203, 3639, 2254, 11013, 31, 203, 565, 289, 203, 203, 565, 1958, 611, 6012, 1462, 1891, 1370, 288, 203, 3639, 2254, 787, 1768, 31, 203, 3639, 2254, 679, 1768, 31, 203, 3639, 2254, 8526, 787, 16595, 31, 203, 3639, 2254, 8526, 679, 16595, 31, 203, 565, 289, 203, 203, 203, 565, 445, 1089, 6544, 12, 203, 3639, 467, 31660, 18464, 2864, 365, 16, 203, 3639, 23450, 2864, 324, 2864, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 394, 6544, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 203, 3639, 2583, 12, 2704, 6544, 1545, 605, 5191, 2918, 18, 6236, 67, 29988, 16, 315, 9712, 67, 6236, 67, 29988, 8863, 203, 3639, 2583, 12, 2704, 6544, 1648, 605, 5191, 2918, 18, 6694, 67, 29988, 16, 315, 9712, 67, 6694, 67, 29988, 8863, 203, 203, 3639, 2254, 783, 6544, 273, 324, 2864, 18, 588, 8517, 1687, 1235, 6544, 12, 2316, 1769, 203, 3639, 309, 261, 2972, 6544, 422, 394, 6544, 13, 288, 203, 2398, 327, 31, 203, 3639, 289, 203, 203, 3639, 2254, 783, 13937, 273, 324, 2864, 18, 588, 13937, 12, 2316, 1769, 203, 3639, 2254, 2078, 3088, 1283, 273, 365, 18, 4963, 3088, 1283, 5621, 203, 3639, 2254, 2078, 6544, 273, 324, 2864, 18, 2 ]
/** * @title ByteSlice * * Slices are objects that allow you to work with arrays without copying them. * * @author Andreas Olofsson (androlo1980@gmail.com) */ library ByteSlice { struct Slice { uint _unsafe_memPtr; // Memory address of the first byte. uint _unsafe_length; // Length. } /// @dev Converts bytes to a slice. /// @param self The bytes. /// @return A slice. function slice(bytes memory self) internal constant returns (Slice memory slice) { assembly { let len := mload(self) let memPtr := add(self, 0x20) mstore(slice, mul(memPtr, iszero(iszero(len)))) mstore(add(slice, 0x20), len) } } /// @dev Converts bytes to a slice from the given starting position. /// 'startpos' <= 'len(slice)' /// @param self The bytes. /// @param startpos The starting position. /// @return A slice. function slice(bytes memory self, uint startpos) internal constant returns (Slice memory) { return slice(slice(self), startpos); } /// @dev Converts bytes to a slice from the given starting position. /// -len(slice) <= 'startpos' <= 'len(slice)' /// @param self The bytes. /// @param startpos The starting position. /// @return A slice. function slice(bytes memory self, int startpos) internal constant returns (Slice memory) { return slice(slice(self), startpos); } /// @dev Converts bytes to a slice from the given starting-position, and end-position. /// 'startpos <= len(slice) and startpos <= endpos' /// 'endpos <= len(slice)' /// @param self The bytes. /// @param startpos The starting position. /// @param endpos The end position. /// @return A slice. function slice(bytes memory self, uint startpos, uint endpos) internal constant returns (Slice memory) { return slice(slice(self), startpos, endpos); } /// @dev Converts bytes to a slice from the given starting-position, and end-position. /// Warning: higher cost then using unsigned integers. /// @param self The bytes. /// @param startpos The starting position. /// @param endpos The end position. /// @return A slice. function slice(bytes memory self, int startpos, int endpos) internal constant returns (Slice memory) { return slice(slice(self), startpos, endpos); } /// @dev Get the length of the slice (in bytes). /// @param self The slice. /// @return the length. function len(Slice memory self) internal constant returns (uint) { return self._unsafe_length; } /// @dev Returns the byte from the backing array at a given index. /// The function will throw unless 'index < len(slice)' /// @param self The slice. /// @param index The index. /// @return The byte at that index. function at(Slice memory self, uint index) internal constant returns (byte b) { if (index >= self._unsafe_length) throw; uint bb; assembly { // Get byte at index, and format to 'byte' variable. bb := byte(0, mload(add(mload(self), index))) } b = byte(bb); } /// @dev Returns the byte from the backing array at a given index. /// The function will throw unless '-len(self) <= index < len(self)'. /// @param self The slice. /// @param index The index. /// @return The byte at that index. function at(Slice memory self, int index) internal constant returns (byte b) { if (index >= 0) return at(self, uint(index)); uint iAbs = uint(-index); if (iAbs > self._unsafe_length) throw; return at(self, self._unsafe_length - iAbs); } /// @dev Set the byte at the given index. /// The function will throw unless 'index < len(slice)' /// @param self The slice. /// @param index The index. /// @return The byte at that index. function set(Slice memory self, uint index, byte b) internal constant { if (index >= self._unsafe_length) throw; assembly { mstore8(add(mload(self), index), byte(0, b)) } } /// @dev Set the byte at the given index. /// The function will throw unless '-len(self) <= index < len(self)'. /// @param self The slice. /// @param index The index. /// @return The byte at that index. function set(Slice memory self, int index, byte b) internal constant { if (index >= 0) return set(self, uint(index), b); uint iAbs = uint(-index); if (iAbs > self._unsafe_length) throw; return set(self, self._unsafe_length - iAbs, b); } /// @dev Creates a copy of the slice. /// @param self The slice. /// @return the new reference. function slice(Slice memory self) internal constant returns (Slice memory newSlice) { newSlice._unsafe_memPtr = self._unsafe_memPtr; newSlice._unsafe_length = self._unsafe_length; } /// @dev Create a new slice from the given starting position. /// 'startpos' <= 'len(slice)' /// @param self The slice. /// @param startpos The starting position. /// @return The new slice. function slice(Slice memory self, uint startpos) internal constant returns (Slice memory newSlice) { uint len = self._unsafe_length; if (startpos > len) throw; assembly { len := sub(len, startpos) let newMemPtr := mul(add(mload(self), startpos), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// @dev Create a new slice from the given starting position. /// -len(slice) <= 'startpos' <= 'len(slice)' /// @param self The slice. /// @param startpos The starting position. /// @return The new slice. function slice(Slice memory self, int startpos) internal constant returns (Slice memory newSlice) { uint sAbs; uint startpos_; uint len = self._unsafe_length; if (startpos >= 0) { startpos_ = uint(startpos); if (startpos_ > len) throw; } else { startpos_ = uint(-startpos); if (startpos_ > len) throw; startpos_ = len - startpos_; } assembly { len := sub(len, startpos_) let newMemPtr := mul(add(mload(self), startpos_), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// @dev Create a new slice from a given slice, starting-position, and end-position. /// 'startpos <= len(slice) and startpos <= endpos' /// 'endpos <= len(slice)' /// @param self The slice. /// @param startpos The starting position. /// @param endpos The end position. /// @return the new slice. function slice(Slice memory self, uint startpos, uint endpos) internal constant returns (Slice memory newSlice) { uint len = self._unsafe_length; if (startpos > len || endpos > len || startpos > endpos) throw; assembly { len := sub(endpos, startpos) let newMemPtr := mul(add(mload(self), startpos), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// Same as new(Slice memory, uint, uint) but allows for negative indices. /// Warning: higher cost then using unsigned integers. /// @param self The slice. /// @param startpos The starting position. /// @param endpos The end position. /// @return The new slice. function slice(Slice memory self, int startpos, int endpos) internal constant returns (Slice memory newSlice) { // Don't allow slice on bytes of length 0. uint startpos_; uint endpos_; uint len = self._unsafe_length; if (startpos < 0) { startpos_ = uint(-startpos); if (startpos_ > len) throw; startpos_ = len - startpos_; } else { startpos_ = uint(startpos); if (startpos_ > len) throw; } if (endpos < 0) { endpos_ = uint(-endpos); if (endpos_ > len) throw; endpos_ = len - endpos_; } else { endpos_ = uint(endpos); if (endpos_ > len) throw; } if(startpos_ > endpos_) throw; assembly { len := sub(endpos_, startpos_) let newMemPtr := mul(add(mload(self), startpos_), iszero(iszero(len))) mstore(newSlice, newMemPtr) mstore(add(newSlice, 0x20), len) } } /// @dev Creates a 'bytes memory' variable from a slice, copying the data. /// Bytes are copied from the memory address 'self._unsafe_memPtr'. /// The number of bytes copied is 'self._unsafe_length'. /// @param self The slice. /// @return The bytes variable. function toBytes(Slice memory self) internal constant returns (bytes memory bts) { uint length = self._unsafe_length; if (length == 0) return; uint memPtr = self._unsafe_memPtr; bts = new bytes(length); // We can do word-by-word copying since 'bts' was the last thing to be // allocated. Just overwrite any excess bytes at the end with zeroes. assembly { let i := 0 let btsOffset := add(bts, 0x20) let words := div(add(length, 31), 32) tag_loop: jumpi(end, gt(i, words)) { let offset := mul(i, 32) mstore(add(btsOffset, offset), mload(add(memPtr, offset))) i := add(i, 1) } jump(tag_loop) end: mstore(add(add(bts, length), 0x20), 0) } } /// @dev Creates an ascii-encoded 'string' variable from a slice, copying the data. /// Bytes are copied from the memory address 'self._unsafe_memPtr'. /// The number of bytes copied is 'self._unsafe_length'. /// @param self The slice. /// @return The bytes variable. function toAscii(Slice memory self) internal constant returns (string memory str) { return string(toBytes(self)); } /// @dev Check if two slices are equal. /// @param self The slice. /// @param other The other slice. /// @return True if both slices point to the same memory address, and has the same length. function equals(Slice memory self, Slice memory other) internal constant returns (bool) { return ( self._unsafe_length == other._unsafe_length && self._unsafe_memPtr == other._unsafe_memPtr ); } }
Memory address of the first byte.
uint _unsafe_memPtr;
954,823
[ 1, 6031, 1758, 434, 326, 1122, 1160, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 389, 318, 4626, 67, 3917, 5263, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x99743a2dF45bE75832c083e0d0644BF2E9F0a0C1/sources/contracts/mimic/SocialTraderToken.sol
Assumes that the token was deployed from the social hub
socialHub = msg.sender;
9,595,150
[ 1, 2610, 6411, 716, 326, 1147, 1703, 19357, 628, 326, 16702, 11891, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 16702, 8182, 273, 1234, 18, 15330, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xd640671958EA3bad720CC356F2beEF15Dba58726/sources/Utils.sol
now calculate reward
uint256 reward = WAVAXPool.mul(multiplier).mul(currentBalance).div(100).div(totalSupply);
4,638,264
[ 1, 3338, 4604, 19890, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 19890, 273, 678, 5856, 2501, 2864, 18, 16411, 12, 20538, 2934, 16411, 12, 2972, 13937, 2934, 2892, 12, 6625, 2934, 2892, 12, 4963, 3088, 1283, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.1; interface IMoonCatRescue { function rescueOrder(uint256 tokenId) external view returns (bytes5); function catOwners(bytes5 catId) external view returns (address); } interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IERC721 { function safeTransferFrom(address from, address to, uint256 tokenId) external; function ownerOf(uint256 tokenId) external view returns (address); } interface IMoonCatReference { function doc (address contractAddress) external view returns (string memory name, string memory description, string memory details); function setDoc (address contractAddress, string calldata name, string calldata description) external; } interface IMoonCatTraits { function kTraitsOf (bytes5 catId) external view returns (bool genesis, bool pale, uint8 facing, uint8 expression, uint8 pattern, uint8 pose); } interface IMoonCatColors { function colorsOf (bytes5 catId) external view returns (uint8[24] memory); } /** * @title MoonCatSVGs * @notice On Chain MoonCat Image Generation * @dev Builds SVGs of MoonCat Images */ contract MoonCatSVGs { /* External Contracts */ IMoonCatRescue MoonCatRescue = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6); IMoonCatReference MoonCatReference; IMoonCatTraits MoonCatTraits; IMoonCatColors MoonCatColors; address MoonCatAcclimatorAddress = 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69; uint8[16] public CatBox = [53, 49, 42, 34, 51, 49, 40, 28, 51, 49, 34, 44, 53, 37, 40, 42]; string constant public Face = "57 51,59 51,59 53,61 53,61 55,67 55,67 53,69 53,69 51,71 51,71 53,69 53,69 55,71 55,71 57,73 57,73 67,71 67,71 69,57 69,57 67,55 67,55 57,57 57,57 55,59 55,59 53,57 53"; string[4] public Border = ["57 49,59 49,59 51,61 51,61 53,67 53,67 51,69 51,69 49,71 49,71 51,73 51,73 55,75 55,75 59,85 59,85 61,87 61,87 65,89 65,89 61,87 61,87 55,93 55,93 59,95 59,95 69,93 69,93 71,89 71,89 75,87 75,87 77,85 77,85 79,83 79,83 81,81 81,81 83,61 83,61 77,59 77,59 75,57 75,57 69,55 69,55 67,53 67,53 55,55 55,55 51,57 51", "57 49,59 49,59 51,61 51,61 53,67 53,67 51,69 51,69 49,71 49,71 51,73 51,73 55,83 55,83 57,89 57,89 61,91 61,91 71,89 71,89 73,87 73,87 75,85 75,85 77,69 77,69 75,53 75,53 73,51 73,51 65,53 65,53 55,55 55,55 51,57 51", "57 49,59 49,59 51,61 51,61 53,67 53,67 51,69 51,69 49,73 49,73 55,75 55,75 69,79 69,79 71,83 71,83 75,85 75,85 85,83 85,83 87,81 87,81 89,77 89,77 93,71 93,71 91,65 91,65 93,61 93,61 91,59 91,59 83,57 83,57 77,55 77,55 75,51 75,51 69,55 69,55 67,53 67,53 55,55 55,55 51,57 51", "57 49,61 49,61 53,67 53,67 51,69 51,69 49,73 49,73 53,77 53,77 51,79 51,79 49,83 49,83 45,81 45,81 43,77 43,77 45,73 45,73 37,85 37,85 39,89 39,89 45,91 45,91 51,93 51,93 61,91 61,91 67,93 67,93 73,91 73,91 77,89 77,89 79,81 79,81 77,75 77,75 75,71 75,71 77,69 77,69 79,63 79,63 77,61 77,61 79,53 79,53 73,55 73,55 71,57 71,57 69,55 69,55 67,53 67,53 53,55 53,55 51,57 51"]; string[4] public Coat = ["59 71,71 71,71 69,73 69,73 67,75 67,75 61,83 61,83 63,85 63,85 67,91 67,91 59,89 59,89 57,91 57,91 59,93 59,93 67,91 67,91 69,87 69,87 73,85 73,85 75,83 75,83 77,81 77,81 79,79 79,79 81,77 81,77 75,79 75,79 73,69 73,69 75,71 75,71 79,69 79,69 77,67 77,67 75,65 75,65 79,63 79,63 77,61 77,61 75,59 75", "53 69,57 69,57 71,73 71,73 73,81 73,81 71,83 71,83 69,85 69,85 67,81 67,81 65,79 65,79 67,81 67,81 71,79 71,79 69,73 69,73 67,75 67,75 59,77 59,77 57,81 57,81 59,87 59,87 63,89 63,89 69,87 69,87 71,85 71,85 73,83 73,83 75,71 75,71 71,69 71,69 73,65 73,65 71,59 71,59 73,55 73,55 71,53 71", "55 69,57 69,57 71,71 71,71 69,73 69,73 71,75 71,75 75,77 75,77 85,79 85,79 81,81 81,81 77,79 77,79 73,77 73,77 71,79 71,79 73,81 73,81 77,83 77,83 83,81 83,81 85,79 85,79 87,75 87,75 89,69 89,69 87,67 87,67 85,71 85,71 83,75 83,75 81,69 81,69 85,67 85,67 77,65 77,65 75,67 75,67 73,61 73,61 77,63 77,63 79,61 79,61 89,65 89,65 87,63 87,63 85,61 85,61 81,59 81,59 75,57 75,57 73,55 73", "89 49,85 49,85 43,81 43,81 41,77 41,77 43,75 43,75 39,83 39,83 41,87 41,87 47,89 47,89 53,91 53,91 59,89 59,89 67,91 67,91 71,89 71,89 75,87 75,87 77,85 77,85 75,79 75,79 71,83 71,83 73,81 73,81 75,85 75,85 73,87 73,87 69,85 69,85 63,83 63,83 65,79 65,79 67,77 67,77 71,73 71,73 73,69 73,69 75,65 75,65 73,63 73,63 75,59 75,59 77,57 77,57 57,55 57,55 53,57 53,57 57,71 57,71 53,73 53,73 57,57 57,57 73,59 73,59 71,71 71,71 69,75 69,75 57,77 57,77 55,79 55,79 53,81 53,81 51,89 51"]; string[4] public Tummy = ["71 73,77 73,77 75,75 75,75 79,73 79,73 75,71 75", "75 69,79 69,79 71,75 71", "61 79,67 79,67 87,63 87,63 85,61 85", "83 63,85 63,85 67,83 67,83 69,77 69,77 67,79 67,79 65,83 65"]; uint8[] public Eyes = [2,0,0,0, 59,59,67,59]; uint8[] public Whiskers = [4,4,4,4, 59,63,67,63,61,65,65,65, 59,57,67,57,61,65,65,65, 59,61,67,61,61,65,65,65, 57,63,59,63,67,63,69,63]; uint8[] public Skin = [6,5,7,7, 57,53,69,53,63,63,63,79,69,79,75,79, 57,53,69,53,63,63,59,71,63,71, 57,53,69,53,63,63,53,71,63,75,63,89,73,89, 57,53,69,53,63,63,77,73,55,75,65,75,83,75]; uint8[882] public Patterns = [16,17,17,18,34,25,27,40,62,53,56,70, 61,55,65,55,55,59,71,59,79,61,91,61,55,63,71,63,77,63,83,63,81,65,91,65,87,67,85,69,59,73,69,75, 61,55,65,55,55,59,71,59,79,59,85,59,77,61,83,61,55,63,71,63,87,65,55,69,67,71,83,71,73,73,77,73,81,73, 61,55,65,55,55,59,71,59,55,63,71,63,57,71,73,71,59,73,71,73,79,73,75,75,73,77,81,77,81,81,79,83,61,85, 77,39,81,39,81,41,85,41,85,45,81,53,61,55,65,55,77,55,83,55,79,57,55,59,71,59,55,63,71,63,89,67,59,73,67,73, 69,51,67,53,57,57,59,57,89,57,57,59,91,59,71,61,77,61,79,61,81,61,91,61,71,63,79,63,81,63,83,63,55,65,81,65,73,67,73,69,75,69,61,71,63,71,65,71,71,71,73,71,75,71,79,71,81,71,63,73,79,73,81,73,83,73,81,75, 69,51,67,53,57,57,59,57,57,59,81,59,83,59,85,59,71,61,83,61,85,61,71,63,55,65,77,65,77,67,79,67,53,69,55,69,55,71,57,71,71,71,71,73,73,73,75,73,77,73, 69,51,67,53,57,57,59,57,57,59,71,61,71,63,55,65,57,71,59,71,61,71,63,71,77,71,59,73,79,73,71,75,75,75,79,75,73,77,75,77,73,79,75,79,75,81,75,83,61,85,61,87,63,87, 75,39,77,39,79,39,81,39,75,41,81,41,69,51,81,51,83,51,85,51,67,53,71,53,79,53,81,53,83,53,77,55,79,55,81,55,83,55,57,57,59,57,79,57,81,57,57,59,87,59,71,61,85,61,87,61,71,63,85,63,87,63,55,65,87,65,87,67,89,67,59,71,61,71,63,71,65,71,61,73, 57,51,59,53,57,55,59,55,61,55,55,57,57,57,59,57,61,57,63,57,55,59,57,59,61,59,63,59,55,61,57,61,59,61,61,61,63,61,65,61,81,61,55,63,57,63,59,63,61,63,65,63,81,63,83,63,55,65,57,65,59,65,61,65,63,65,65,65,81,65,83,65,57,67,59,67,61,67,63,67,65,67,79,67,81,67,83,67,85,67,87,67,89,67,71,69,73,69,81,69,83,69,67,71,69,71,71,71,73,71,75,71,65,73,67,73,67,75,69,75,69,77,75,79, 57,51,59,53,57,55,59,55,61,55,55,57,57,57,59,57,61,57,63,57,55,59,57,59,61,59,63,59,55,61,57,61,59,61,61,61,63,61,65,61,83,61,85,61,55,63,57,63,59,63,61,63,65,63,83,63,85,63,87,63,55,65,57,65,59,65,61,65,63,65,65,65,81,65,83,65,85,65,87,65,57,67,59,67,61,67,63,67,65,67,85,67,87,67,83,69,85,69,63,71,65,71,67,71,83,71, 57,51,59,53,57,55,59,55,61,55,55,57,57,57,59,57,61,57,63,57,55,59,57,59,61,59,63,59,55,61,57,61,59,61,61,61,63,61,65,61,55,63,57,63,59,63,61,63,65,63,55,65,57,65,59,65,61,65,63,65,65,65,57,67,59,67,61,67,63,67,65,67,67,73,65,75,67,75,69,75,67,77,69,77,75,81,79,81,81,81,73,83,75,83,79,83,61,85,73,85,75,85,77,85,61,87,63,87,73,87,73,89, 85,43,85,45,85,47,87,47,57,51,81,51,83,51,85,51,87,51,55,53,59,53,83,53,85,53,87,53,55,55,57,55,59,55,61,55,55,57,57,57,59,57,61,57,63,57,55,59,57,59,61,59,63,59,55,61,57,61,59,61,61,61,63,61,65,61,55,63,57,63,59,63,61,63,65,63,75,63,77,63,79,63,55,65,57,65,59,65,61,65,63,65,65,65,75,65,77,65,57,67,59,67,61,67,63,67,65,67,75,67,71,69,73,69,75,69,87,69,65,71,67,71,69,71,71,71,87,71,65,73,67,73,85,73,87,73,83,75,85,75]; /** * @dev Wrap a chunk of SVG objects with a group that flips their appearance horizontally. */ function flip (bytes memory svgData) public pure returns (bytes memory) { return abi.encodePacked("<g transform=\"scale(-1,1) translate(-128,0)\">", svgData, "</g>"); } /** * @dev Transform a set of coordinate points into an SVG polygon object. */ function polygon(string memory points, uint8 r, uint8 g, uint8 b) internal pure returns (bytes memory) { return abi.encodePacked("<polygon points=\"", points, "\" fill=\"rgb(",uint2str(r),",",uint2str(g),",",uint2str(b), ")\"/>" ); } /** * @dev Transform a coordinate point into SVG rectangles. */ function setPixel (bytes memory imageData, uint8 x, uint8 y) internal pure returns (bytes memory) { return abi.encodePacked(imageData, "<use href=\"#r", "\" x=\"",uint2str(x), "\" y=\"",uint2str(y), "\"/>"); } /** * @dev Transform a set of coordinate points into a collection of SVG rectangles. */ function pixelGroup (uint8[] memory data, uint8 index) public pure returns (bytes memory) { bytes memory pixels; uint startIndex = 2; for (uint i = 0; i < index; i++) { startIndex += data[i]; } uint endIndex = startIndex + data[index]; for (uint i = startIndex; i < endIndex; i++){ uint p = i * 2; pixels = setPixel(pixels, data[p], data[p+1]); } return pixels; } /** * @dev For a given MoonCat pose and pattern ID, return a collection of SVG rectangles drawing that pattern. */ function getPattern (uint8 pose, uint8 pattern) public view returns (bytes memory) { bytes memory pixels; if (pattern > 0) { pattern -= 1; uint index = (pattern << 2) + pose; uint startIndex = 6; for (uint i = 0; i < index; i++) { startIndex += Patterns[i]; } uint endIndex = startIndex + Patterns[index]; for (uint i = startIndex; i < endIndex; i++){ uint p = i * 2; pixels = setPixel(pixels, Patterns[p], Patterns[p+1]); } } return pixels; } /** * @dev Wrap a collection of SVG rectangle "pixels" in a group to color them all the same color. */ function colorGroup (bytes memory pixels, uint8 r, uint8 g, uint8 b) internal pure returns (bytes memory) { return abi.encodePacked("<g fill=\"rgb(",uint2str(r),",",uint2str(g),",",uint2str(b),")\">", pixels, "</g>"); } /** * @dev Wrap a collection of SVG rectangle "pixels" in a group to create a colored glow around them. */ function glowGroup (bytes memory pixels, uint8 r, uint8 g, uint8 b) public pure returns (bytes memory) { return abi.encodePacked("<g style=\"filter:drop-shadow(0px 0px 2px rgb(",uint2str(r), ",", uint2str(g), ",", uint2str(b),"))\">", pixels, "</g>"); } /** * @dev Given specific MoonCat trait information, assemble the main visual SVG objects to represent a MoonCat with those traits. */ function getPixelData (uint8 facing, uint8 expression, uint8 pose, uint8 pattern, uint8[24] memory colors) public view returns (bytes memory) { bytes memory border = polygon(Border[pose], colors[3], colors[4], colors[5]); bytes memory face = polygon(Face, colors[9], colors[10], colors[11]); bytes memory coat = polygon(Coat[pose], colors[9], colors[10], colors[11]); bytes memory skin = colorGroup(pixelGroup(Skin, pose), colors[15], colors[16], colors[17]); bytes memory tummy = polygon(Tummy[pose], colors[12], colors[13], colors[14]); bytes memory patt = colorGroup(getPattern(pose, pattern), colors[6], colors[7], colors[8]); bytes memory whiskers = colorGroup(pixelGroup(Whiskers, expression), colors[12], colors[13], colors[14]); bytes memory eyes = colorGroup(pixelGroup(Eyes, 0), colors[3], colors[4], colors[5]); bytes memory data; if (pattern == 2) { data = abi.encodePacked(border, face, coat, skin, tummy, whiskers, patt, eyes); } else { data = abi.encodePacked(border, face, coat, skin, tummy, patt, whiskers, eyes); } if (facing == 1) { return flip(data); } return data; } /** * @dev Construct SVG header/wrapper tag for a given set of canvas dimensions. */ function svgTag (uint8 x, uint8 y, uint8 w, uint8 h) public pure returns (bytes memory) { return abi.encodePacked("<svg xmlns=\"http://www.w3.org/2000/svg\" preserveAspectRatio=\"xMidYMid slice\" viewBox=\"", uint2str(x), " ", uint2str(y), " ", uint2str(w), " ", uint2str(h), "\" width=\"", uint2str(uint32(w)*5), "\" height=\"", uint2str(uint32(h)*5), "\" shape-rendering=\"crispEdges\" style=\"image-rendering:pixelated\"><defs><rect id=\"r\" width=\"2\" height=\"2\" /></defs>"); } /** * @dev Convert a MoonCat facing and pose trait information into an SVG viewBox definition to set that canvas size. */ function boundingBox (uint8 facing, uint8 pose) public view returns (uint8 x, uint8 y, uint8 width, uint8 height) { x = CatBox[pose * 4 + 0] - 2; y = CatBox[pose * 4 + 1] - 2; width = CatBox[pose * 4 + 2] + 4; height = CatBox[pose * 4 + 3] + 4; if (facing == 1) { x = 128 - width - x; } return (x, y, width, height); } /** * @dev For a given MoonCat hex ID, create an SVG of their appearance, specifying glowing or not. */ function imageOf (bytes5 catId, bool glow) public view returns (string memory) { (,,uint8 facing, uint8 expression, uint8 pattern, uint8 pose) = MoonCatTraits.kTraitsOf(catId); uint8[24] memory colors = MoonCatColors.colorsOf(catId); bytes memory pixelData = getPixelData(facing, expression, pose, pattern, colors); if (glow) { pixelData = glowGroup(pixelData, colors[0], colors[1], colors[2]); } (uint8 x, uint8 y, uint8 width, uint8 height) = boundingBox(facing, pose); return string(abi.encodePacked(svgTag(x, y, width, height), pixelData, "</svg>")); } /** * @dev For a given MoonCat hex ID, create an SVG of their appearance, glowing if they're Acclimated. */ function imageOf (bytes5 catId) public view returns (string memory) { return imageOf(catId, MoonCatRescue.catOwners(catId) == MoonCatAcclimatorAddress); } /** * @dev For a given MoonCat rescue order, create an SVG of their appearance, specifying glowing or not. */ function imageOf (uint256 rescueOrder, bool glow) public view returns (string memory) { require(rescueOrder < 25440, "Invalid Rescue Order"); return imageOf(MoonCatRescue.rescueOrder(rescueOrder), glow); } /** * @dev For a given MoonCat rescue order, create an SVG of their appearance, glowing if they're Acclimated. */ function imageOf (uint256 rescueOrder) public view returns (string memory) { require(rescueOrder < 25440, "Invalid Rescue Order"); return imageOf(MoonCatRescue.rescueOrder(rescueOrder)); } /** * @dev Convert an integer/numeric value into a string of that number's decimal value. */ function uint2str (uint value) public 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); } /* General */ /** * @dev Get documentation about this contract. */ function doc() public view returns (string memory name, string memory description, string memory details) { return MoonCatReference.doc(address(this)); } constructor (address MoonCatReferenceAddress, address MoonCatTraitsAddress, address MoonCatColorsAddress) { owner = payable(msg.sender); // https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148).claim(msg.sender); MoonCatReference = IMoonCatReference(MoonCatReferenceAddress); MoonCatTraits = IMoonCatTraits(MoonCatTraitsAddress); MoonCatColors = IMoonCatColors(MoonCatColorsAddress); } address payable public owner; modifier onlyOwner () { require(msg.sender == owner, "Only Owner"); _; } /** * @dev Allow current `owner` to transfer ownership to another address. */ function transferOwnership (address payable newOwner) public onlyOwner { owner = newOwner; } /** * @dev Update the location of the Reference Contract. */ function setReferenceContract (address referenceContract) public onlyOwner { MoonCatReference = IMoonCatReference(referenceContract); } /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20 (address tokenContract) public onlyOwner { IERC20 token = IERC20(tokenContract); token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721 (address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId); } }
External Contracts */* @dev Wrap a chunk of SVG objects with a group that flips their appearance horizontally./
function flip (bytes memory svgData) public pure returns (bytes memory) { return abi.encodePacked("<g transform=\"scale(-1,1) translate(-128,0)\">", svgData, "</g>"); }
394,105
[ 1, 6841, 30131, 342, 225, 4266, 279, 2441, 434, 11281, 2184, 598, 279, 1041, 716, 284, 11693, 3675, 9788, 1359, 366, 6157, 1230, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9668, 261, 3890, 3778, 9804, 751, 13, 1071, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 24126, 18, 3015, 4420, 329, 2932, 32, 75, 2510, 5189, 5864, 19236, 21, 16, 21, 13, 4204, 19236, 10392, 16, 20, 13, 21121, 16, 9804, 751, 16, 6823, 75, 2984, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xEACa2B16784f4048A37C220649409Ec0993f7Ee5/sources/contracts/BDCContract.sol
`_mint`'s second argument now takes in a `quantity`, not a `tokenId`.
function mint(address to, uint256 quantity) external payable isCorrectPayment(PUBLIC_SALE_PRICE,quantity) canMintBDCs(quantity) { _mint(to, quantity); }
12,437,095
[ 1, 68, 67, 81, 474, 11294, 87, 2205, 1237, 2037, 5530, 316, 279, 1375, 16172, 9191, 486, 279, 1375, 2316, 548, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 10457, 13, 7010, 3639, 3903, 7010, 3639, 8843, 429, 203, 3639, 353, 16147, 6032, 12, 14939, 67, 5233, 900, 67, 7698, 1441, 16, 16172, 13, 203, 3639, 848, 49, 474, 38, 5528, 87, 12, 16172, 13, 7010, 565, 288, 203, 3639, 389, 81, 474, 12, 869, 16, 10457, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Copyright (c) 2017-present, Parsec Labs (parseclabs.org) * * This source code is licensed under the Mozilla Public License, version 2, * found in the LICENSE file in the root directory of this source tree. */ pragma solidity ^0.4.22; library TxLib { uint constant internal WORD_SIZE = 32; uint constant internal ONES = ~uint(0); // DEPOSIT: 2, // TRANSFER: 3, // CONSOLIDATE: 4, // COMP_REQ: 5, // COMP_RESP: 6, enum TxType { Deposit, Transfer, Consolidate, CompReq, CompRsp } struct Input { bytes32 hash; uint8 outPos; bytes32 r; bytes32 s; uint8 v; } struct Output { uint64 value; uint16 color; address owner; uint32 gasPrice; bytes msgData; bytes32 stateRoot; } struct Tx { TxType txType; Input[] ins; Output[] outs; } function parseInput(TxType _type, bytes _txData, uint256 _pos, uint256 offset, Input[] _ins) internal pure returns (uint256 newOffset) { bytes32 hash; uint8 index; if (_type == TxType.Deposit) { assembly { hash := mload(add(add(offset, 4), _txData)) } hash = bytes32(uint32(hash)); index = 0; newOffset = offset + 4; } else { assembly { hash := mload(add(add(offset, 32), _txData)) index := mload(add(add(offset, 33), _txData)) } newOffset = offset + 33; } Input memory input = Input(hash, index, 0, 0, 0); if (_type == TxType.Transfer || ((_type == TxType.CompReq || _type == TxType.CompRsp ) && _pos > 0)) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(add(offset, 65), _txData)) s := mload(add(add(offset, 97), _txData)) v := mload(add(add(offset, 98), _txData)) } input.r = r; input.s = s; input.v = v; newOffset = offset + 33 + 65; } _ins[_pos] = input; } // Copies 'len' bytes from 'srcPtr' to 'destPtr'. // NOTE: This function does not check if memory is allocated, it only copies the bytes. function memcopy(uint srcPtr, uint destPtr, uint len) internal pure { uint offset = 0; uint size = len / WORD_SIZE; // Copy word-length chunks while possible. for (uint i = 0; i < size; i++) { offset = i * WORD_SIZE; assembly { mstore(add(destPtr, offset), mload(add(srcPtr, offset))) } } offset = size*WORD_SIZE; uint mask = ONES << 8*(32 - len % WORD_SIZE); assembly { let nSrc := add(srcPtr, offset) let nDest := add(destPtr, offset) mstore(nDest, or(and(mload(nSrc), mask), and(mload(nDest), not(mask)))) } } function parseOutput(TxType _type, bytes _txData, uint256 _pos, uint256 offset, Output[] _outs) internal pure returns (uint256 newOffset) { uint64 value; uint16 color; address owner; assembly { value := mload(add(add(offset, 8), _txData)) color := mload(add(add(offset, 10), _txData)) owner := mload(add(add(offset, 30), _txData)) } bytes memory data = new bytes(0); Output memory output = Output(value, color, owner, 0, data, 0); _outs[_pos] = output; newOffset = offset + 30; if (_type == TxType.CompReq && _pos == 0) { // read gasPrice // read length of msgData uint32 gasPrice; assembly { gasPrice := mload(add(add(offset, 34), _txData)) value := mload(add(add(offset, 36), _txData)) } output.gasPrice = gasPrice; // read msgData value = uint16(value); // using value for length here data = new bytes(value); uint src; uint dest; assembly { src := add(add(add(offset, 36), 0x20), _txData) dest := add(data, 0x20) } memcopy(src, dest, value); output.msgData = data; newOffset = offset + 36 + value; } else if (_type == TxType.CompRsp && _pos == 0) { // read new stateRoot bytes32 stateRoot; output.stateRoot = stateRoot; newOffset = offset + 33 + 32; } } function parseTx(bytes _txData) internal pure returns (Tx memory txn) { // read type TxType txType; uint256 a; assembly { a := mload(add(0x20, _txData)) } a = a >> 248; // get first byte if (a == 2 ) { txType = TxType.Deposit; } else if (a == 3 ) { txType = TxType.Transfer; } else if (a == 4 ) { txType = TxType.Consolidate; } else if (a == 5 ) { txType = TxType.CompReq; } else if (a == 6 ) { txType = TxType.CompRsp; } else { revert("unknow tx type"); } // read ins and outs assembly { a := mload(add(0x21, _txData)) } a = a >> 252; // get ins nibble Input[] memory ins = new Input[](a); uint256 offset = 2; for (uint i = 0; i < ins.length; i++) { offset = parseInput(txType, _txData, i, offset, ins); } assembly { a := mload(add(0x21, _txData)) } a = (a >> 248) & 0x0f; // get ins nibble Output[] memory outs = new Output[](a); if (txType == TxType.Consolidate && ins.length <= outs.length) { revert("invalide consolidate"); } for (i = 0; i < outs.length; i++) { offset = parseOutput(txType, _txData, i, offset, outs); } txn = Tx(txType, ins, outs); } function getMerkleRoot(bytes32 _leaf, uint256 _index, uint256 _offset, bytes32[] _proof) internal pure returns (bytes32) { for (uint256 i = _offset; i < _proof.length; i++) { // solhint-disable-next-line no-inline-assembly if (_index % 2 == 0) { _leaf = keccak256(_leaf, _proof[i]); } else { _leaf = keccak256(_proof[i], _leaf); } _index = _index / 2; } return _leaf; } //validate that transaction is included to the period (merkle proof) function validateProof(uint256 _cdOffset, bytes32[] _proof) internal pure returns (uint64 txPos, bytes32 txHash, bytes memory txData) { uint256 offset = uint16(_proof[1] >> 248); uint256 txLength = uint16(_proof[1] >> 224); txData = new bytes(txLength); assembly { calldatacopy(add(txData, 0x20), add(68, add(offset, _cdOffset)), txLength) } txHash = keccak256(txData); txPos = uint64(_proof[1] >> 160); bytes32 root = getMerkleRoot(txHash, txPos, uint8(_proof[1] >> 240), _proof); require(root == _proof[0]); } function recoverTxSigner(uint256 offset, bytes32[] _proof) internal pure returns (address dest) { uint16 txLength = uint16(_proof[1] >> 224); bytes memory txData = new bytes(txLength); bytes32 r; bytes32 s; uint8 v; assembly { calldatacopy(add(txData, 32), add(114, offset), 43) r := calldataload(add(157, offset)) s := calldataload(add(189, offset)) v := calldataload(add(190, offset)) calldatacopy(add(txData, 140), add(222, offset), 28) // 32 + 43 + 65 } dest = ecrecover(keccak256(txData), v, r, s); } }
using value for length here
value = uint16(value);
12,854,050
[ 1, 9940, 460, 364, 769, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 460, 273, 2254, 2313, 12, 1132, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x97742240d6eBE32198B315d30C73c3D2FFC9cE21/sources/src/contracts/BaseParaSwapBuyAdapter.sol
* @title BaseParaSwapBuyAdapter @notice Implements the logic for buying tokens on ParaSwap/
abstract contract BaseParaSwapBuyAdapter is BaseParaSwapAdapter { using SafeERC20 for IERC20Detailed; using PercentageMath for uint256; IParaSwapAugustusRegistry public immutable AUGUSTUS_REGISTRY; constructor( IPoolAddressesProvider addressesProvider, address pool, IParaSwapAugustusRegistry augustusRegistry pragma solidity ^0.8.10; import {PercentageMath} from '@aave/core-v3/contracts/protocol/libraries/math/PercentageMath.sol'; import {IPoolAddressesProvider} from '@aave/core-v3/contracts/interfaces/IPoolAddressesProvider.sol'; import {IERC20Detailed} from '@aave/core-v3/contracts/dependencies/openzeppelin/contracts/IERC20Detailed.sol'; import {SafeERC20} from '@aave/core-v3/contracts/dependencies/openzeppelin/contracts/SafeERC20.sol'; import {IParaSwapAugustus} from '../interfaces/IParaSwapAugustus.sol'; import {IParaSwapAugustusRegistry} from '../interfaces/IParaSwapAugustusRegistry.sol'; import {BaseParaSwapAdapter} from './BaseParaSwapAdapter.sol'; ) BaseParaSwapAdapter(addressesProvider, pool) { require(!augustusRegistry.isValidAugustus(address(0)), 'Not a valid Augustus address'); AUGUSTUS_REGISTRY = augustusRegistry; } function _buyOnParaSwap( uint256 toAmountOffset, bytes memory paraswapData, IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive ) internal returns (uint256 amountSold) { (bytes memory buyCalldata, IParaSwapAugustus augustus) = abi.decode( paraswapData, (bytes, IParaSwapAugustus) ); require(AUGUSTUS_REGISTRY.isValidAugustus(address(augustus)), 'INVALID_AUGUSTUS'); { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(address(assetToSwapFrom)); uint256 toAssetPrice = _getPrice(address(assetToSwapTo)); uint256 expectedMaxAmountToSwap = ((amountToReceive * (toAssetPrice * (10 ** fromAssetDecimals))) / (fromAssetPrice * (10 ** toAssetDecimals))) .percentMul(PercentageMath.PERCENTAGE_FACTOR + MAX_SLIPPAGE_PERCENT); require(maxAmountToSwap <= expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); } uint256 balanceBeforeAssetFrom = assetToSwapFrom.balanceOf(address(this)); require(balanceBeforeAssetFrom >= maxAmountToSwap, 'INSUFFICIENT_BALANCE_BEFORE_SWAP'); uint256 balanceBeforeAssetTo = assetToSwapTo.balanceOf(address(this)); address tokenTransferProxy = augustus.getTokenTransferProxy(); assetToSwapFrom.safeApprove(tokenTransferProxy, 0); assetToSwapFrom.safeApprove(tokenTransferProxy, maxAmountToSwap); if (toAmountOffset != 0) { require( toAmountOffset >= 4 && toAmountOffset <= buyCalldata.length - 32, 'TO_AMOUNT_OFFSET_OUT_OF_RANGE' ); assembly { mstore(add(buyCalldata, add(toAmountOffset, 32)), amountToReceive) } } (bool success, ) = address(augustus).call(buyCalldata); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } uint256 balanceAfterAssetFrom = assetToSwapFrom.balanceOf(address(this)); amountSold = balanceBeforeAssetFrom - balanceAfterAssetFrom; require(amountSold <= maxAmountToSwap, 'WRONG_BALANCE_AFTER_SWAP'); uint256 amountReceived = assetToSwapTo.balanceOf(address(this)) - balanceBeforeAssetTo; require(amountReceived >= amountToReceive, 'INSUFFICIENT_AMOUNT_RECEIVED'); emit Bought(address(assetToSwapFrom), address(assetToSwapTo), amountSold, amountReceived); } function _buyOnParaSwap( uint256 toAmountOffset, bytes memory paraswapData, IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive ) internal returns (uint256 amountSold) { (bytes memory buyCalldata, IParaSwapAugustus augustus) = abi.decode( paraswapData, (bytes, IParaSwapAugustus) ); require(AUGUSTUS_REGISTRY.isValidAugustus(address(augustus)), 'INVALID_AUGUSTUS'); { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(address(assetToSwapFrom)); uint256 toAssetPrice = _getPrice(address(assetToSwapTo)); uint256 expectedMaxAmountToSwap = ((amountToReceive * (toAssetPrice * (10 ** fromAssetDecimals))) / (fromAssetPrice * (10 ** toAssetDecimals))) .percentMul(PercentageMath.PERCENTAGE_FACTOR + MAX_SLIPPAGE_PERCENT); require(maxAmountToSwap <= expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); } uint256 balanceBeforeAssetFrom = assetToSwapFrom.balanceOf(address(this)); require(balanceBeforeAssetFrom >= maxAmountToSwap, 'INSUFFICIENT_BALANCE_BEFORE_SWAP'); uint256 balanceBeforeAssetTo = assetToSwapTo.balanceOf(address(this)); address tokenTransferProxy = augustus.getTokenTransferProxy(); assetToSwapFrom.safeApprove(tokenTransferProxy, 0); assetToSwapFrom.safeApprove(tokenTransferProxy, maxAmountToSwap); if (toAmountOffset != 0) { require( toAmountOffset >= 4 && toAmountOffset <= buyCalldata.length - 32, 'TO_AMOUNT_OFFSET_OUT_OF_RANGE' ); assembly { mstore(add(buyCalldata, add(toAmountOffset, 32)), amountToReceive) } } (bool success, ) = address(augustus).call(buyCalldata); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } uint256 balanceAfterAssetFrom = assetToSwapFrom.balanceOf(address(this)); amountSold = balanceBeforeAssetFrom - balanceAfterAssetFrom; require(amountSold <= maxAmountToSwap, 'WRONG_BALANCE_AFTER_SWAP'); uint256 amountReceived = assetToSwapTo.balanceOf(address(this)) - balanceBeforeAssetTo; require(amountReceived >= amountToReceive, 'INSUFFICIENT_AMOUNT_RECEIVED'); emit Bought(address(assetToSwapFrom), address(assetToSwapTo), amountSold, amountReceived); } function _buyOnParaSwap( uint256 toAmountOffset, bytes memory paraswapData, IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive ) internal returns (uint256 amountSold) { (bytes memory buyCalldata, IParaSwapAugustus augustus) = abi.decode( paraswapData, (bytes, IParaSwapAugustus) ); require(AUGUSTUS_REGISTRY.isValidAugustus(address(augustus)), 'INVALID_AUGUSTUS'); { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(address(assetToSwapFrom)); uint256 toAssetPrice = _getPrice(address(assetToSwapTo)); uint256 expectedMaxAmountToSwap = ((amountToReceive * (toAssetPrice * (10 ** fromAssetDecimals))) / (fromAssetPrice * (10 ** toAssetDecimals))) .percentMul(PercentageMath.PERCENTAGE_FACTOR + MAX_SLIPPAGE_PERCENT); require(maxAmountToSwap <= expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); } uint256 balanceBeforeAssetFrom = assetToSwapFrom.balanceOf(address(this)); require(balanceBeforeAssetFrom >= maxAmountToSwap, 'INSUFFICIENT_BALANCE_BEFORE_SWAP'); uint256 balanceBeforeAssetTo = assetToSwapTo.balanceOf(address(this)); address tokenTransferProxy = augustus.getTokenTransferProxy(); assetToSwapFrom.safeApprove(tokenTransferProxy, 0); assetToSwapFrom.safeApprove(tokenTransferProxy, maxAmountToSwap); if (toAmountOffset != 0) { require( toAmountOffset >= 4 && toAmountOffset <= buyCalldata.length - 32, 'TO_AMOUNT_OFFSET_OUT_OF_RANGE' ); assembly { mstore(add(buyCalldata, add(toAmountOffset, 32)), amountToReceive) } } (bool success, ) = address(augustus).call(buyCalldata); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } uint256 balanceAfterAssetFrom = assetToSwapFrom.balanceOf(address(this)); amountSold = balanceBeforeAssetFrom - balanceAfterAssetFrom; require(amountSold <= maxAmountToSwap, 'WRONG_BALANCE_AFTER_SWAP'); uint256 amountReceived = assetToSwapTo.balanceOf(address(this)) - balanceBeforeAssetTo; require(amountReceived >= amountToReceive, 'INSUFFICIENT_AMOUNT_RECEIVED'); emit Bought(address(assetToSwapFrom), address(assetToSwapTo), amountSold, amountReceived); } function _buyOnParaSwap( uint256 toAmountOffset, bytes memory paraswapData, IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive ) internal returns (uint256 amountSold) { (bytes memory buyCalldata, IParaSwapAugustus augustus) = abi.decode( paraswapData, (bytes, IParaSwapAugustus) ); require(AUGUSTUS_REGISTRY.isValidAugustus(address(augustus)), 'INVALID_AUGUSTUS'); { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(address(assetToSwapFrom)); uint256 toAssetPrice = _getPrice(address(assetToSwapTo)); uint256 expectedMaxAmountToSwap = ((amountToReceive * (toAssetPrice * (10 ** fromAssetDecimals))) / (fromAssetPrice * (10 ** toAssetDecimals))) .percentMul(PercentageMath.PERCENTAGE_FACTOR + MAX_SLIPPAGE_PERCENT); require(maxAmountToSwap <= expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); } uint256 balanceBeforeAssetFrom = assetToSwapFrom.balanceOf(address(this)); require(balanceBeforeAssetFrom >= maxAmountToSwap, 'INSUFFICIENT_BALANCE_BEFORE_SWAP'); uint256 balanceBeforeAssetTo = assetToSwapTo.balanceOf(address(this)); address tokenTransferProxy = augustus.getTokenTransferProxy(); assetToSwapFrom.safeApprove(tokenTransferProxy, 0); assetToSwapFrom.safeApprove(tokenTransferProxy, maxAmountToSwap); if (toAmountOffset != 0) { require( toAmountOffset >= 4 && toAmountOffset <= buyCalldata.length - 32, 'TO_AMOUNT_OFFSET_OUT_OF_RANGE' ); assembly { mstore(add(buyCalldata, add(toAmountOffset, 32)), amountToReceive) } } (bool success, ) = address(augustus).call(buyCalldata); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } uint256 balanceAfterAssetFrom = assetToSwapFrom.balanceOf(address(this)); amountSold = balanceBeforeAssetFrom - balanceAfterAssetFrom; require(amountSold <= maxAmountToSwap, 'WRONG_BALANCE_AFTER_SWAP'); uint256 amountReceived = assetToSwapTo.balanceOf(address(this)) - balanceBeforeAssetTo; require(amountReceived >= amountToReceive, 'INSUFFICIENT_AMOUNT_RECEIVED'); emit Bought(address(assetToSwapFrom), address(assetToSwapTo), amountSold, amountReceived); } function _buyOnParaSwap( uint256 toAmountOffset, bytes memory paraswapData, IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive ) internal returns (uint256 amountSold) { (bytes memory buyCalldata, IParaSwapAugustus augustus) = abi.decode( paraswapData, (bytes, IParaSwapAugustus) ); require(AUGUSTUS_REGISTRY.isValidAugustus(address(augustus)), 'INVALID_AUGUSTUS'); { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(address(assetToSwapFrom)); uint256 toAssetPrice = _getPrice(address(assetToSwapTo)); uint256 expectedMaxAmountToSwap = ((amountToReceive * (toAssetPrice * (10 ** fromAssetDecimals))) / (fromAssetPrice * (10 ** toAssetDecimals))) .percentMul(PercentageMath.PERCENTAGE_FACTOR + MAX_SLIPPAGE_PERCENT); require(maxAmountToSwap <= expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); } uint256 balanceBeforeAssetFrom = assetToSwapFrom.balanceOf(address(this)); require(balanceBeforeAssetFrom >= maxAmountToSwap, 'INSUFFICIENT_BALANCE_BEFORE_SWAP'); uint256 balanceBeforeAssetTo = assetToSwapTo.balanceOf(address(this)); address tokenTransferProxy = augustus.getTokenTransferProxy(); assetToSwapFrom.safeApprove(tokenTransferProxy, 0); assetToSwapFrom.safeApprove(tokenTransferProxy, maxAmountToSwap); if (toAmountOffset != 0) { require( toAmountOffset >= 4 && toAmountOffset <= buyCalldata.length - 32, 'TO_AMOUNT_OFFSET_OUT_OF_RANGE' ); assembly { mstore(add(buyCalldata, add(toAmountOffset, 32)), amountToReceive) } } (bool success, ) = address(augustus).call(buyCalldata); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } uint256 balanceAfterAssetFrom = assetToSwapFrom.balanceOf(address(this)); amountSold = balanceBeforeAssetFrom - balanceAfterAssetFrom; require(amountSold <= maxAmountToSwap, 'WRONG_BALANCE_AFTER_SWAP'); uint256 amountReceived = assetToSwapTo.balanceOf(address(this)) - balanceBeforeAssetTo; require(amountReceived >= amountToReceive, 'INSUFFICIENT_AMOUNT_RECEIVED'); emit Bought(address(assetToSwapFrom), address(assetToSwapTo), amountSold, amountReceived); } function _buyOnParaSwap( uint256 toAmountOffset, bytes memory paraswapData, IERC20Detailed assetToSwapFrom, IERC20Detailed assetToSwapTo, uint256 maxAmountToSwap, uint256 amountToReceive ) internal returns (uint256 amountSold) { (bytes memory buyCalldata, IParaSwapAugustus augustus) = abi.decode( paraswapData, (bytes, IParaSwapAugustus) ); require(AUGUSTUS_REGISTRY.isValidAugustus(address(augustus)), 'INVALID_AUGUSTUS'); { uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom); uint256 toAssetDecimals = _getDecimals(assetToSwapTo); uint256 fromAssetPrice = _getPrice(address(assetToSwapFrom)); uint256 toAssetPrice = _getPrice(address(assetToSwapTo)); uint256 expectedMaxAmountToSwap = ((amountToReceive * (toAssetPrice * (10 ** fromAssetDecimals))) / (fromAssetPrice * (10 ** toAssetDecimals))) .percentMul(PercentageMath.PERCENTAGE_FACTOR + MAX_SLIPPAGE_PERCENT); require(maxAmountToSwap <= expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage'); } uint256 balanceBeforeAssetFrom = assetToSwapFrom.balanceOf(address(this)); require(balanceBeforeAssetFrom >= maxAmountToSwap, 'INSUFFICIENT_BALANCE_BEFORE_SWAP'); uint256 balanceBeforeAssetTo = assetToSwapTo.balanceOf(address(this)); address tokenTransferProxy = augustus.getTokenTransferProxy(); assetToSwapFrom.safeApprove(tokenTransferProxy, 0); assetToSwapFrom.safeApprove(tokenTransferProxy, maxAmountToSwap); if (toAmountOffset != 0) { require( toAmountOffset >= 4 && toAmountOffset <= buyCalldata.length - 32, 'TO_AMOUNT_OFFSET_OUT_OF_RANGE' ); assembly { mstore(add(buyCalldata, add(toAmountOffset, 32)), amountToReceive) } } (bool success, ) = address(augustus).call(buyCalldata); if (!success) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } uint256 balanceAfterAssetFrom = assetToSwapFrom.balanceOf(address(this)); amountSold = balanceBeforeAssetFrom - balanceAfterAssetFrom; require(amountSold <= maxAmountToSwap, 'WRONG_BALANCE_AFTER_SWAP'); uint256 amountReceived = assetToSwapTo.balanceOf(address(this)) - balanceBeforeAssetTo; require(amountReceived >= amountToReceive, 'INSUFFICIENT_AMOUNT_RECEIVED'); emit Bought(address(assetToSwapFrom), address(assetToSwapTo), amountSold, amountReceived); } }
5,004,764
[ 1, 2171, 23529, 12521, 38, 9835, 4216, 225, 29704, 326, 4058, 364, 30143, 310, 2430, 603, 2280, 69, 12521, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 3360, 23529, 12521, 38, 9835, 4216, 353, 3360, 23529, 12521, 4216, 288, 203, 225, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 40, 6372, 31, 203, 225, 1450, 21198, 410, 10477, 364, 2254, 5034, 31, 203, 203, 225, 467, 23529, 12521, 37, 637, 641, 407, 4243, 1071, 11732, 28235, 43, 5996, 3378, 67, 5937, 25042, 31, 203, 203, 225, 3885, 12, 203, 565, 467, 2864, 7148, 2249, 6138, 2249, 16, 203, 565, 1758, 2845, 16, 203, 565, 467, 23529, 12521, 37, 637, 641, 407, 4243, 31350, 641, 407, 4243, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 2163, 31, 203, 5666, 288, 16397, 10477, 97, 628, 4622, 69, 836, 19, 3644, 17, 90, 23, 19, 16351, 87, 19, 8373, 19, 31417, 19, 15949, 19, 16397, 10477, 18, 18281, 13506, 203, 5666, 288, 2579, 1371, 7148, 2249, 97, 628, 4622, 69, 836, 19, 3644, 17, 90, 23, 19, 16351, 87, 19, 15898, 19, 2579, 1371, 7148, 2249, 18, 18281, 13506, 203, 5666, 288, 45, 654, 39, 3462, 40, 6372, 97, 628, 4622, 69, 836, 19, 3644, 17, 90, 23, 19, 16351, 87, 19, 11037, 19, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 45, 654, 39, 3462, 40, 6372, 18, 18281, 13506, 203, 5666, 288, 9890, 654, 39, 3462, 97, 628, 4622, 69, 836, 19, 3644, 17, 90, 23, 19, 16351, 87, 19, 11037, 19, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 9890, 654, 39, 3462, 18, 18281, 13506, 203, 5666, 288, 45, 23529, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-07-18 */ pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view 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); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- 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 BioDoge is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "Bio Doge"; symbol = "BDOGE"; decimals = 18; _totalSupply = 100000000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } 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 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; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "Bio Doge"; symbol = "BDOGE"; decimals = 18; _totalSupply = 100000000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
10,542,381
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 38, 1594, 463, 717, 73, 14432, 203, 3639, 3273, 273, 315, 38, 3191, 7113, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 12648, 9449, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/// base.sol -- basic ERC20 implementation // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >=0.4.23; import "erc20.sol"; import "math.sol"; contract TokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() external view returns (uint) { return _supply; } function balanceOf(address src) external view returns (uint) { return _balances[src]; } function allowance(address src, address guy) external view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); //Revert if funds insufficient. } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) external returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } event Mint(address guy, uint wad); event Burn(address guy, uint wad); function mint(uint wad) internal { //Note: _supply constant _balances[msg.sender] = add(_balances[msg.sender], wad); emit Mint(msg.sender, wad); } function burn(uint wad) internal { //Note: _supply constant _balances[msg.sender] = sub(_balances[msg.sender], wad); //Revert if funds insufficient. emit Burn(msg.sender, wad); } } // Copyright (C) 2020 Benjamin M J D Wang // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.5.0; import "gov_interface_v2.sol"; //Import governance contract interface. import "proposal_tokens_v3.sol"; //proposal tokens data structure and transfer functions. contract onchain_gov_BMJDW2020 is IOnchain_gov, proposal_tokens, onchain_gov_events{ ERC20 public ERC20Interface; function calculate_price(uint _side, uint _now) public view returns (uint p) { //Function could also be internal if users can calculate price themselves easily. uint[4] memory price_data = proposal[pa_proposal_id].next_init_price_data; p = wmul(price_data[_side], wpow(price_data[2], mul(price_data[3], sub(_now, current_tranche_start))/WAD)); //(WAD) //p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD)); /** p = WAD p1 = WAD e = WAD f = int now = int start = int */ } function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external { uint param = wdiv(_amount, mul(_next_min_prop_period, _prop_period)); //_next_min_prop_period is purely an anti-spam prevention to stop spammers submitting proposals with very small amounts. Assume WAD since _next_min_prop_period * _prop_period may result in large number. require(param > top_param, "param < top_param"); require(_prop_period > proposal[pa_proposal_id].next_min_prop_period, "prop_period < minimum"); //check that voting period is greater than the next_min_prop_period of the last accepted proposal. top_param = param; //Sets current top param to that of the resently submitted proposal. ERC20Interface.transferFrom(msg.sender, address(this), _amount / 100);//Takes proposer's deposit in dai. This must throw an error and revert if the user does not have enough funds available. ERC20Interface.transfer(proposal[top_proposal_id].beneficiary, proposal[top_proposal_id].amount / 100); ////Pays back the deposit to the old top proposer in dai. uint id = ++nonce; //Implicit conversion to uint256 top_proposal_id = uint40(id); //set top proposal id and is used as id for recording data. //Store all new proposal data: proposal[id].beneficiary = msg.sender; proposal[id].amount = _amount; proposal[id].next_init_tranche_size = _next_init_tranche_size; proposal[id].next_init_price_data = _next_init_price_data; proposal[id].next_reject_spread_threshold = _next_reject_spread_threshold; proposal[id].next_minimum_sell_volume = _next_minimum_sell_volume; proposal[id].prop_period = _prop_period; proposal[id].next_min_prop_period = _next_min_prop_period; proposal[id].reset_time_period = _reset_time_period; emit NewSubmission(uint40(id), msg.sender, _amount, _next_init_tranche_size, _next_init_price_data, _next_reject_spread_threshold, _next_minimum_sell_volume, _prop_period, _next_min_prop_period, _reset_time_period); } function init_proposal(uint40 _id) external { //'sell' and 'buy' indicate sell and buy side from the user perspective in the context of governance tokens even though it is in reference to dai. require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished. /** When proposal has ended and was accepted: pa_proposal_id = running_proposal_id running_proposal_id = 0 When proposal has ended and was rejected: pa_proposal_id remains the same. running_proposal_id = 0 When initialised: running_proposal_id = top_proposal_id top_proposal_id = 1; proposal status = 1; */ require (_id == top_proposal_id, "Wrong id."); //Require correct proposal to be chosen. require (_id != 0, "_id != 0"); //Cannot initialise the genesis proposal. running_proposal_id = _id; //Update running proposal id. top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposa_id is necessary in the submission function above for the first submission after each proposal. proposal[_id].status = 1; //Set proposal status to 'ongoing'. uint init_sell_size = proposal[pa_proposal_id].next_init_tranche_size; //Init sell tranche size. proposal[_id].side[1].current_tranche_size = init_sell_size; uint minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume; uint dai_out = add(wmul(990000000000000000, proposal[_id].amount), minimum_sell_volume); uint net_balance = net_dai_balance; uint init_buy_size; //Make sure that the contract is always running a positive net dai balance: if (dai_out > net_balance){ init_buy_size = wmul(wdiv(init_sell_size, minimum_sell_volume), sub(dai_out, net_balance)); } else{ init_buy_size = init_sell_size; } proposal[_id].side[0].current_tranche_size = init_buy_size; current_tranche_start = uint40(now); proposal[_id].proposal_start = uint40(now); top_param = 0; //reset top param. emit InitProposal (_id, init_buy_size, init_sell_size); } function reset() external{ require (uint40(now) - proposal[pa_proposal_id].proposal_start > proposal[pa_proposal_id].reset_time_period, "Reset time not elapsed."); //Tests amount of time since last proposal passed. uint id = ++nonce; //Set proposal data: proposal[id].beneficiary = msg.sender; proposal[id].next_min_prop_period = proposal[pa_proposal_id].next_min_prop_period; proposal[id].next_init_tranche_size = proposal[pa_proposal_id].next_init_tranche_size; proposal[id].next_init_price_data = proposal[pa_proposal_id].next_init_price_data; proposal[id].next_reject_spread_threshold = proposal[pa_proposal_id].next_reject_spread_threshold; uint next_minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume; proposal[id].next_minimum_sell_volume = next_minimum_sell_volume; proposal[id].reset_time_period = proposal[pa_proposal_id].reset_time_period; require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished. running_proposal_id = uint40(id); //Update running proposal id. top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposal_id is necessary in the submission function above for the first submission after each proposal. proposal[id].status = 4; //Set proposal status to 'ongoing reset proposal'. proposal[id].side[0].current_tranche_size = next_minimum_sell_volume; proposal[id].side[1].current_tranche_size = next_minimum_sell_volume; //Set as size of tranche as minimum sell volume. current_tranche_start = uint40(now); proposal[id].proposal_start = uint40(now); top_param = 0; //reset top param. emit Reset(id); } function all_trades_common(uint _id, uint _side, uint _tranche_size) internal view returns (uint current_tranche_t) { require (_id == running_proposal_id, "Wrong id."); //User can only trade on currently running proposal. require (proposal[_id].side[_side].current_tranche_size == _tranche_size, "Wrong tranche size."); //Make sure the user's selected tranche size is the current tranche size. Without this they may choose arbitrary tranches and then loose tokens. require (proposal[_id].side[_side].tranche[_tranche_size].price == 0, "Tranche already closed."); //Check tranche is still open. current_tranche_t = proposal[_id].side[_side].current_tranche_total; } function buy_sell_common(uint _id, uint _input_amount, uint _side, uint _tranche_size, uint _current_dai_price) internal { uint current_tranche_t = all_trades_common(_id, _side, _tranche_size); require (wmul(add(_input_amount, current_tranche_t), _current_dai_price) < _tranche_size, "Try closing tranche."); //Makes sure users cannot send tokens beyond or even up to the current tranche size since this is for the tranche close function. proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = add(proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender], _input_amount); //Record proposal balance. proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time = sub(now, current_tranche_start); //Set time of most recent trade so 2nd to last trade time can be recorded. Offset by current_tranche_start to account for zero initial value. proposal[_id].side[_side].current_tranche_total = add(current_tranche_t, _input_amount); //Update current_tranche_total. emit NewTrancheTotal (_side, current_tranche_t + _input_amount); } function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external { //Set correct amount of dai buy_sell_common(_id, _input_dai_amount, 0, _tranche_size, WAD); //For buying _dai_amount = _input_dai_amount. Dai price = 1.0. ERC20Interface.transferFrom(msg.sender, address(this), _input_dai_amount); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction. } function sell(uint _id, uint _input_token_amount, uint _tranche_size) external { //Set correct amount of dai buy_sell_common(_id, _input_token_amount, 1, _tranche_size, calculate_price(1, now)); //For selling, the current dai amount must be used based on current price. burn(_input_token_amount); //Remove user governance tokens. SafeMath should revert with insufficient funds. } function close_buy_sell_common_1(uint _id, uint _side, uint _tranche_size) internal returns(uint price, uint final_trade_price, uint current_tranche_t) { current_tranche_t = all_trades_common(_id, _side, _tranche_size); price = calculate_price(_side, add(proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time, current_tranche_start)); //(WAD) Sets price for all traders. final_trade_price = calculate_price(_side, now); proposal[_id].side[_side].tranche[_tranche_size].price = price; //(WAD) Sets price for all traders. proposal[_id].side[_side].tranche[_tranche_size].final_trade_price = final_trade_price; //(WAD) Sets price for only the final trader. proposal[_id].side[_side].tranche[_tranche_size].final_trade_address = msg.sender; //Record address of final trade. proposal[_id].side[_side].current_tranche_total = 0; //Reset current_tranche_total to zero. } function close_buy_sell_common_2(uint _id, uint _balance_amount, uint _side, uint _tranche_size, uint _input_dai_amount, uint _current_tranche_t_dai, uint _this_tranche_tokens_total) internal { require (add(_input_dai_amount, _current_tranche_t_dai) >= _tranche_size, "Not enough to close."); //Check that the user has provided enough dai or equivalent to close the tranche. proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = _balance_amount; //Record final trade amount. if (proposal[_id].side[(_side+1)%2].tranche[proposal[_id].side[(_side+1)%2].current_tranche_size].price != 0){ //Check whether tranche for other side has closed. current_tranche_start = uint40(now); //Reset timer for next tranche. proposal[_id].side[_side].total_tokens_traded = add(proposal[_id].side[_side].total_tokens_traded, _this_tranche_tokens_total); proposal[_id].side[(_side+1)%2].total_tokens_traded = add(proposal[_id].side[(_side+1)%2].total_tokens_traded, lct_tokens_traded); //Sets total tokens traded on each side now that tranches on both sides have closed (using lct_tokens_traded which was recorded when the other side closed.) proposal[_id].side[_side].total_dai_traded = add(proposal[_id].side[_side].total_dai_traded, _tranche_size); proposal[_id].side[(_side+1)%2].total_dai_traded = add(proposal[_id].side[(_side+1)%2].total_dai_traded, proposal[_id].side[(_side+1)%2].current_tranche_size); //Add total dai traded in tranche to total_dai_traded. //Add total dai traded in tranche to total_dai_traded. if (proposal[_id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume) { //if sell volume has reached the minimum and reset has not already happened: then reset the tranche sizes on both sides to the same value. uint new_size = mul(_tranche_size, 2); proposal[_id].side[0].current_tranche_size = new_size; proposal[_id].side[1].current_tranche_size = new_size; //Set both tranche sizes to the same size. } else { proposal[_id].side[_side].current_tranche_size = mul(_tranche_size, 2); proposal[_id].side[(_side+1)%2].current_tranche_size = mul(proposal[_id].side[(_side+1)%2].current_tranche_size, 2); //Double the current tranche sizes. } } else{ lct_tokens_traded = _this_tranche_tokens_total; //Records last closed tranche tokens traded total for when both tranches close. } emit TrancheClose (_side, _tranche_size, _this_tranche_tokens_total); //Users must check when both sides have closed and then calculate total traded themselves by summing the TrancheClose data. } function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external { (uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 0, _tranche_size); uint dai_amount_left = sub(_tranche_size, current_tranche_t); //Calculates new amount of dai for user to give. uint this_tranche_tokens_total = add(wmul(current_tranche_t,price), wmul(dai_amount_left, final_trade_price)); //Update total_tokens_traded close_buy_sell_common_2(_id, dai_amount_left, 0, _tranche_size, _input_dai_amount, current_tranche_t, this_tranche_tokens_total); ERC20Interface.transferFrom(msg.sender, address(this), dai_amount_left); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction. } function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external { (uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 1, _tranche_size); uint dai_amount_left = sub(_tranche_size, wmul(current_tranche_t, price)); //Calculates dai_amount_left in tranche which is based on the price the other sellers will pay, not the current price. uint token_equiv_left = wdiv(dai_amount_left, final_trade_price); //Calculate amount of tokens to give user based on dai amount left. uint equiv_input_dai_amount = wmul(_input_token_amount, final_trade_price); //Equivalent amount of dai at current prices based on the user amount of tokens. uint this_tranche_tokens_total = add(current_tranche_t, token_equiv_left); //Update total_tokens_traded close_buy_sell_common_2(_id, token_equiv_left, 1, _tranche_size, equiv_input_dai_amount, wmul(current_tranche_t, price), this_tranche_tokens_total); burn(token_equiv_left); //Remove user governance tokens. SafeMath should revert with insufficient funds. } function accept_prop() external { uint id = running_proposal_id; require (proposal[id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached. //Collect state data into memory for calculating prices: uint current_total_dai_sold = proposal[id].side[0].total_dai_traded; uint previous_total_dai_bought = proposal[pa_proposal_id].side[1].total_dai_traded; uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded; uint proposal_amount = proposal[id].amount; uint accept_current_p_amount; uint accept_previous_p_amount; //Calculate where attacker's capital will be spent for accept case and reject case: if (current_total_dai_sold < add(previous_total_dai_bought, proposal_amount)){ accept_current_p_amount = proposal_amount; //accept_previous_p_amount = 0 by default. } else{ //accept_current_p_amount = 0 by default. accept_previous_p_amount = proposal_amount; } //Attacker aims to attack at weakest point. The assumed ratio of z_a_p to y_a_p determines where attack is spending capital i.e. where they are attacking. So the attacker will aim to spend the most where the amount of dai is lowest, since this will have the greatest effect on price. Or in other words we want to know the minimum of the minimum prices. uint accept_price = wmul(wdiv(sub(current_total_dai_sold, accept_current_p_amount), current_total_tokens_bought), wdiv(proposal[pa_proposal_id].side[1].total_tokens_traded, add(accept_previous_p_amount, previous_total_dai_bought))); //Minimum non-manipulated price. if (accept_price > WAD){ //If proposal accepted: (change to require later) proposal[id].status = 2; ERC20Interface.transfer(proposal[id].beneficiary, proposal[id].amount); pa_proposal_id = running_proposal_id; running_proposal_id = 0; _supply = sub(add(_supply, proposal[id].side[0].total_tokens_traded), proposal[id].side[1].total_tokens_traded); net_dai_balance = sub(add(net_dai_balance, current_total_dai_sold), add(wmul(990000000000000000, proposal_amount), proposal[id].side[1].total_dai_traded)); //Update net_dai_balance } emit AcceptAttempt (accept_price, wdiv(current_total_dai_sold, current_total_tokens_bought), wdiv(proposal[id].side[1].total_dai_traded, proposal[id].side[1].total_tokens_traded)); } function reject_prop_spread() external { uint id = running_proposal_id; require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal. uint recent_buy_price = proposal[id].side[0].tranche[proposal[id].side[0].current_tranche_size].price; //Price of current tranche. uint recent_sell_price = proposal[id].side[1].tranche[proposal[id].side[1].current_tranche_size].price; if (recent_buy_price == 0) { //Checks whether current tranche has closed. If not then latest price is calculated. recent_buy_price = calculate_price(0, now); } if (recent_sell_price == 0) { recent_sell_price = calculate_price(1, now); } uint spread = wmul(recent_buy_price, recent_sell_price); //Spread based on current tranche using auction prices that have not finished when necessary. You cannot manipulate spread to be larger so naive price is used. if (spread > proposal[pa_proposal_id].next_reject_spread_threshold){ proposal[id].status = 3; running_proposal_id = 0; } emit RejectSpreadAttempt(spread); } function reject_prop_time() external { uint id = running_proposal_id; require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal. require (now - proposal[id].proposal_start > proposal[id].prop_period, "Still has time."); proposal[id].status = 3; running_proposal_id = 0; emit TimeRejected(); } function accept_reset() external { uint id = running_proposal_id; uint current_total_dai_bought = proposal[id].side[1].total_dai_traded; uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded; uint current_total_tokens_sold = proposal[id].side[1].total_tokens_traded; require (current_total_dai_bought >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached. require (proposal[id].status == 4, "Not reset proposal."); //Check that this is a reset proposal rather than just any standard proposal. proposal[id].status = 2; //Proposal accepted pa_proposal_id = running_proposal_id; running_proposal_id = 0; _supply = sub(add(_supply, current_total_tokens_bought), current_total_tokens_sold); //Update supply. //Net_dai_balance remains the same since equal dai is traded on both sides and proposal.amount = 0. emit ResetAccepted(wdiv(proposal[id].side[0].total_dai_traded, current_total_tokens_bought), wdiv(current_total_dai_bought, current_total_tokens_sold)); } function redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){ require (proposal[_id].status == _status, "incorrect status"); amount = proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender]; proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = 0; //Set balance to zero. } function redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) { require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Other side never finished."); //Make sure that both sides of the tranche finished. amount = wmul(redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function. } function buy_redeem(uint _id, uint _tranche_size) external { mint(redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens. } function sell_redeem(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai. } function buy_refund_reject(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai. } function sell_refund_reject(uint _id, uint _tranche_size) external { mint(redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens. } function buy_refund_accept(uint _id, uint _tranche_size) external { require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished. ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 2)); //User paid with dai so they get back dai. } function sell_refund_accept(uint _id, uint _tranche_size) external { require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished. mint(redeem_refund_common(_id, _tranche_size, 1, 2));//User paid with tokens so they get back tokens. } //Functions for redeeming final trades: function final_redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){ require (proposal[_id].status == _status, "Incorrect status"); require (proposal[_id].side[_side].tranche[_tranche_size].final_trade_address == msg.sender, "Wasn't you."); amount = proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount; proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = 0; //Set balance to zero. } function final_redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) { require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Try refund."); //Make sure that both sides of the tranche finished. amount = wmul(final_redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].final_trade_price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function. } function final_buy_redeem(uint _id, uint _tranche_size) external { mint(final_redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens. } function final_sell_redeem(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, final_redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai. } function final_buy_refund_reject(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, final_redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai. } function final_sell_refund_reject(uint _id, uint _tranche_size) external { mint(final_redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens. } constructor(uint _init_price, ERC20 _ERC20Interface) public { //(WAD) _init_price is defined as dai_amount/token_amount. _supply is defined in the TokenBase constructor. ERC20Interface = _ERC20Interface; //fakeDai contract. Use checksum version of address. //Genesis proposal which will be used by first proposal. proposal[0].status = 2; proposal[0].beneficiary = address(this); //Because the submission of first proposal would break the erc20 transfer function if address(0) is used, therefore, we use this address. proposal[0].amount = 0; //For first proposal submission, 0/100 will be returned to contract address. proposal[0].prop_period = 1; proposal[0].next_min_prop_period = 1; proposal[0].next_init_tranche_size = wmul(_supply, _init_price)/100; proposal[0].next_init_price_data = [wdiv(WAD, wmul(40*WAD, _init_price)), wdiv(_init_price, 2*WAD) , 1003858241594480000, 10**17]; //Price here is defined as [amount received by user after proposal]/[amount given by user before]. //Price should double every 30 mins. Buy price starts above sell price at max potential price - vice versa for sell price. p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD)). e = 2**(1/180). Value of f defines 10 seconds as 1 int. proposal[0].next_reject_spread_threshold = 7 * WAD; proposal[0].next_minimum_sell_volume = wmul(_supply, _init_price)/100; //(10 ** -6) dai minimum sell volume. proposal[0].reset_time_period = 10; proposal[0].proposal_start = uint40(now); //Genesis trade values: proposal[0].side[0].total_dai_traded = wmul(_supply, _init_price); //0.001 dai initial market cap. (10 ** -6) dai initial price. proposal[0].side[1].total_dai_traded = wmul(_supply, _init_price); proposal[0].side[0].total_tokens_traded = _supply; proposal[0].side[1].total_tokens_traded = _supply; } //price = total_dai_traded/_supply } /// erc20.sol -- API for the ERC20 token standard // See <https://github.com/ethereum/EIPs/issues/20>. // This file likely does not meet the threshold of originality // required for copyright to apply. As a result, this is free and // unencumbered software belonging to the public domain. pragma solidity >0.4.20; contract ERC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); } contract ERC20 is ERC20Events { function totalSupply() external view returns (uint); function balanceOf(address guy) external view returns (uint); function allowance(address src, address guy) external view returns (uint); function approve(address guy, uint wad) external returns (bool); function transfer(address dst, uint wad) external returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } pragma solidity ^0.5.0; contract onchain_gov_events{ event NewSubmission (uint40 indexed id, address beneficiary, uint amount, uint next_init_tranche_size, uint[4] next_init_price_data, uint next_reject_spread_threshold, uint next_minimum_sell_volume, uint40 prop_period, uint40 next_min_prop_period, uint40 reset_time_period); event InitProposal (uint40 id, uint init_buy_tranche, uint init_sell_tranche); event Reset(uint id); event NewTrancheTotal (uint side, uint current_tranche_t); //Measured in terms of given token. event TrancheClose (uint side, uint current_tranche_size, uint this_tranche_tokens_total); //Indicates tranche that closed and whether both or just one side have now closed. event AcceptAttempt (uint accept_price, uint average_buy_dai_price, uint average_sell_dai_price); // event RejectSpreadAttempt(uint spread); event TimeRejected(); event ResetAccepted(uint average_buy_dai_price, uint average_sell_dai_price); } interface IOnchain_gov{ function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint); function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint); function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool); function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount) external returns (bool); function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool); function calculate_price(uint _side, uint _now) external view returns (uint p); function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external; function init_proposal(uint40 _id) external; function reset() external; function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external; function sell(uint _id, uint _input_token_amount, uint _tranche_size) external; function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external; function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external; function accept_prop() external; function reject_prop_spread() external; function reject_prop_time() external; function accept_reset() external; function buy_redeem(uint _id, uint _tranche_size) external; function sell_redeem(uint _id, uint _tranche_size) external; function buy_refund_reject(uint _id, uint _tranche_size) external; function sell_refund_reject(uint _id, uint _tranche_size) external; function buy_refund_accept(uint _id, uint _tranche_size) external; function sell_refund_accept(uint _id, uint _tranche_size) external; function final_buy_redeem(uint _id, uint _tranche_size) external; function final_sell_redeem(uint _id, uint _tranche_size) external; function final_buy_refund_reject(uint _id, uint _tranche_size) external; function final_sell_refund_reject(uint _id, uint _tranche_size) external; } //27 functions /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >0.4.13; contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } uint constant WAD = 10 ** 18; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function wpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : WAD; for (n /= 2; n != 0; n /= 2) { x = wmul(x, x); if (n % 2 != 0) { z = wmul(z, x); } } } } // Copyright (C) 2020 Benjamin M J D Wang // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.5.0; import "base.sol"; contract proposal_tokens is TokenBase(0) { //Proposal mappings mapping (uint => Proposal) internal proposal; //proposal id is taken from nonce. struct Proposal { //Records all data that is submitted during proposal submission. address beneficiary; uint amount; //(WAD) uint next_init_tranche_size; //(WAD) uint[4] next_init_price_data; //Array of data for next proposal [initial buy price (WAD), initial sell price (WAD), base (WAD), exponent factor (int)] uint next_reject_spread_threshold; //(WAD) uint next_minimum_sell_volume; //(WAD) uint8 status; //0 = not submitted or not ongoing, 1 = ongoing, 2 = accepted, 3 = rejected, 4 = ongoing reset proposal. uint40 prop_period; //(int) How long users have to prop before prop rejected. uint40 next_min_prop_period; //(int) Minimum prop period for the next proposal. uint40 reset_time_period; //(int) Time period necessary for proposal to be reset. uint40 proposal_start; //(int) This is to provide a time limit for the length of proposals. mapping (uint => Side) side; //Each side of proposal } struct Side { //Current tranche data for this interval. uint current_tranche_total; //This is in units of given tokens rather than only dai tokens: dai for buying, proposal token for selling. For selling, total equivalent dai tokens is calculated within the function. uint total_dai_traded; //Used for calculating acceptance/rejection thresholds. uint total_tokens_traded; //Used for calculating acceptance/rejection thresholds. uint current_tranche_size; //(WAD) This is maximum amount or equivalent maximum amount of dai tokens the tranche can be. mapping (uint => Tranche) tranche; //Data for each tranche that must be recorded. Size of tranche will be the uint tranche id. } struct Tranche { uint price; //(WAD) Final tranche price for each tranche. Price is defined as if the user is selling their respective token types to the proposal so price increases over time to incentivise selling. Buy price is price of dai in proposal tokens where sell price is the price in dai. uint final_trade_price; uint recent_trade_time; uint final_trade_amount; address final_trade_address; mapping (address => uint) balance; //(WAD) mapping (address => mapping (address => uint256)) approvals; } uint40 internal nonce; // Nonce for submitted proposals that have a higher param regardless of whether they are chosen or not. Will also be used for chosen proposals. uint40 public top_proposal_id; //Id of current top proposal. uint40 public running_proposal_id; //id of the proposal that has been initialised. uint40 public pa_proposal_id; //Previously accepted proposal id. uint40 current_tranche_start; //(int) uint public top_param; //(WAD) uint internal lct_tokens_traded; //Records the total tokens traded for the tranche on the first side to close. This means that this calculation won't need to be repeated when both sides close. uint internal net_dai_balance; //The contract's dai balance as if all redemptions and refunds are collected in full, re-calculated at the end of every accepted proposal. function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint) { return proposal[_id].side[_side].tranche[_tranche].balance[_account]; } function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint) { return proposal[_id].side[_side].tranche[_tranche].approvals[_from][_guy]; } function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool) { return proposal_transfer_from(_id, _side, _tranche, msg.sender, _to, _amount); } event ProposalTokenTransfer(address from, address to, uint amount); function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount) public returns (bool) { if (_from != msg.sender) { proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender] = sub(proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender], _amount); //Revert if funds insufficient. } proposal[_id].side[_side].tranche[_tranche].balance[_from] = sub(proposal[_id].side[_side].tranche[_tranche].balance[_from], _amount); proposal[_id].side[_side].tranche[_tranche].balance[_to] = add(proposal[_id].side[_side].tranche[_tranche].balance[_to], _amount); emit ProposalTokenTransfer(_from, _to, _amount); return true; } event ProposalTokenApproval(address account, address guy, uint amount); function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool) { proposal[_id].side[_side].tranche[_tranche].approvals[msg.sender][_guy] = _amount; emit ProposalTokenApproval(msg.sender, _guy, _amount); return true; } } /// base.sol -- basic ERC20 implementation // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >=0.4.23; import "erc20.sol"; import "math.sol"; contract TokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() external view returns (uint) { return _supply; } function balanceOf(address src) external view returns (uint) { return _balances[src]; } function allowance(address src, address guy) external view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); //Revert if funds insufficient. } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) external returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } event Mint(address guy, uint wad); event Burn(address guy, uint wad); function mint(uint wad) internal { //Note: _supply constant _balances[msg.sender] = add(_balances[msg.sender], wad); emit Mint(msg.sender, wad); } function burn(uint wad) internal { //Note: _supply constant _balances[msg.sender] = sub(_balances[msg.sender], wad); //Revert if funds insufficient. emit Burn(msg.sender, wad); } } // Copyright (C) 2020 Benjamin M J D Wang // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.5.0; import "gov_interface_v2.sol"; //Import governance contract interface. import "proposal_tokens_v3.sol"; //proposal tokens data structure and transfer functions. contract onchain_gov_BMJDW2020 is IOnchain_gov, proposal_tokens, onchain_gov_events{ ERC20 public ERC20Interface; function calculate_price(uint _side, uint _now) public view returns (uint p) { //Function could also be internal if users can calculate price themselves easily. uint[4] memory price_data = proposal[pa_proposal_id].next_init_price_data; p = wmul(price_data[_side], wpow(price_data[2], mul(price_data[3], sub(_now, current_tranche_start))/WAD)); //(WAD) //p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD)); /** p = WAD p1 = WAD e = WAD f = int now = int start = int */ } function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external { uint param = wdiv(_amount, mul(_next_min_prop_period, _prop_period)); //_next_min_prop_period is purely an anti-spam prevention to stop spammers submitting proposals with very small amounts. Assume WAD since _next_min_prop_period * _prop_period may result in large number. require(param > top_param, "param < top_param"); require(_prop_period > proposal[pa_proposal_id].next_min_prop_period, "prop_period < minimum"); //check that voting period is greater than the next_min_prop_period of the last accepted proposal. top_param = param; //Sets current top param to that of the resently submitted proposal. ERC20Interface.transferFrom(msg.sender, address(this), _amount / 100);//Takes proposer's deposit in dai. This must throw an error and revert if the user does not have enough funds available. ERC20Interface.transfer(proposal[top_proposal_id].beneficiary, proposal[top_proposal_id].amount / 100); ////Pays back the deposit to the old top proposer in dai. uint id = ++nonce; //Implicit conversion to uint256 top_proposal_id = uint40(id); //set top proposal id and is used as id for recording data. //Store all new proposal data: proposal[id].beneficiary = msg.sender; proposal[id].amount = _amount; proposal[id].next_init_tranche_size = _next_init_tranche_size; proposal[id].next_init_price_data = _next_init_price_data; proposal[id].next_reject_spread_threshold = _next_reject_spread_threshold; proposal[id].next_minimum_sell_volume = _next_minimum_sell_volume; proposal[id].prop_period = _prop_period; proposal[id].next_min_prop_period = _next_min_prop_period; proposal[id].reset_time_period = _reset_time_period; emit NewSubmission(uint40(id), msg.sender, _amount, _next_init_tranche_size, _next_init_price_data, _next_reject_spread_threshold, _next_minimum_sell_volume, _prop_period, _next_min_prop_period, _reset_time_period); } function init_proposal(uint40 _id) external { //'sell' and 'buy' indicate sell and buy side from the user perspective in the context of governance tokens even though it is in reference to dai. require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished. /** When proposal has ended and was accepted: pa_proposal_id = running_proposal_id running_proposal_id = 0 When proposal has ended and was rejected: pa_proposal_id remains the same. running_proposal_id = 0 When initialised: running_proposal_id = top_proposal_id top_proposal_id = 1; proposal status = 1; */ require (_id == top_proposal_id, "Wrong id."); //Require correct proposal to be chosen. require (_id != 0, "_id != 0"); //Cannot initialise the genesis proposal. running_proposal_id = _id; //Update running proposal id. top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposa_id is necessary in the submission function above for the first submission after each proposal. proposal[_id].status = 1; //Set proposal status to 'ongoing'. uint init_sell_size = proposal[pa_proposal_id].next_init_tranche_size; //Init sell tranche size. proposal[_id].side[1].current_tranche_size = init_sell_size; uint minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume; uint dai_out = add(wmul(990000000000000000, proposal[_id].amount), minimum_sell_volume); uint net_balance = net_dai_balance; uint init_buy_size; //Make sure that the contract is always running a positive net dai balance: if (dai_out > net_balance){ init_buy_size = wmul(wdiv(init_sell_size, minimum_sell_volume), sub(dai_out, net_balance)); } else{ init_buy_size = init_sell_size; } proposal[_id].side[0].current_tranche_size = init_buy_size; current_tranche_start = uint40(now); proposal[_id].proposal_start = uint40(now); top_param = 0; //reset top param. emit InitProposal (_id, init_buy_size, init_sell_size); } function reset() external{ require (uint40(now) - proposal[pa_proposal_id].proposal_start > proposal[pa_proposal_id].reset_time_period, "Reset time not elapsed."); //Tests amount of time since last proposal passed. uint id = ++nonce; //Set proposal data: proposal[id].beneficiary = msg.sender; proposal[id].next_min_prop_period = proposal[pa_proposal_id].next_min_prop_period; proposal[id].next_init_tranche_size = proposal[pa_proposal_id].next_init_tranche_size; proposal[id].next_init_price_data = proposal[pa_proposal_id].next_init_price_data; proposal[id].next_reject_spread_threshold = proposal[pa_proposal_id].next_reject_spread_threshold; uint next_minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume; proposal[id].next_minimum_sell_volume = next_minimum_sell_volume; proposal[id].reset_time_period = proposal[pa_proposal_id].reset_time_period; require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished. running_proposal_id = uint40(id); //Update running proposal id. top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposal_id is necessary in the submission function above for the first submission after each proposal. proposal[id].status = 4; //Set proposal status to 'ongoing reset proposal'. proposal[id].side[0].current_tranche_size = next_minimum_sell_volume; proposal[id].side[1].current_tranche_size = next_minimum_sell_volume; //Set as size of tranche as minimum sell volume. current_tranche_start = uint40(now); proposal[id].proposal_start = uint40(now); top_param = 0; //reset top param. emit Reset(id); } function all_trades_common(uint _id, uint _side, uint _tranche_size) internal view returns (uint current_tranche_t) { require (_id == running_proposal_id, "Wrong id."); //User can only trade on currently running proposal. require (proposal[_id].side[_side].current_tranche_size == _tranche_size, "Wrong tranche size."); //Make sure the user's selected tranche size is the current tranche size. Without this they may choose arbitrary tranches and then loose tokens. require (proposal[_id].side[_side].tranche[_tranche_size].price == 0, "Tranche already closed."); //Check tranche is still open. current_tranche_t = proposal[_id].side[_side].current_tranche_total; } function buy_sell_common(uint _id, uint _input_amount, uint _side, uint _tranche_size, uint _current_dai_price) internal { uint current_tranche_t = all_trades_common(_id, _side, _tranche_size); require (wmul(add(_input_amount, current_tranche_t), _current_dai_price) < _tranche_size, "Try closing tranche."); //Makes sure users cannot send tokens beyond or even up to the current tranche size since this is for the tranche close function. proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = add(proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender], _input_amount); //Record proposal balance. proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time = sub(now, current_tranche_start); //Set time of most recent trade so 2nd to last trade time can be recorded. Offset by current_tranche_start to account for zero initial value. proposal[_id].side[_side].current_tranche_total = add(current_tranche_t, _input_amount); //Update current_tranche_total. emit NewTrancheTotal (_side, current_tranche_t + _input_amount); } function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external { //Set correct amount of dai buy_sell_common(_id, _input_dai_amount, 0, _tranche_size, WAD); //For buying _dai_amount = _input_dai_amount. Dai price = 1.0. ERC20Interface.transferFrom(msg.sender, address(this), _input_dai_amount); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction. } function sell(uint _id, uint _input_token_amount, uint _tranche_size) external { //Set correct amount of dai buy_sell_common(_id, _input_token_amount, 1, _tranche_size, calculate_price(1, now)); //For selling, the current dai amount must be used based on current price. burn(_input_token_amount); //Remove user governance tokens. SafeMath should revert with insufficient funds. } function close_buy_sell_common_1(uint _id, uint _side, uint _tranche_size) internal returns(uint price, uint final_trade_price, uint current_tranche_t) { current_tranche_t = all_trades_common(_id, _side, _tranche_size); price = calculate_price(_side, add(proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time, current_tranche_start)); //(WAD) Sets price for all traders. final_trade_price = calculate_price(_side, now); proposal[_id].side[_side].tranche[_tranche_size].price = price; //(WAD) Sets price for all traders. proposal[_id].side[_side].tranche[_tranche_size].final_trade_price = final_trade_price; //(WAD) Sets price for only the final trader. proposal[_id].side[_side].tranche[_tranche_size].final_trade_address = msg.sender; //Record address of final trade. proposal[_id].side[_side].current_tranche_total = 0; //Reset current_tranche_total to zero. } function close_buy_sell_common_2(uint _id, uint _balance_amount, uint _side, uint _tranche_size, uint _input_dai_amount, uint _current_tranche_t_dai, uint _this_tranche_tokens_total) internal { require (add(_input_dai_amount, _current_tranche_t_dai) >= _tranche_size, "Not enough to close."); //Check that the user has provided enough dai or equivalent to close the tranche. proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = _balance_amount; //Record final trade amount. if (proposal[_id].side[(_side+1)%2].tranche[proposal[_id].side[(_side+1)%2].current_tranche_size].price != 0){ //Check whether tranche for other side has closed. current_tranche_start = uint40(now); //Reset timer for next tranche. proposal[_id].side[_side].total_tokens_traded = add(proposal[_id].side[_side].total_tokens_traded, _this_tranche_tokens_total); proposal[_id].side[(_side+1)%2].total_tokens_traded = add(proposal[_id].side[(_side+1)%2].total_tokens_traded, lct_tokens_traded); //Sets total tokens traded on each side now that tranches on both sides have closed (using lct_tokens_traded which was recorded when the other side closed.) proposal[_id].side[_side].total_dai_traded = add(proposal[_id].side[_side].total_dai_traded, _tranche_size); proposal[_id].side[(_side+1)%2].total_dai_traded = add(proposal[_id].side[(_side+1)%2].total_dai_traded, proposal[_id].side[(_side+1)%2].current_tranche_size); //Add total dai traded in tranche to total_dai_traded. //Add total dai traded in tranche to total_dai_traded. if (proposal[_id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume) { //if sell volume has reached the minimum and reset has not already happened: then reset the tranche sizes on both sides to the same value. uint new_size = mul(_tranche_size, 2); proposal[_id].side[0].current_tranche_size = new_size; proposal[_id].side[1].current_tranche_size = new_size; //Set both tranche sizes to the same size. } else { proposal[_id].side[_side].current_tranche_size = mul(_tranche_size, 2); proposal[_id].side[(_side+1)%2].current_tranche_size = mul(proposal[_id].side[(_side+1)%2].current_tranche_size, 2); //Double the current tranche sizes. } } else{ lct_tokens_traded = _this_tranche_tokens_total; //Records last closed tranche tokens traded total for when both tranches close. } emit TrancheClose (_side, _tranche_size, _this_tranche_tokens_total); //Users must check when both sides have closed and then calculate total traded themselves by summing the TrancheClose data. } function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external { (uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 0, _tranche_size); uint dai_amount_left = sub(_tranche_size, current_tranche_t); //Calculates new amount of dai for user to give. uint this_tranche_tokens_total = add(wmul(current_tranche_t,price), wmul(dai_amount_left, final_trade_price)); //Update total_tokens_traded close_buy_sell_common_2(_id, dai_amount_left, 0, _tranche_size, _input_dai_amount, current_tranche_t, this_tranche_tokens_total); ERC20Interface.transferFrom(msg.sender, address(this), dai_amount_left); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction. } function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external { (uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 1, _tranche_size); uint dai_amount_left = sub(_tranche_size, wmul(current_tranche_t, price)); //Calculates dai_amount_left in tranche which is based on the price the other sellers will pay, not the current price. uint token_equiv_left = wdiv(dai_amount_left, final_trade_price); //Calculate amount of tokens to give user based on dai amount left. uint equiv_input_dai_amount = wmul(_input_token_amount, final_trade_price); //Equivalent amount of dai at current prices based on the user amount of tokens. uint this_tranche_tokens_total = add(current_tranche_t, token_equiv_left); //Update total_tokens_traded close_buy_sell_common_2(_id, token_equiv_left, 1, _tranche_size, equiv_input_dai_amount, wmul(current_tranche_t, price), this_tranche_tokens_total); burn(token_equiv_left); //Remove user governance tokens. SafeMath should revert with insufficient funds. } function accept_prop() external { uint id = running_proposal_id; require (proposal[id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached. //Collect state data into memory for calculating prices: uint current_total_dai_sold = proposal[id].side[0].total_dai_traded; uint previous_total_dai_bought = proposal[pa_proposal_id].side[1].total_dai_traded; uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded; uint proposal_amount = proposal[id].amount; uint accept_current_p_amount; uint accept_previous_p_amount; //Calculate where attacker's capital will be spent for accept case and reject case: if (current_total_dai_sold < add(previous_total_dai_bought, proposal_amount)){ accept_current_p_amount = proposal_amount; //accept_previous_p_amount = 0 by default. } else{ //accept_current_p_amount = 0 by default. accept_previous_p_amount = proposal_amount; } //Attacker aims to attack at weakest point. The assumed ratio of z_a_p to y_a_p determines where attack is spending capital i.e. where they are attacking. So the attacker will aim to spend the most where the amount of dai is lowest, since this will have the greatest effect on price. Or in other words we want to know the minimum of the minimum prices. uint accept_price = wmul(wdiv(sub(current_total_dai_sold, accept_current_p_amount), current_total_tokens_bought), wdiv(proposal[pa_proposal_id].side[1].total_tokens_traded, add(accept_previous_p_amount, previous_total_dai_bought))); //Minimum non-manipulated price. if (accept_price > WAD){ //If proposal accepted: (change to require later) proposal[id].status = 2; ERC20Interface.transfer(proposal[id].beneficiary, proposal[id].amount); pa_proposal_id = running_proposal_id; running_proposal_id = 0; _supply = sub(add(_supply, proposal[id].side[0].total_tokens_traded), proposal[id].side[1].total_tokens_traded); net_dai_balance = sub(add(net_dai_balance, current_total_dai_sold), add(wmul(990000000000000000, proposal_amount), proposal[id].side[1].total_dai_traded)); //Update net_dai_balance } emit AcceptAttempt (accept_price, wdiv(current_total_dai_sold, current_total_tokens_bought), wdiv(proposal[id].side[1].total_dai_traded, proposal[id].side[1].total_tokens_traded)); } function reject_prop_spread() external { uint id = running_proposal_id; require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal. uint recent_buy_price = proposal[id].side[0].tranche[proposal[id].side[0].current_tranche_size].price; //Price of current tranche. uint recent_sell_price = proposal[id].side[1].tranche[proposal[id].side[1].current_tranche_size].price; if (recent_buy_price == 0) { //Checks whether current tranche has closed. If not then latest price is calculated. recent_buy_price = calculate_price(0, now); } if (recent_sell_price == 0) { recent_sell_price = calculate_price(1, now); } uint spread = wmul(recent_buy_price, recent_sell_price); //Spread based on current tranche using auction prices that have not finished when necessary. You cannot manipulate spread to be larger so naive price is used. if (spread > proposal[pa_proposal_id].next_reject_spread_threshold){ proposal[id].status = 3; running_proposal_id = 0; } emit RejectSpreadAttempt(spread); } function reject_prop_time() external { uint id = running_proposal_id; require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal. require (now - proposal[id].proposal_start > proposal[id].prop_period, "Still has time."); proposal[id].status = 3; running_proposal_id = 0; emit TimeRejected(); } function accept_reset() external { uint id = running_proposal_id; uint current_total_dai_bought = proposal[id].side[1].total_dai_traded; uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded; uint current_total_tokens_sold = proposal[id].side[1].total_tokens_traded; require (current_total_dai_bought >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached. require (proposal[id].status == 4, "Not reset proposal."); //Check that this is a reset proposal rather than just any standard proposal. proposal[id].status = 2; //Proposal accepted pa_proposal_id = running_proposal_id; running_proposal_id = 0; _supply = sub(add(_supply, current_total_tokens_bought), current_total_tokens_sold); //Update supply. //Net_dai_balance remains the same since equal dai is traded on both sides and proposal.amount = 0. emit ResetAccepted(wdiv(proposal[id].side[0].total_dai_traded, current_total_tokens_bought), wdiv(current_total_dai_bought, current_total_tokens_sold)); } function redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){ require (proposal[_id].status == _status, "incorrect status"); amount = proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender]; proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = 0; //Set balance to zero. } function redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) { require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Other side never finished."); //Make sure that both sides of the tranche finished. amount = wmul(redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function. } function buy_redeem(uint _id, uint _tranche_size) external { mint(redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens. } function sell_redeem(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai. } function buy_refund_reject(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai. } function sell_refund_reject(uint _id, uint _tranche_size) external { mint(redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens. } function buy_refund_accept(uint _id, uint _tranche_size) external { require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished. ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 2)); //User paid with dai so they get back dai. } function sell_refund_accept(uint _id, uint _tranche_size) external { require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished. mint(redeem_refund_common(_id, _tranche_size, 1, 2));//User paid with tokens so they get back tokens. } //Functions for redeeming final trades: function final_redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){ require (proposal[_id].status == _status, "Incorrect status"); require (proposal[_id].side[_side].tranche[_tranche_size].final_trade_address == msg.sender, "Wasn't you."); amount = proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount; proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = 0; //Set balance to zero. } function final_redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) { require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Try refund."); //Make sure that both sides of the tranche finished. amount = wmul(final_redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].final_trade_price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function. } function final_buy_redeem(uint _id, uint _tranche_size) external { mint(final_redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens. } function final_sell_redeem(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, final_redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai. } function final_buy_refund_reject(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, final_redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai. } function final_sell_refund_reject(uint _id, uint _tranche_size) external { mint(final_redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens. } constructor(uint _init_price, ERC20 _ERC20Interface) public { //(WAD) _init_price is defined as dai_amount/token_amount. _supply is defined in the TokenBase constructor. ERC20Interface = _ERC20Interface; //fakeDai contract. Use checksum version of address. //Genesis proposal which will be used by first proposal. proposal[0].status = 2; proposal[0].beneficiary = address(this); //Because the submission of first proposal would break the erc20 transfer function if address(0) is used, therefore, we use this address. proposal[0].amount = 0; //For first proposal submission, 0/100 will be returned to contract address. proposal[0].prop_period = 1; proposal[0].next_min_prop_period = 1; proposal[0].next_init_tranche_size = wmul(_supply, _init_price)/100; proposal[0].next_init_price_data = [wdiv(WAD, wmul(40*WAD, _init_price)), wdiv(_init_price, 2*WAD) , 1003858241594480000, 10**17]; //Price here is defined as [amount received by user after proposal]/[amount given by user before]. //Price should double every 30 mins. Buy price starts above sell price at max potential price - vice versa for sell price. p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD)). e = 2**(1/180). Value of f defines 10 seconds as 1 int. proposal[0].next_reject_spread_threshold = 7 * WAD; proposal[0].next_minimum_sell_volume = wmul(_supply, _init_price)/100; //(10 ** -6) dai minimum sell volume. proposal[0].reset_time_period = 10; proposal[0].proposal_start = uint40(now); //Genesis trade values: proposal[0].side[0].total_dai_traded = wmul(_supply, _init_price); //0.001 dai initial market cap. (10 ** -6) dai initial price. proposal[0].side[1].total_dai_traded = wmul(_supply, _init_price); proposal[0].side[0].total_tokens_traded = _supply; proposal[0].side[1].total_tokens_traded = _supply; } //price = total_dai_traded/_supply } /// erc20.sol -- API for the ERC20 token standard // See <https://github.com/ethereum/EIPs/issues/20>. // This file likely does not meet the threshold of originality // required for copyright to apply. As a result, this is free and // unencumbered software belonging to the public domain. pragma solidity >0.4.20; contract ERC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); } contract ERC20 is ERC20Events { function totalSupply() external view returns (uint); function balanceOf(address guy) external view returns (uint); function allowance(address src, address guy) external view returns (uint); function approve(address guy, uint wad) external returns (bool); function transfer(address dst, uint wad) external returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } pragma solidity ^0.5.0; contract onchain_gov_events{ event NewSubmission (uint40 indexed id, address beneficiary, uint amount, uint next_init_tranche_size, uint[4] next_init_price_data, uint next_reject_spread_threshold, uint next_minimum_sell_volume, uint40 prop_period, uint40 next_min_prop_period, uint40 reset_time_period); event InitProposal (uint40 id, uint init_buy_tranche, uint init_sell_tranche); event Reset(uint id); event NewTrancheTotal (uint side, uint current_tranche_t); //Measured in terms of given token. event TrancheClose (uint side, uint current_tranche_size, uint this_tranche_tokens_total); //Indicates tranche that closed and whether both or just one side have now closed. event AcceptAttempt (uint accept_price, uint average_buy_dai_price, uint average_sell_dai_price); // event RejectSpreadAttempt(uint spread); event TimeRejected(); event ResetAccepted(uint average_buy_dai_price, uint average_sell_dai_price); } interface IOnchain_gov{ function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint); function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint); function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool); function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount) external returns (bool); function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool); function calculate_price(uint _side, uint _now) external view returns (uint p); function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external; function init_proposal(uint40 _id) external; function reset() external; function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external; function sell(uint _id, uint _input_token_amount, uint _tranche_size) external; function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external; function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external; function accept_prop() external; function reject_prop_spread() external; function reject_prop_time() external; function accept_reset() external; function buy_redeem(uint _id, uint _tranche_size) external; function sell_redeem(uint _id, uint _tranche_size) external; function buy_refund_reject(uint _id, uint _tranche_size) external; function sell_refund_reject(uint _id, uint _tranche_size) external; function buy_refund_accept(uint _id, uint _tranche_size) external; function sell_refund_accept(uint _id, uint _tranche_size) external; function final_buy_redeem(uint _id, uint _tranche_size) external; function final_sell_redeem(uint _id, uint _tranche_size) external; function final_buy_refund_reject(uint _id, uint _tranche_size) external; function final_sell_refund_reject(uint _id, uint _tranche_size) external; } //27 functions /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >0.4.13; contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } uint constant WAD = 10 ** 18; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function wpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : WAD; for (n /= 2; n != 0; n /= 2) { x = wmul(x, x); if (n % 2 != 0) { z = wmul(z, x); } } } } // Copyright (C) 2020 Benjamin M J D Wang // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.5.0; import "base.sol"; contract proposal_tokens is TokenBase(0) { //Proposal mappings mapping (uint => Proposal) internal proposal; //proposal id is taken from nonce. struct Proposal { //Records all data that is submitted during proposal submission. address beneficiary; uint amount; //(WAD) uint next_init_tranche_size; //(WAD) uint[4] next_init_price_data; //Array of data for next proposal [initial buy price (WAD), initial sell price (WAD), base (WAD), exponent factor (int)] uint next_reject_spread_threshold; //(WAD) uint next_minimum_sell_volume; //(WAD) uint8 status; //0 = not submitted or not ongoing, 1 = ongoing, 2 = accepted, 3 = rejected, 4 = ongoing reset proposal. uint40 prop_period; //(int) How long users have to prop before prop rejected. uint40 next_min_prop_period; //(int) Minimum prop period for the next proposal. uint40 reset_time_period; //(int) Time period necessary for proposal to be reset. uint40 proposal_start; //(int) This is to provide a time limit for the length of proposals. mapping (uint => Side) side; //Each side of proposal } struct Side { //Current tranche data for this interval. uint current_tranche_total; //This is in units of given tokens rather than only dai tokens: dai for buying, proposal token for selling. For selling, total equivalent dai tokens is calculated within the function. uint total_dai_traded; //Used for calculating acceptance/rejection thresholds. uint total_tokens_traded; //Used for calculating acceptance/rejection thresholds. uint current_tranche_size; //(WAD) This is maximum amount or equivalent maximum amount of dai tokens the tranche can be. mapping (uint => Tranche) tranche; //Data for each tranche that must be recorded. Size of tranche will be the uint tranche id. } struct Tranche { uint price; //(WAD) Final tranche price for each tranche. Price is defined as if the user is selling their respective token types to the proposal so price increases over time to incentivise selling. Buy price is price of dai in proposal tokens where sell price is the price in dai. uint final_trade_price; uint recent_trade_time; uint final_trade_amount; address final_trade_address; mapping (address => uint) balance; //(WAD) mapping (address => mapping (address => uint256)) approvals; } uint40 internal nonce; // Nonce for submitted proposals that have a higher param regardless of whether they are chosen or not. Will also be used for chosen proposals. uint40 public top_proposal_id; //Id of current top proposal. uint40 public running_proposal_id; //id of the proposal that has been initialised. uint40 public pa_proposal_id; //Previously accepted proposal id. uint40 current_tranche_start; //(int) uint public top_param; //(WAD) uint internal lct_tokens_traded; //Records the total tokens traded for the tranche on the first side to close. This means that this calculation won't need to be repeated when both sides close. uint internal net_dai_balance; //The contract's dai balance as if all redemptions and refunds are collected in full, re-calculated at the end of every accepted proposal. function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint) { return proposal[_id].side[_side].tranche[_tranche].balance[_account]; } function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint) { return proposal[_id].side[_side].tranche[_tranche].approvals[_from][_guy]; } function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool) { return proposal_transfer_from(_id, _side, _tranche, msg.sender, _to, _amount); } event ProposalTokenTransfer(address from, address to, uint amount); function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount) public returns (bool) { if (_from != msg.sender) { proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender] = sub(proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender], _amount); //Revert if funds insufficient. } proposal[_id].side[_side].tranche[_tranche].balance[_from] = sub(proposal[_id].side[_side].tranche[_tranche].balance[_from], _amount); proposal[_id].side[_side].tranche[_tranche].balance[_to] = add(proposal[_id].side[_side].tranche[_tranche].balance[_to], _amount); emit ProposalTokenTransfer(_from, _to, _amount); return true; } event ProposalTokenApproval(address account, address guy, uint amount); function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool) { proposal[_id].side[_side].tranche[_tranche].approvals[msg.sender][_guy] = _amount; emit ProposalTokenApproval(msg.sender, _guy, _amount); return true; } } /// base.sol -- basic ERC20 implementation // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >=0.4.23; import "erc20.sol"; import "math.sol"; contract TokenBase is ERC20, DSMath { uint256 _supply; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _approvals; constructor(uint supply) public { _balances[msg.sender] = supply; _supply = supply; } function totalSupply() external view returns (uint) { return _supply; } function balanceOf(address src) external view returns (uint) { return _balances[src]; } function allowance(address src, address guy) external view returns (uint) { return _approvals[src][guy]; } function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { if (src != msg.sender) { _approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad); //Revert if funds insufficient. } _balances[src] = sub(_balances[src], wad); _balances[dst] = add(_balances[dst], wad); emit Transfer(src, dst, wad); return true; } function approve(address guy, uint wad) external returns (bool) { _approvals[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } event Mint(address guy, uint wad); event Burn(address guy, uint wad); function mint(uint wad) internal { //Note: _supply constant _balances[msg.sender] = add(_balances[msg.sender], wad); emit Mint(msg.sender, wad); } function burn(uint wad) internal { //Note: _supply constant _balances[msg.sender] = sub(_balances[msg.sender], wad); //Revert if funds insufficient. emit Burn(msg.sender, wad); } } // Copyright (C) 2020 Benjamin M J D Wang // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.5.0; import "gov_interface_v2.sol"; //Import governance contract interface. import "proposal_tokens_v3.sol"; //proposal tokens data structure and transfer functions. contract onchain_gov_BMJDW2020 is IOnchain_gov, proposal_tokens, onchain_gov_events{ ERC20 public ERC20Interface; function calculate_price(uint _side, uint _now) public view returns (uint p) { //Function could also be internal if users can calculate price themselves easily. uint[4] memory price_data = proposal[pa_proposal_id].next_init_price_data; p = wmul(price_data[_side], wpow(price_data[2], mul(price_data[3], sub(_now, current_tranche_start))/WAD)); //(WAD) //p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD)); /** p = WAD p1 = WAD e = WAD f = int now = int start = int */ } function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external { uint param = wdiv(_amount, mul(_next_min_prop_period, _prop_period)); //_next_min_prop_period is purely an anti-spam prevention to stop spammers submitting proposals with very small amounts. Assume WAD since _next_min_prop_period * _prop_period may result in large number. require(param > top_param, "param < top_param"); require(_prop_period > proposal[pa_proposal_id].next_min_prop_period, "prop_period < minimum"); //check that voting period is greater than the next_min_prop_period of the last accepted proposal. top_param = param; //Sets current top param to that of the resently submitted proposal. ERC20Interface.transferFrom(msg.sender, address(this), _amount / 100);//Takes proposer's deposit in dai. This must throw an error and revert if the user does not have enough funds available. ERC20Interface.transfer(proposal[top_proposal_id].beneficiary, proposal[top_proposal_id].amount / 100); ////Pays back the deposit to the old top proposer in dai. uint id = ++nonce; //Implicit conversion to uint256 top_proposal_id = uint40(id); //set top proposal id and is used as id for recording data. //Store all new proposal data: proposal[id].beneficiary = msg.sender; proposal[id].amount = _amount; proposal[id].next_init_tranche_size = _next_init_tranche_size; proposal[id].next_init_price_data = _next_init_price_data; proposal[id].next_reject_spread_threshold = _next_reject_spread_threshold; proposal[id].next_minimum_sell_volume = _next_minimum_sell_volume; proposal[id].prop_period = _prop_period; proposal[id].next_min_prop_period = _next_min_prop_period; proposal[id].reset_time_period = _reset_time_period; emit NewSubmission(uint40(id), msg.sender, _amount, _next_init_tranche_size, _next_init_price_data, _next_reject_spread_threshold, _next_minimum_sell_volume, _prop_period, _next_min_prop_period, _reset_time_period); } function init_proposal(uint40 _id) external { //'sell' and 'buy' indicate sell and buy side from the user perspective in the context of governance tokens even though it is in reference to dai. require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished. /** When proposal has ended and was accepted: pa_proposal_id = running_proposal_id running_proposal_id = 0 When proposal has ended and was rejected: pa_proposal_id remains the same. running_proposal_id = 0 When initialised: running_proposal_id = top_proposal_id top_proposal_id = 1; proposal status = 1; */ require (_id == top_proposal_id, "Wrong id."); //Require correct proposal to be chosen. require (_id != 0, "_id != 0"); //Cannot initialise the genesis proposal. running_proposal_id = _id; //Update running proposal id. top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposa_id is necessary in the submission function above for the first submission after each proposal. proposal[_id].status = 1; //Set proposal status to 'ongoing'. uint init_sell_size = proposal[pa_proposal_id].next_init_tranche_size; //Init sell tranche size. proposal[_id].side[1].current_tranche_size = init_sell_size; uint minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume; uint dai_out = add(wmul(990000000000000000, proposal[_id].amount), minimum_sell_volume); uint net_balance = net_dai_balance; uint init_buy_size; //Make sure that the contract is always running a positive net dai balance: if (dai_out > net_balance){ init_buy_size = wmul(wdiv(init_sell_size, minimum_sell_volume), sub(dai_out, net_balance)); } else{ init_buy_size = init_sell_size; } proposal[_id].side[0].current_tranche_size = init_buy_size; current_tranche_start = uint40(now); proposal[_id].proposal_start = uint40(now); top_param = 0; //reset top param. emit InitProposal (_id, init_buy_size, init_sell_size); } function reset() external{ require (uint40(now) - proposal[pa_proposal_id].proposal_start > proposal[pa_proposal_id].reset_time_period, "Reset time not elapsed."); //Tests amount of time since last proposal passed. uint id = ++nonce; //Set proposal data: proposal[id].beneficiary = msg.sender; proposal[id].next_min_prop_period = proposal[pa_proposal_id].next_min_prop_period; proposal[id].next_init_tranche_size = proposal[pa_proposal_id].next_init_tranche_size; proposal[id].next_init_price_data = proposal[pa_proposal_id].next_init_price_data; proposal[id].next_reject_spread_threshold = proposal[pa_proposal_id].next_reject_spread_threshold; uint next_minimum_sell_volume = proposal[pa_proposal_id].next_minimum_sell_volume; proposal[id].next_minimum_sell_volume = next_minimum_sell_volume; proposal[id].reset_time_period = proposal[pa_proposal_id].reset_time_period; require (running_proposal_id == 0, "Proposal still running."); //Makes sure previous proposal has finished. running_proposal_id = uint40(id); //Update running proposal id. top_proposal_id = 0; //Set top proposal to the genesis proposal. This is because some top_proposal_id is necessary in the submission function above for the first submission after each proposal. proposal[id].status = 4; //Set proposal status to 'ongoing reset proposal'. proposal[id].side[0].current_tranche_size = next_minimum_sell_volume; proposal[id].side[1].current_tranche_size = next_minimum_sell_volume; //Set as size of tranche as minimum sell volume. current_tranche_start = uint40(now); proposal[id].proposal_start = uint40(now); top_param = 0; //reset top param. emit Reset(id); } function all_trades_common(uint _id, uint _side, uint _tranche_size) internal view returns (uint current_tranche_t) { require (_id == running_proposal_id, "Wrong id."); //User can only trade on currently running proposal. require (proposal[_id].side[_side].current_tranche_size == _tranche_size, "Wrong tranche size."); //Make sure the user's selected tranche size is the current tranche size. Without this they may choose arbitrary tranches and then loose tokens. require (proposal[_id].side[_side].tranche[_tranche_size].price == 0, "Tranche already closed."); //Check tranche is still open. current_tranche_t = proposal[_id].side[_side].current_tranche_total; } function buy_sell_common(uint _id, uint _input_amount, uint _side, uint _tranche_size, uint _current_dai_price) internal { uint current_tranche_t = all_trades_common(_id, _side, _tranche_size); require (wmul(add(_input_amount, current_tranche_t), _current_dai_price) < _tranche_size, "Try closing tranche."); //Makes sure users cannot send tokens beyond or even up to the current tranche size since this is for the tranche close function. proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = add(proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender], _input_amount); //Record proposal balance. proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time = sub(now, current_tranche_start); //Set time of most recent trade so 2nd to last trade time can be recorded. Offset by current_tranche_start to account for zero initial value. proposal[_id].side[_side].current_tranche_total = add(current_tranche_t, _input_amount); //Update current_tranche_total. emit NewTrancheTotal (_side, current_tranche_t + _input_amount); } function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external { //Set correct amount of dai buy_sell_common(_id, _input_dai_amount, 0, _tranche_size, WAD); //For buying _dai_amount = _input_dai_amount. Dai price = 1.0. ERC20Interface.transferFrom(msg.sender, address(this), _input_dai_amount); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction. } function sell(uint _id, uint _input_token_amount, uint _tranche_size) external { //Set correct amount of dai buy_sell_common(_id, _input_token_amount, 1, _tranche_size, calculate_price(1, now)); //For selling, the current dai amount must be used based on current price. burn(_input_token_amount); //Remove user governance tokens. SafeMath should revert with insufficient funds. } function close_buy_sell_common_1(uint _id, uint _side, uint _tranche_size) internal returns(uint price, uint final_trade_price, uint current_tranche_t) { current_tranche_t = all_trades_common(_id, _side, _tranche_size); price = calculate_price(_side, add(proposal[_id].side[_side].tranche[_tranche_size].recent_trade_time, current_tranche_start)); //(WAD) Sets price for all traders. final_trade_price = calculate_price(_side, now); proposal[_id].side[_side].tranche[_tranche_size].price = price; //(WAD) Sets price for all traders. proposal[_id].side[_side].tranche[_tranche_size].final_trade_price = final_trade_price; //(WAD) Sets price for only the final trader. proposal[_id].side[_side].tranche[_tranche_size].final_trade_address = msg.sender; //Record address of final trade. proposal[_id].side[_side].current_tranche_total = 0; //Reset current_tranche_total to zero. } function close_buy_sell_common_2(uint _id, uint _balance_amount, uint _side, uint _tranche_size, uint _input_dai_amount, uint _current_tranche_t_dai, uint _this_tranche_tokens_total) internal { require (add(_input_dai_amount, _current_tranche_t_dai) >= _tranche_size, "Not enough to close."); //Check that the user has provided enough dai or equivalent to close the tranche. proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = _balance_amount; //Record final trade amount. if (proposal[_id].side[(_side+1)%2].tranche[proposal[_id].side[(_side+1)%2].current_tranche_size].price != 0){ //Check whether tranche for other side has closed. current_tranche_start = uint40(now); //Reset timer for next tranche. proposal[_id].side[_side].total_tokens_traded = add(proposal[_id].side[_side].total_tokens_traded, _this_tranche_tokens_total); proposal[_id].side[(_side+1)%2].total_tokens_traded = add(proposal[_id].side[(_side+1)%2].total_tokens_traded, lct_tokens_traded); //Sets total tokens traded on each side now that tranches on both sides have closed (using lct_tokens_traded which was recorded when the other side closed.) proposal[_id].side[_side].total_dai_traded = add(proposal[_id].side[_side].total_dai_traded, _tranche_size); proposal[_id].side[(_side+1)%2].total_dai_traded = add(proposal[_id].side[(_side+1)%2].total_dai_traded, proposal[_id].side[(_side+1)%2].current_tranche_size); //Add total dai traded in tranche to total_dai_traded. //Add total dai traded in tranche to total_dai_traded. if (proposal[_id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume) { //if sell volume has reached the minimum and reset has not already happened: then reset the tranche sizes on both sides to the same value. uint new_size = mul(_tranche_size, 2); proposal[_id].side[0].current_tranche_size = new_size; proposal[_id].side[1].current_tranche_size = new_size; //Set both tranche sizes to the same size. } else { proposal[_id].side[_side].current_tranche_size = mul(_tranche_size, 2); proposal[_id].side[(_side+1)%2].current_tranche_size = mul(proposal[_id].side[(_side+1)%2].current_tranche_size, 2); //Double the current tranche sizes. } } else{ lct_tokens_traded = _this_tranche_tokens_total; //Records last closed tranche tokens traded total for when both tranches close. } emit TrancheClose (_side, _tranche_size, _this_tranche_tokens_total); //Users must check when both sides have closed and then calculate total traded themselves by summing the TrancheClose data. } function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external { (uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 0, _tranche_size); uint dai_amount_left = sub(_tranche_size, current_tranche_t); //Calculates new amount of dai for user to give. uint this_tranche_tokens_total = add(wmul(current_tranche_t,price), wmul(dai_amount_left, final_trade_price)); //Update total_tokens_traded close_buy_sell_common_2(_id, dai_amount_left, 0, _tranche_size, _input_dai_amount, current_tranche_t, this_tranche_tokens_total); ERC20Interface.transferFrom(msg.sender, address(this), dai_amount_left); //Take dai from user using call to dai contract. User must approve contract address and amount before transaction. } function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external { (uint price, uint final_trade_price, uint current_tranche_t) = close_buy_sell_common_1(_id, 1, _tranche_size); uint dai_amount_left = sub(_tranche_size, wmul(current_tranche_t, price)); //Calculates dai_amount_left in tranche which is based on the price the other sellers will pay, not the current price. uint token_equiv_left = wdiv(dai_amount_left, final_trade_price); //Calculate amount of tokens to give user based on dai amount left. uint equiv_input_dai_amount = wmul(_input_token_amount, final_trade_price); //Equivalent amount of dai at current prices based on the user amount of tokens. uint this_tranche_tokens_total = add(current_tranche_t, token_equiv_left); //Update total_tokens_traded close_buy_sell_common_2(_id, token_equiv_left, 1, _tranche_size, equiv_input_dai_amount, wmul(current_tranche_t, price), this_tranche_tokens_total); burn(token_equiv_left); //Remove user governance tokens. SafeMath should revert with insufficient funds. } function accept_prop() external { uint id = running_proposal_id; require (proposal[id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached. //Collect state data into memory for calculating prices: uint current_total_dai_sold = proposal[id].side[0].total_dai_traded; uint previous_total_dai_bought = proposal[pa_proposal_id].side[1].total_dai_traded; uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded; uint proposal_amount = proposal[id].amount; uint accept_current_p_amount; uint accept_previous_p_amount; //Calculate where attacker's capital will be spent for accept case and reject case: if (current_total_dai_sold < add(previous_total_dai_bought, proposal_amount)){ accept_current_p_amount = proposal_amount; //accept_previous_p_amount = 0 by default. } else{ //accept_current_p_amount = 0 by default. accept_previous_p_amount = proposal_amount; } //Attacker aims to attack at weakest point. The assumed ratio of z_a_p to y_a_p determines where attack is spending capital i.e. where they are attacking. So the attacker will aim to spend the most where the amount of dai is lowest, since this will have the greatest effect on price. Or in other words we want to know the minimum of the minimum prices. uint accept_price = wmul(wdiv(sub(current_total_dai_sold, accept_current_p_amount), current_total_tokens_bought), wdiv(proposal[pa_proposal_id].side[1].total_tokens_traded, add(accept_previous_p_amount, previous_total_dai_bought))); //Minimum non-manipulated price. if (accept_price > WAD){ //If proposal accepted: (change to require later) proposal[id].status = 2; ERC20Interface.transfer(proposal[id].beneficiary, proposal[id].amount); pa_proposal_id = running_proposal_id; running_proposal_id = 0; _supply = sub(add(_supply, proposal[id].side[0].total_tokens_traded), proposal[id].side[1].total_tokens_traded); net_dai_balance = sub(add(net_dai_balance, current_total_dai_sold), add(wmul(990000000000000000, proposal_amount), proposal[id].side[1].total_dai_traded)); //Update net_dai_balance } emit AcceptAttempt (accept_price, wdiv(current_total_dai_sold, current_total_tokens_bought), wdiv(proposal[id].side[1].total_dai_traded, proposal[id].side[1].total_tokens_traded)); } function reject_prop_spread() external { uint id = running_proposal_id; require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal. uint recent_buy_price = proposal[id].side[0].tranche[proposal[id].side[0].current_tranche_size].price; //Price of current tranche. uint recent_sell_price = proposal[id].side[1].tranche[proposal[id].side[1].current_tranche_size].price; if (recent_buy_price == 0) { //Checks whether current tranche has closed. If not then latest price is calculated. recent_buy_price = calculate_price(0, now); } if (recent_sell_price == 0) { recent_sell_price = calculate_price(1, now); } uint spread = wmul(recent_buy_price, recent_sell_price); //Spread based on current tranche using auction prices that have not finished when necessary. You cannot manipulate spread to be larger so naive price is used. if (spread > proposal[pa_proposal_id].next_reject_spread_threshold){ proposal[id].status = 3; running_proposal_id = 0; } emit RejectSpreadAttempt(spread); } function reject_prop_time() external { uint id = running_proposal_id; require (proposal[id].status == 1, "Prop status is incorrect."); //Make sure it is not a reset proposal. require (now - proposal[id].proposal_start > proposal[id].prop_period, "Still has time."); proposal[id].status = 3; running_proposal_id = 0; emit TimeRejected(); } function accept_reset() external { uint id = running_proposal_id; uint current_total_dai_bought = proposal[id].side[1].total_dai_traded; uint current_total_tokens_bought = proposal[id].side[0].total_tokens_traded; uint current_total_tokens_sold = proposal[id].side[1].total_tokens_traded; require (current_total_dai_bought >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum"); //Check that minimum sell volume has been reached. require (proposal[id].status == 4, "Not reset proposal."); //Check that this is a reset proposal rather than just any standard proposal. proposal[id].status = 2; //Proposal accepted pa_proposal_id = running_proposal_id; running_proposal_id = 0; _supply = sub(add(_supply, current_total_tokens_bought), current_total_tokens_sold); //Update supply. //Net_dai_balance remains the same since equal dai is traded on both sides and proposal.amount = 0. emit ResetAccepted(wdiv(proposal[id].side[0].total_dai_traded, current_total_tokens_bought), wdiv(current_total_dai_bought, current_total_tokens_sold)); } function redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){ require (proposal[_id].status == _status, "incorrect status"); amount = proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender]; proposal[_id].side[_side].tranche[_tranche_size].balance[msg.sender] = 0; //Set balance to zero. } function redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) { require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Other side never finished."); //Make sure that both sides of the tranche finished. amount = wmul(redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function. } function buy_redeem(uint _id, uint _tranche_size) external { mint(redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens. } function sell_redeem(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai. } function buy_refund_reject(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai. } function sell_refund_reject(uint _id, uint _tranche_size) external { mint(redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens. } function buy_refund_accept(uint _id, uint _tranche_size) external { require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished. ERC20Interface.transfer(msg.sender, redeem_refund_common(_id, _tranche_size, 0, 2)); //User paid with dai so they get back dai. } function sell_refund_accept(uint _id, uint _tranche_size) external { require (proposal[_id].side[0].tranche[_tranche_size].price == 0 || proposal[_id].side[1].tranche[_tranche_size].price == 0, "Try redeem"); //One of tranches is unfinished. mint(redeem_refund_common(_id, _tranche_size, 1, 2));//User paid with tokens so they get back tokens. } //Functions for redeeming final trades: function final_redeem_refund_common(uint _id, uint _tranche_size, uint _side, uint8 _status) internal returns (uint amount){ require (proposal[_id].status == _status, "Incorrect status"); require (proposal[_id].side[_side].tranche[_tranche_size].final_trade_address == msg.sender, "Wasn't you."); amount = proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount; proposal[_id].side[_side].tranche[_tranche_size].final_trade_amount = 0; //Set balance to zero. } function final_redeem_common(uint _id, uint _tranche_size, uint _side) internal returns (uint amount) { require (proposal[_id].side[0].tranche[_tranche_size].price != 0 && proposal[_id].side[1].tranche[_tranche_size].price != 0, "Try refund."); //Make sure that both sides of the tranche finished. amount = wmul(final_redeem_refund_common(_id, _tranche_size, _side, 2), proposal[_id].side[_side].tranche[_tranche_size].final_trade_price); //Set 'amount' to balance multiplied by price since user just gives the amount of tokens that they are sending in the prop function. } function final_buy_redeem(uint _id, uint _tranche_size) external { mint(final_redeem_common(_id, _tranche_size, 0)); //User paid with dai so they get back tokens. } function final_sell_redeem(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, final_redeem_common(_id, _tranche_size, 1)); //User paid with tokens so they get back dai. } function final_buy_refund_reject(uint _id, uint _tranche_size) external { ERC20Interface.transfer(msg.sender, final_redeem_refund_common(_id, _tranche_size, 0, 3)); //User paid with dai so they get back dai. } function final_sell_refund_reject(uint _id, uint _tranche_size) external { mint(final_redeem_refund_common(_id, _tranche_size, 1, 3)); //User paid with tokens so they get back tokens. } constructor(uint _init_price, ERC20 _ERC20Interface) public { //(WAD) _init_price is defined as dai_amount/token_amount. _supply is defined in the TokenBase constructor. ERC20Interface = _ERC20Interface; //fakeDai contract. Use checksum version of address. //Genesis proposal which will be used by first proposal. proposal[0].status = 2; proposal[0].beneficiary = address(this); //Because the submission of first proposal would break the erc20 transfer function if address(0) is used, therefore, we use this address. proposal[0].amount = 0; //For first proposal submission, 0/100 will be returned to contract address. proposal[0].prop_period = 1; proposal[0].next_min_prop_period = 1; proposal[0].next_init_tranche_size = wmul(_supply, _init_price)/100; proposal[0].next_init_price_data = [wdiv(WAD, wmul(40*WAD, _init_price)), wdiv(_init_price, 2*WAD) , 1003858241594480000, 10**17]; //Price here is defined as [amount received by user after proposal]/[amount given by user before]. //Price should double every 30 mins. Buy price starts above sell price at max potential price - vice versa for sell price. p = wmul(_p1, rpow(_e, mul(_f, sub(_now, _start))/ WAD)). e = 2**(1/180). Value of f defines 10 seconds as 1 int. proposal[0].next_reject_spread_threshold = 7 * WAD; proposal[0].next_minimum_sell_volume = wmul(_supply, _init_price)/100; //(10 ** -6) dai minimum sell volume. proposal[0].reset_time_period = 10; proposal[0].proposal_start = uint40(now); //Genesis trade values: proposal[0].side[0].total_dai_traded = wmul(_supply, _init_price); //0.001 dai initial market cap. (10 ** -6) dai initial price. proposal[0].side[1].total_dai_traded = wmul(_supply, _init_price); proposal[0].side[0].total_tokens_traded = _supply; proposal[0].side[1].total_tokens_traded = _supply; } //price = total_dai_traded/_supply } /// erc20.sol -- API for the ERC20 token standard // See <https://github.com/ethereum/EIPs/issues/20>. // This file likely does not meet the threshold of originality // required for copyright to apply. As a result, this is free and // unencumbered software belonging to the public domain. pragma solidity >0.4.20; contract ERC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); } contract ERC20 is ERC20Events { function totalSupply() external view returns (uint); function balanceOf(address guy) external view returns (uint); function allowance(address src, address guy) external view returns (uint); function approve(address guy, uint wad) external returns (bool); function transfer(address dst, uint wad) external returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } pragma solidity ^0.5.0; contract onchain_gov_events{ event NewSubmission (uint40 indexed id, address beneficiary, uint amount, uint next_init_tranche_size, uint[4] next_init_price_data, uint next_reject_spread_threshold, uint next_minimum_sell_volume, uint40 prop_period, uint40 next_min_prop_period, uint40 reset_time_period); event InitProposal (uint40 id, uint init_buy_tranche, uint init_sell_tranche); event Reset(uint id); event NewTrancheTotal (uint side, uint current_tranche_t); //Measured in terms of given token. event TrancheClose (uint side, uint current_tranche_size, uint this_tranche_tokens_total); //Indicates tranche that closed and whether both or just one side have now closed. event AcceptAttempt (uint accept_price, uint average_buy_dai_price, uint average_sell_dai_price); // event RejectSpreadAttempt(uint spread); event TimeRejected(); event ResetAccepted(uint average_buy_dai_price, uint average_sell_dai_price); } interface IOnchain_gov{ function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint); function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint); function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool); function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount) external returns (bool); function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool); function calculate_price(uint _side, uint _now) external view returns (uint p); function submit_proposal(uint _amount, uint _next_init_tranche_size, uint[4] calldata _next_init_price_data, uint _next_reject_spread_threshold, uint _next_minimum_sell_volume, uint40 _prop_period, uint40 _next_min_prop_period, uint40 _reset_time_period) external; function init_proposal(uint40 _id) external; function reset() external; function buy(uint _id, uint _input_dai_amount, uint _tranche_size) external; function sell(uint _id, uint _input_token_amount, uint _tranche_size) external; function close_tranche_buy(uint _id, uint _input_dai_amount, uint _tranche_size) external; function close_tranche_sell(uint _id, uint _input_token_amount, uint _tranche_size) external; function accept_prop() external; function reject_prop_spread() external; function reject_prop_time() external; function accept_reset() external; function buy_redeem(uint _id, uint _tranche_size) external; function sell_redeem(uint _id, uint _tranche_size) external; function buy_refund_reject(uint _id, uint _tranche_size) external; function sell_refund_reject(uint _id, uint _tranche_size) external; function buy_refund_accept(uint _id, uint _tranche_size) external; function sell_refund_accept(uint _id, uint _tranche_size) external; function final_buy_redeem(uint _id, uint _tranche_size) external; function final_sell_redeem(uint _id, uint _tranche_size) external; function final_buy_refund_reject(uint _id, uint _tranche_size) external; function final_sell_refund_reject(uint _id, uint _tranche_size) external; } //27 functions /// math.sol -- mixin for inline numerical wizardry // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >0.4.13; contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } uint constant WAD = 10 ** 18; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function wpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : WAD; for (n /= 2; n != 0; n /= 2) { x = wmul(x, x); if (n % 2 != 0) { z = wmul(z, x); } } } } // Copyright (C) 2020 Benjamin M J D Wang // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.5.0; import "base.sol"; contract proposal_tokens is TokenBase(0) { //Proposal mappings mapping (uint => Proposal) internal proposal; //proposal id is taken from nonce. struct Proposal { //Records all data that is submitted during proposal submission. address beneficiary; uint amount; //(WAD) uint next_init_tranche_size; //(WAD) uint[4] next_init_price_data; //Array of data for next proposal [initial buy price (WAD), initial sell price (WAD), base (WAD), exponent factor (int)] uint next_reject_spread_threshold; //(WAD) uint next_minimum_sell_volume; //(WAD) uint8 status; //0 = not submitted or not ongoing, 1 = ongoing, 2 = accepted, 3 = rejected, 4 = ongoing reset proposal. uint40 prop_period; //(int) How long users have to prop before prop rejected. uint40 next_min_prop_period; //(int) Minimum prop period for the next proposal. uint40 reset_time_period; //(int) Time period necessary for proposal to be reset. uint40 proposal_start; //(int) This is to provide a time limit for the length of proposals. mapping (uint => Side) side; //Each side of proposal } struct Side { //Current tranche data for this interval. uint current_tranche_total; //This is in units of given tokens rather than only dai tokens: dai for buying, proposal token for selling. For selling, total equivalent dai tokens is calculated within the function. uint total_dai_traded; //Used for calculating acceptance/rejection thresholds. uint total_tokens_traded; //Used for calculating acceptance/rejection thresholds. uint current_tranche_size; //(WAD) This is maximum amount or equivalent maximum amount of dai tokens the tranche can be. mapping (uint => Tranche) tranche; //Data for each tranche that must be recorded. Size of tranche will be the uint tranche id. } struct Tranche { uint price; //(WAD) Final tranche price for each tranche. Price is defined as if the user is selling their respective token types to the proposal so price increases over time to incentivise selling. Buy price is price of dai in proposal tokens where sell price is the price in dai. uint final_trade_price; uint recent_trade_time; uint final_trade_amount; address final_trade_address; mapping (address => uint) balance; //(WAD) mapping (address => mapping (address => uint256)) approvals; } uint40 internal nonce; // Nonce for submitted proposals that have a higher param regardless of whether they are chosen or not. Will also be used for chosen proposals. uint40 public top_proposal_id; //Id of current top proposal. uint40 public running_proposal_id; //id of the proposal that has been initialised. uint40 public pa_proposal_id; //Previously accepted proposal id. uint40 current_tranche_start; //(int) uint public top_param; //(WAD) uint internal lct_tokens_traded; //Records the total tokens traded for the tranche on the first side to close. This means that this calculation won't need to be repeated when both sides close. uint internal net_dai_balance; //The contract's dai balance as if all redemptions and refunds are collected in full, re-calculated at the end of every accepted proposal. function proposal_token_balanceOf(uint40 _id, uint _side, uint _tranche, address _account) external view returns (uint) { return proposal[_id].side[_side].tranche[_tranche].balance[_account]; } function proposal_token_allowance(uint40 _id, uint _side, uint _tranche, address _from, address _guy) external view returns (uint) { return proposal[_id].side[_side].tranche[_tranche].approvals[_from][_guy]; } function proposal_token_transfer(uint40 _id, uint _side, uint _tranche, address _to, uint _amount) external returns (bool) { return proposal_transfer_from(_id, _side, _tranche, msg.sender, _to, _amount); } event ProposalTokenTransfer(address from, address to, uint amount); function proposal_transfer_from(uint40 _id, uint _side, uint _tranche,address _from, address _to, uint _amount) public returns (bool) { if (_from != msg.sender) { proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender] = sub(proposal[_id].side[_side].tranche[_tranche].approvals[_from][msg.sender], _amount); //Revert if funds insufficient. } proposal[_id].side[_side].tranche[_tranche].balance[_from] = sub(proposal[_id].side[_side].tranche[_tranche].balance[_from], _amount); proposal[_id].side[_side].tranche[_tranche].balance[_to] = add(proposal[_id].side[_side].tranche[_tranche].balance[_to], _amount); emit ProposalTokenTransfer(_from, _to, _amount); return true; } event ProposalTokenApproval(address account, address guy, uint amount); function proposal_token_approve(uint40 _id, uint _side, uint _tranche, address _guy, uint _amount) external returns (bool) { proposal[_id].side[_side].tranche[_tranche].approvals[msg.sender][_guy] = _amount; emit ProposalTokenApproval(msg.sender, _guy, _amount); return true; } }
Check that minimum sell volume has been reached.
require (proposal[id].side[1].total_dai_traded >= proposal[pa_proposal_id].next_minimum_sell_volume, "dai sold < minimum");
1,816,029
[ 1, 1564, 716, 5224, 357, 80, 3940, 711, 2118, 8675, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 6528, 261, 685, 8016, 63, 350, 8009, 5564, 63, 21, 8009, 4963, 67, 2414, 77, 67, 2033, 785, 1545, 14708, 63, 8774, 67, 685, 8016, 67, 350, 8009, 4285, 67, 15903, 67, 87, 1165, 67, 9491, 16, 315, 2414, 77, 272, 1673, 411, 5224, 8863, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x864a1CBB53b9Dea3691a6974B456088C2771DcAd/sources/browser/Bar.sol
View function to see the number of blocks remaining until launch on the frontend
function blocksUntilLaunch() public view returns (uint256) { if (block.number >= startBlock) return 0; else return startBlock.sub(block.number); }
4,927,171
[ 1, 1767, 445, 358, 2621, 326, 1300, 434, 4398, 4463, 3180, 8037, 603, 326, 15442, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4398, 9716, 9569, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 2629, 18, 2696, 1545, 787, 1768, 13, 327, 374, 31, 203, 3639, 469, 327, 787, 1768, 18, 1717, 12, 2629, 18, 2696, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x918F65dEF819b0720cf5C0a264603d451F522C2A/sources/ERC20.sol
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide 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, Owned { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name = 'Everlasting Parallel Chain'; string private _symbol = 'ELP'; uint8 private _decimals = 18; } constructor () public { _mint(msg.sender, 10000000*1e18); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _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 burn(address addr, uint256 amount) public virtual ownerOnly returns (bool) { _burn(addr, amount); return true; } 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; } 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 _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) 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); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
3,898,092
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 273, 296, 41, 502, 2722, 310, 20203, 7824, 13506, 203, 565, 533, 3238, 389, 7175, 273, 296, 2247, 52, 13506, 203, 565, 2254, 28, 3238, 389, 31734, 273, 6549, 31, 203, 203, 97, 203, 565, 3885, 1832, 1071, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2130, 11706, 14, 21, 73, 2643, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2 ]
//Address: 0xfd26d4fedea09da1bb2c4e410c747dda72fdb506 //Contract name: VZTPresale //Balance: 0 Ether //Verification Date: 1/19/2018 //Transacion Count: 23 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 * https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract Ownable { address public owner; // Operational owner. address public masterOwner = 0xe4925C73851490401b858B657F26E62e9aD20F66; // for ownership transfer segregation of duty, hard coded to wallet account event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public { require(newOwner != address(0)); require(masterOwner == msg.sender); // only master owner can initiate change to ownership OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * https://github.com/OpenZeppelin/zeppelin-solidity/ */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function cei(uint256 a, uint256 b) internal pure returns (uint256) { return ((a + b - 1) / b) * b; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 * https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** This interfaces will be implemented by different VZT contracts in future*/ interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract VZToken is StandardToken, Ownable { /* metadata */ string public constant name = "VectorZilla Token"; // solium-disable-line uppercase string public constant symbol = "VZT"; // solium-disable-line uppercase string public constant version = "1.0"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase /* all accounts in wei */ uint256 public constant INITIAL_SUPPLY = 100000000 * 10 ** 18; //intial total supply uint256 public constant BURNABLE_UP_TO = 90000000 * 10 ** 18; //burnable up to 90% (90 million) of total supply uint256 public constant VECTORZILLA_RESERVE_VZT = 25000000 * 10 ** 18; //25 million - reserved tokens // Reserved tokens will be sent to this address. this address will be replaced on production: address public constant VECTORZILLA_RESERVE = 0xF63e65c57024886cCa65985ca6E2FB38df95dA11; // - tokenSaleContract receives the whole balance for distribution address public tokenSaleContract; /* Following stuff is to manage regulatory hurdles on who can and cannot use VZT token */ mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); /** Modifiers to be used all over the place **/ modifier onlyOwnerAndContract() { require(msg.sender == owner || msg.sender == tokenSaleContract); _; } modifier onlyWhenValidAddress( address _addr ) { require(_addr != address(0x0)); _; } modifier onlyWhenValidContractAddress(address _addr) { require(_addr != address(0x0)); require(_addr != address(this)); require(isContract(_addr)); _; } modifier onlyWhenBurnable(uint256 _value) { require(totalSupply - _value >= INITIAL_SUPPLY - BURNABLE_UP_TO); _; } modifier onlyWhenNotFrozen(address _addr) { require(!frozenAccount[_addr]); _; } /** End of Modifier Definations */ /** Events */ event Burn(address indexed burner, uint256 value); event Finalized(); //log event whenever withdrawal from this contract address happens event Withdraw(address indexed from, address indexed to, uint256 value); /* Contructor that distributes initial supply between owner and vzt reserve. */ function VZToken(address _owner) public { require(_owner != address(0)); totalSupply = INITIAL_SUPPLY; balances[_owner] = INITIAL_SUPPLY - VECTORZILLA_RESERVE_VZT; //75 millions tokens balances[VECTORZILLA_RESERVE] = VECTORZILLA_RESERVE_VZT; //25 millions owner = _owner; } /* This unnamed function is called whenever the owner send Ether to fund the gas fees and gas reimbursement. */ function () payable public onlyOwner {} /** * @dev transfer `_value` 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 onlyWhenValidAddress(_to) onlyWhenNotFrozen(msg.sender) onlyWhenNotFrozen(_to) returns(bool) { return super.transfer(_to, _value); } /** * @dev Transfer `_value` tokens from one address (`_from`) to another (`_to`) * @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 onlyWhenValidAddress(_to) onlyWhenValidAddress(_from) onlyWhenNotFrozen(_from) onlyWhenNotFrozen(_to) returns(bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Burns a specific (`_value`) amount of tokens. * @param _value uint256 The amount of token to be burned. */ function burn(uint256 _value) public onlyWhenBurnable(_value) onlyWhenNotFrozen(msg.sender) returns (bool) { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0x0), _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public onlyWhenBurnable(_value) onlyWhenNotFrozen(_from) onlyWhenNotFrozen(msg.sender) returns (bool success) { assert(transferFrom( _from, msg.sender, _value )); return burn(_value); } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyWhenValidAddress(_spender) returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Freezes account and disables transfers/burning * This is to manage regulatory hurdlers where contract owner is required to freeze some accounts. */ function freezeAccount(address target, bool freeze) external onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /* Owner withdrawal of an ether deposited from Token ether balance */ function withdrawToOwner(uint256 weiAmt) public onlyOwner { // do not allow zero transfer require(weiAmt > 0); owner.transfer(weiAmt); // signal the event for communication only it is meaningful Withdraw(this, msg.sender, weiAmt); } /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) external onlyOwner { if (_token == 0x0) { owner.transfer(this.balance); return; } StandardToken token = StandardToken(_token); uint balance = token.balanceOf(this); token.transfer(owner, balance); // signal the event for communication only it is meaningful Withdraw(this, owner, balance); } function setTokenSaleContract(address _tokenSaleContract) external onlyWhenValidContractAddress(_tokenSaleContract) onlyOwner { require(_tokenSaleContract != tokenSaleContract); tokenSaleContract = _tokenSaleContract; } /// @dev Internal function to determine if an address is a contract /// @param _addr address The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { if (_addr == 0) { return false; } uint256 size; assembly { size: = extcodesize(_addr) } return (size > 0); } /** * @dev Function to send `_value` tokens to user (`_to`) from sale contract/owner * @param _to address The address that will receive the minted tokens. * @param _value uint256 The amount of tokens to be sent. * @return True if the operation was successful. */ function sendToken(address _to, uint256 _value) public onlyWhenValidAddress(_to) onlyOwnerAndContract returns(bool) { address _from = owner; // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows require(balances[_to] + _value > balances[_to]); // Save this for an assertion in the future uint256 previousBalances = balances[_from] + balances[_to]; // Subtract from the sender balances[_from] -= _value; // Add the same to the recipient balances[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); return true; } /** * @dev Batch transfer of tokens to addresses from owner's balance * @param addresses address[] The address that will receive the minted tokens. * @param _values uint256[] The amount of tokens to be sent. * @return True if the operation was successful. */ function batchSendTokens(address[] addresses, uint256[] _values) public onlyOwnerAndContract returns (bool) { require(addresses.length == _values.length); require(addresses.length <= 20); //only batches of 20 allowed uint i = 0; uint len = addresses.length; for (;i < len; i++) { sendToken(addresses[i], _values[i]); } return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Contracts that should be able to recover tokens * @author SylTi * @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner. * This will prevent any accidental loss of tokens. * https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; //log event whenever withdrawal from this contract address happens event Withdraw(address indexed from, address indexed to, uint256 value); /** * @dev Reclaim all ERC20Basic compatible tokens * @param token ERC20Basic The address of the token contract */ function reclaimToken(address token) external onlyOwner { if (token == 0x0) { owner.transfer(this.balance); return; } ERC20Basic ecr20BasicToken = ERC20Basic(token); uint256 balance = ecr20BasicToken.balanceOf(this); ecr20BasicToken.safeTransfer(owner, balance); Withdraw(msg.sender, owner, balance); } } /** * @title Contracts that should not own Tokens * @author Remco Bloemen <remco@2π.com> * @dev This blocks incoming ERC23 tokens to prevent accidental loss of tokens. * Should tokens (any ERC20Basic compatible) end up in the contract, it allows the * owner to reclaim the tokens. * https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract HasNoTokens is CanReclaimToken { /** * @dev Reject all ERC23 compatible tokens * @param from_ address The address that is transferring the tokens * @param value_ uint256 the amount of the specified token * @param data_ Bytes The data passed from the caller. */ function tokenFallback(address from_, uint256 value_, bytes data_) pure external { from_; value_; data_; revert(); } } contract VZTPresale is Ownable, Pausable, HasNoTokens { using SafeMath for uint256; string public constant name = "VectorZilla Public Presale"; // solium-disable-line uppercase string public constant version = "1.0"; // solium-disable-line uppercase VZToken token; // this multi-sig address will be replaced on production: address public constant VZT_WALLET = 0xa50EB7D45aA025525254aB2452679cE888B16b86; /* if the minimum funding goal in wei is not reached, buyers may withdraw their funds */ uint256 public constant MIN_FUNDING_GOAL = 200 * 10 ** 18; uint256 public constant PRESALE_TOKEN_SOFT_CAP = 1875000 * 10 ** 18; // presale soft cap of 1,875,000 VZT uint256 public constant PRESALE_RATE = 1250; // presale price is 1 ETH to 1,250 VZT uint256 public constant SOFTCAP_RATE = 1150; // presale price becomes 1 ETH to 1,150 VZT after softcap is reached uint256 public constant PRESALE_TOKEN_HARD_CAP = 5900000 * 10 ** 18; // presale token hardcap uint256 public constant MAX_GAS_PRICE = 50000000000; uint256 public minimumPurchaseLimit = 0.1 * 10 ** 18; // minimum purchase is 0.1 ETH to make the gas worthwhile uint256 public startDate = 1516001400; // January 15, 2018 7:30 AM UTC uint256 public endDate = 1517815800; // Febuary 5, 2018 7:30 AM UTC uint256 public totalCollected = 0; // total amount of Ether raised in wei uint256 public tokensSold = 0; // total number of VZT tokens sold uint256 public totalDistributed = 0; // total number of VZT tokens distributed once finalised uint256 public numWhitelisted = 0; // total number whitelisted struct PurchaseLog { uint256 ethValue; uint256 vztValue; bool kycApproved; bool tokensDistributed; bool paidFiat; uint256 lastPurchaseTime; uint256 lastDistributionTime; } //purchase log that captures mapping (address => PurchaseLog) public purchaseLog; //capture refunds mapping (address => bool) public refundLog; //capture buyers in array, this is for quickly looking up from DAPP address[] public buyers; uint256 public buyerCount = 0; // total number of buyers purchased VZT bool public isFinalized = false; // it becomes true when token sale is completed bool public publicSoftCapReached = false; // it becomes true when public softcap is reached // list of addresses that can purchase mapping(address => bool) public whitelist; // event logging for token purchase event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); // event logging for token sale finalized event Finalized(); // event logging for softcap reached event SoftCapReached(); // event logging for funds transfered to VectorZilla multi-sig wallet event FundsTransferred(); // event logging for each individual refunded amount event Refunded(address indexed beneficiary, uint256 weiAmount); // event logging for each individual distributed token + bonus event TokenDistributed(address indexed purchaser, uint256 tokenAmt); /* Constructor to initialize everything. */ function VZTPresale(address _token, address _owner) public { require(_token != address(0)); require(_owner != address(0)); token = VZToken(_token); // default owner owner = _owner; } /* default function to buy tokens. */ function() payable public whenNotPaused { doPayment(msg.sender); } /* allows owner to register token purchases done via fiat-eth (or equivalent currency) */ function payableInFiatEth(address buyer, uint256 value) external onlyOwner { purchaseLog[buyer].paidFiat = true; // do public presale purchasePresale(buyer, value); } function setTokenContract(address _token) external onlyOwner { require(token != address(0)); token = VZToken(_token); } /** * add address to whitelist * @param _addr wallet address to be added to whitelist */ function addToWhitelist(address _addr) public onlyOwner returns (bool) { require(_addr != address(0)); if (!whitelist[_addr]) { whitelist[_addr] = true; numWhitelisted++; } purchaseLog[_addr].kycApproved = true; return true; } /** * add address to whitelist * @param _addresses wallet addresses to be whitelisted */ function addManyToWhitelist(address[] _addresses) external onlyOwner returns (bool) { require(_addresses.length <= 50); uint idx = 0; uint len = _addresses.length; for (; idx < len; idx++) { address _addr = _addresses[idx]; addToWhitelist(_addr); } return true; } /** * remove address from whitelist * @param _addr wallet address to be removed from whitelist */ function removeFomWhitelist(address _addr) public onlyOwner returns (bool) { require(_addr != address(0)); require(whitelist[_addr]); delete whitelist[_addr]; purchaseLog[_addr].kycApproved = false; numWhitelisted--; return true; } /* Send Tokens tokens to a buyer: - and KYC is approved */ function sendTokens(address _user) public onlyOwner returns (bool) { require(_user != address(0)); require(_user != address(this)); require(purchaseLog[_user].kycApproved); require(purchaseLog[_user].vztValue > 0); require(!purchaseLog[_user].tokensDistributed); require(!refundLog[_user]); purchaseLog[_user].tokensDistributed = true; purchaseLog[_user].lastDistributionTime = now; totalDistributed++; token.sendToken(_user, purchaseLog[_user].vztValue); TokenDistributed(_user, purchaseLog[_user].vztValue); return true; } /* Refund ethers to buyer if KYC couldn't/wasn't verified. */ function refundEthIfKYCNotVerified(address _user) public onlyOwner returns (bool) { if (!purchaseLog[_user].kycApproved) { return doRefund(_user); } return false; } /* /* return true if buyer is whitelisted */ function isWhitelisted(address buyer) public view returns (bool) { return whitelist[buyer]; } /* Check to see if this is public presale. */ function isPresale() public view returns (bool) { return !isFinalized && now >= startDate && now <= endDate; } /* check if allocated has sold out. */ function hasSoldOut() public view returns (bool) { return PRESALE_TOKEN_HARD_CAP - tokensSold < getMinimumPurchaseVZTLimit(); } /* Check to see if the presale end date has passed or if all tokens allocated for sale has been purchased. */ function hasEnded() public view returns (bool) { return now > endDate || hasSoldOut(); } /* Determine if the minimum goal in wei has been reached. */ function isMinimumGoalReached() public view returns (bool) { return totalCollected >= MIN_FUNDING_GOAL; } /* For the convenience of presale interface to present status info. */ function getSoftCapReached() public view returns (bool) { return publicSoftCapReached; } function setMinimumPurchaseEtherLimit(uint256 newMinimumPurchaseLimit) external onlyOwner { require(newMinimumPurchaseLimit > 0); minimumPurchaseLimit = newMinimumPurchaseLimit; } /* For the convenience of presale interface to find current tier price. */ function getMinimumPurchaseVZTLimit() public view returns (uint256) { if (getTier() == 1) { return minimumPurchaseLimit.mul(PRESALE_RATE); //1250VZT/ether } else if (getTier() == 2) { return minimumPurchaseLimit.mul(SOFTCAP_RATE); //1150VZT/ether } return minimumPurchaseLimit.mul(1000); //base price } /* For the convenience of presale interface to find current discount tier. */ function getTier() public view returns (uint256) { // Assume presale top tier discount uint256 tier = 1; if (now >= startDate && now < endDate && getSoftCapReached()) { // tier 2 discount tier = 2; } return tier; } /* For the convenience of presale interface to present status info. */ function getPresaleStatus() public view returns (uint256[3]) { // 0 - presale not started // 1 - presale started // 2 - presale ended if (now < startDate) return ([0, startDate, endDate]); else if (now <= endDate && !hasEnded()) return ([1, startDate, endDate]); else return ([2, startDate, endDate]); } /* Called after presale ends, to do some extra finalization work. */ function finalize() public onlyOwner { // do nothing if finalized require(!isFinalized); // presale must have ended require(hasEnded()); if (isMinimumGoalReached()) { // transfer to VectorZilla multisig wallet VZT_WALLET.transfer(this.balance); // signal the event for communication FundsTransferred(); } // mark as finalized isFinalized = true; // signal the event for communication Finalized(); } /** * @notice `proxyPayment()` allows the caller to send ether to the VZTPresale * and have the tokens created in an address of their choosing * @param buyer The address that will hold the newly created tokens */ function proxyPayment(address buyer) payable public whenNotPaused returns(bool success) { return doPayment(buyer); } /* Just in case we need to tweak pre-sale dates */ function setDates(uint256 newStartDate, uint256 newEndDate) public onlyOwner { require(newEndDate >= newStartDate); startDate = newStartDate; endDate = newEndDate; } // @dev `doPayment()` is an internal function that sends the ether that this // contract receives to the `vault` and creates tokens in the address of the // `buyer` assuming the VZTPresale is still accepting funds // @param buyer The address that will hold the newly created tokens // @return True if payment is processed successfully function doPayment(address buyer) internal returns(bool success) { require(tx.gasprice <= MAX_GAS_PRICE); // Antispam // do not allow contracts to game the system require(buyer != address(0)); require(!isContract(buyer)); // limit the amount of contributions to once per 100 blocks //require(getBlockNumber().sub(lastCallBlock[msg.sender]) >= maxCallFrequency); //lastCallBlock[msg.sender] = getBlockNumber(); if (msg.sender != owner) { // stop if presale is over require(isPresale()); // stop if no more token is allocated for sale require(!hasSoldOut()); require(msg.value >= minimumPurchaseLimit); } require(msg.value > 0); purchasePresale(buyer, msg.value); return true; } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns (bool) { if (_addr == 0) { return false; } uint256 size; assembly { size := extcodesize(_addr) } return (size > 0); } /// @dev Internal function to process sale /// @param buyer The buyer address /// @param value The value of ether paid function purchasePresale(address buyer, uint256 value) internal { require(value >= minimumPurchaseLimit); require(buyer != address(0)); uint256 tokens = 0; // still under soft cap if (!publicSoftCapReached) { // 1 ETH for 1,250 VZT tokens = value * PRESALE_RATE; // get less if over softcap if (tokensSold + tokens > PRESALE_TOKEN_SOFT_CAP) { uint256 availablePresaleTokens = PRESALE_TOKEN_SOFT_CAP - tokensSold; uint256 softCapTokens = (value - (availablePresaleTokens / PRESALE_RATE)) * SOFTCAP_RATE; tokens = availablePresaleTokens + softCapTokens; // process presale at 1 ETH to 1,150 VZT processSale(buyer, value, tokens, SOFTCAP_RATE); // public soft cap has been reached publicSoftCapReached = true; // signal the event for communication SoftCapReached(); } else { // process presale @PRESALE_RATE processSale(buyer, value, tokens, PRESALE_RATE); } } else { // 1 ETH to 1,150 VZT tokens = value * SOFTCAP_RATE; // process presale at 1 ETH to 1,150 VZT processSale(buyer, value, tokens, SOFTCAP_RATE); } } /* process sale at determined price. */ function processSale(address buyer, uint256 value, uint256 vzt, uint256 vztRate) internal { require(buyer != address(0)); require(vzt > 0); require(vztRate > 0); require(value > 0); uint256 vztOver = 0; uint256 excessEthInWei = 0; uint256 paidValue = value; uint256 purchasedVzt = vzt; if (tokensSold + purchasedVzt > PRESALE_TOKEN_HARD_CAP) {// if maximum is exceeded // find overage vztOver = tokensSold + purchasedVzt - PRESALE_TOKEN_HARD_CAP; // overage ETH to refund excessEthInWei = vztOver / vztRate; // adjust tokens purchased purchasedVzt = purchasedVzt - vztOver; // adjust Ether paid paidValue = paidValue - excessEthInWei; } /* To quick lookup list of buyers (pending token, kyc, or even refunded) we are keeping an array of buyers. There might be duplicate entries when a buyer gets refund (incomplete kyc, or requested), and then again contributes. */ if (purchaseLog[buyer].vztValue == 0) { buyers.push(buyer); buyerCount++; } //if not whitelisted, mark kyc pending if (!isWhitelisted(buyer)) { purchaseLog[buyer].kycApproved = false; } //reset refund status in refundLog refundLog[buyer] = false; // record purchase in purchaseLog purchaseLog[buyer].vztValue = SafeMath.add(purchaseLog[buyer].vztValue, purchasedVzt); purchaseLog[buyer].ethValue = SafeMath.add(purchaseLog[buyer].ethValue, paidValue); purchaseLog[buyer].lastPurchaseTime = now; // total Wei raised totalCollected += paidValue; // total VZT sold tokensSold += purchasedVzt; /* For event, log buyer and beneficiary properly */ address beneficiary = buyer; if (beneficiary == msg.sender) { beneficiary = msg.sender; } // signal the event for communication TokenPurchase(buyer, beneficiary, paidValue, purchasedVzt); // transfer must be done at the end after all states are updated to prevent reentrancy attack. if (excessEthInWei > 0 && !purchaseLog[buyer].paidFiat) { // refund overage ETH buyer.transfer(excessEthInWei); // signal the event for communication Refunded(buyer, excessEthInWei); } } /* Distribute tokens to a buyer: - when minimum goal is reached - and KYC is approved */ function distributeTokensFor(address buyer) external onlyOwner returns (bool) { require(isFinalized); require(hasEnded()); if (isMinimumGoalReached()) { return sendTokens(buyer); } return false; } /* purchaser requesting a refund, only allowed when minimum goal not reached. */ function claimRefund() external returns (bool) { return doRefund(msg.sender); } /* send refund to purchaser requesting a refund */ function sendRefund(address buyer) external onlyOwner returns (bool) { return doRefund(buyer); } /* Internal function to manage refunds */ function doRefund(address buyer) internal returns (bool) { require(tx.gasprice <= MAX_GAS_PRICE); require(buyer != address(0)); require(!purchaseLog[buyer].paidFiat); if (msg.sender != owner) { // cannot refund unless authorized require(isFinalized && !isMinimumGoalReached()); } require(purchaseLog[buyer].ethValue > 0); require(purchaseLog[buyer].vztValue > 0); require(!refundLog[buyer]); require(!purchaseLog[buyer].tokensDistributed); // ETH to refund uint256 depositedValue = purchaseLog[buyer].ethValue; //VZT to revert uint256 vztValue = purchaseLog[buyer].vztValue; // assume all refunded, should we even do this if // we are going to delete buyer from log? purchaseLog[buyer].ethValue = 0; purchaseLog[buyer].vztValue = 0; refundLog[buyer] = true; //delete from purchase log. //but we won't remove buyer from buyers array delete purchaseLog[buyer]; //decrement global counters tokensSold = tokensSold.sub(vztValue); totalCollected = totalCollected.sub(depositedValue); // send must be called only after purchaseLog[buyer] is deleted to //prevent reentrancy attack. buyer.transfer(depositedValue); Refunded(buyer, depositedValue); return true; } function getBuyersList() external view returns (address[]) { return buyers; } /** * @dev Transfer all Ether held by the contract to the owner. * Emergency where we might need to recover */ function reclaimEther() external onlyOwner { assert(owner.send(this.balance)); } }
total amount of Ether raised in wei
uint256 public totalCollected = 0;
939,828
[ 1, 4963, 3844, 434, 512, 1136, 11531, 316, 732, 77, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 2078, 10808, 329, 273, 374, 31, 4766, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1313161554/0x51e20134b7c11D9e868E0EE227BAbc429CA1c2e8/sources/contracts/facets/bridges/cbridge/RangoCBridgeFacet.sol
@notice Emits when the cBridge address is updated @param oldAddress The previous address @param newAddress The new address
event RangoCBridgeMiddlewareAddressUpdated(address oldAddress, address newAddress);
13,230,116
[ 1, 1514, 1282, 1347, 326, 276, 13691, 1758, 353, 3526, 225, 1592, 1887, 1021, 2416, 1758, 225, 394, 1887, 1021, 394, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 534, 6399, 8876, 5404, 9410, 1887, 7381, 12, 2867, 1592, 1887, 16, 1758, 394, 1887, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED // Copyright (c) 2021 0xdev0 - All rights reserved // https://twitter.com/0xdev0 pragma solidity 0.8.6; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function symbol() external view returns (string memory); function decimals() external view returns (uint); function approve(address spender, uint amount) external returns (bool); function mint(address account, uint amount) external; function burn(address account, uint amount) external; function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IUniswapRouter { function getAmountsOut( uint amountIn, address[] memory path ) external view returns (uint[] memory amounts); function getAmountsIn( uint amountOut, address[] memory path ) external view returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); 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); } interface ILendingPair { function checkAccountHealth(address _account) external view; function accrueAccount(address _account) external; function accrue() external; function accountHealth(address _account) external view returns(uint); function totalDebt(address _token) external view returns(uint); function tokenA() external view returns(address); function tokenB() external view returns(address); function lpToken(address _token) external view returns(IERC20); function debtOf(address _account, address _token) external view returns(uint); function pendingDebtTotal(address _token) external view returns(uint); function pendingSupplyTotal(address _token) external view returns(uint); function deposit(address _token, uint _amount) external; function withdraw(address _token, uint _amount) external; function borrow(address _token, uint _amount) external; function repay(address _token, uint _amount) external; function withdrawBorrow(address _token, uint _amount) external; function controller() external view returns(IController); function borrowBalance( address _account, address _borrowedToken, address _returnToken ) external view returns(uint); function convertTokenValues( address _fromToken, address _toToken, uint _inputAmount ) external view returns(uint); } interface IInterestRateModel { function systemRate(ILendingPair _pair, address _token) external view returns(uint); function supplyRatePerBlock(ILendingPair _pair, address _token) external view returns(uint); function borrowRatePerBlock(ILendingPair _pair, address _token) external view returns(uint); } interface IRewardDistribution { function distributeReward(address _account, address _token) external; function setTotalRewardPerBlock(uint _value) external; function migrateRewards(address _recipient, uint _amount) external; function addPool( address _pair, address _token, bool _isSupply, uint _points ) external; function setReward( address _pair, address _token, bool _isSupply, uint _points ) external; } interface IController { function interestRateModel() external view returns(IInterestRateModel); function rewardDistribution() external view returns(IRewardDistribution); function feeRecipient() external view returns(address); function LIQ_MIN_HEALTH() external view returns(uint); function minBorrowUSD() external view returns(uint); function liqFeeSystem(address _token) external view returns(uint); function liqFeeCaller(address _token) external view returns(uint); function liqFeesTotal(address _token) external view returns(uint); function colFactor(address _token) external view returns(uint); function depositLimit(address _lendingPair, address _token) external view returns(uint); function borrowLimit(address _lendingPair, address _token) external view returns(uint); function originFee(address _token) external view returns(uint); function depositsEnabled() external view returns(bool); function borrowingEnabled() external view returns(bool); function setFeeRecipient(address _feeRecipient) external; function tokenPrice(address _token) external view returns(uint); function tokenSupported(address _token) external view returns(bool); function setRewardDistribution(address _value) external; function setInterestRateModel(address _value) external; function setDepositLimit(address _pair, address _token, uint _value) external; } contract Ownable { address public owner; address public pendingOwner; event OwnershipTransferInitiated(address indexed previousOwner, address indexed newOwner); event OwnershipTransferConfirmed(address indexed previousOwner, address indexed newOwner); constructor() { owner = msg.sender; emit OwnershipTransferConfirmed(address(0), owner); } modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } function isOwner() public view returns (bool) { return msg.sender == owner; } function transferOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferInitiated(owner, _newOwner); pendingOwner = _newOwner; } function acceptOwnership() external { require(msg.sender == pendingOwner, "Ownable: caller is not pending owner"); emit OwnershipTransferConfirmed(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract FeeConverter is Ownable { uint private constant MAX_INT = 2**256 - 1; // Only large liquid tokens: ETH, DAI, USDC, WBTC, etc mapping (address => bool) public permittedTokens; IUniswapRouter public uniswapRouter; IERC20 public wildToken; IController public controller; address public stakingPool; uint public callIncentive; event FeeDistribution(uint amount); constructor( IUniswapRouter _uniswapRouter, IController _controller, IERC20 _wildToken, address _stakingPool, uint _callIncentive ) { uniswapRouter = _uniswapRouter; controller = _controller; stakingPool = _stakingPool; callIncentive = _callIncentive; wildToken = _wildToken; } function convert( address _incentiveRecipient, ILendingPair _pair, address[] memory _path, uint _supplyTokenAmount ) external { _validatePath(_path); require(_pair.controller() == controller, "FeeConverter: invalid pair"); require(_supplyTokenAmount > 0, "FeeConverter: nothing to convert"); _pair.withdraw(_path[0], _supplyTokenAmount); IERC20(_path[0]).approve(address(uniswapRouter), MAX_INT); uniswapRouter.swapExactTokensForTokens( _supplyTokenAmount, 0, _path, address(this), block.timestamp + 1000 ); uint wildBalance = wildToken.balanceOf(address(this)); uint callerIncentive = wildBalance * callIncentive / 100e18; wildToken.transfer(_incentiveRecipient, callerIncentive); wildToken.transfer(stakingPool, wildBalance - callerIncentive); emit FeeDistribution(wildBalance - callerIncentive); } function setStakingRewards(address _value) external onlyOwner { stakingPool = _value; } function setController(IController _value) external onlyOwner { controller = _value; } function setCallIncentive(uint _value) external onlyOwner { callIncentive = _value; } function permitToken(address _token, bool _value) external onlyOwner { permittedTokens[_token] = _value; } function _validatePath(address[] memory _path) internal view { require(_path[_path.length - 1] == address(wildToken), "FeeConverter: must convert into WILD"); // Validate only middle tokens. Skip the first and last token. for (uint i; i < _path.length - 1; i++) { if (i > 0) { require(permittedTokens[_path[i]], "FeeConverter: invalid path"); } } } }
Only large liquid tokens: ETH, DAI, USDC, WBTC, etc
contract FeeConverter is Ownable { uint private constant MAX_INT = 2**256 - 1; mapping (address => bool) public permittedTokens; IUniswapRouter public uniswapRouter; IERC20 public wildToken; IController public controller; address public stakingPool; uint public callIncentive; event FeeDistribution(uint amount); constructor( IUniswapRouter _uniswapRouter, IController _controller, IERC20 _wildToken, address _stakingPool, uint _callIncentive ) { uniswapRouter = _uniswapRouter; controller = _controller; stakingPool = _stakingPool; callIncentive = _callIncentive; wildToken = _wildToken; } function convert( address _incentiveRecipient, ILendingPair _pair, address[] memory _path, uint _supplyTokenAmount ) external { _validatePath(_path); require(_pair.controller() == controller, "FeeConverter: invalid pair"); require(_supplyTokenAmount > 0, "FeeConverter: nothing to convert"); _pair.withdraw(_path[0], _supplyTokenAmount); IERC20(_path[0]).approve(address(uniswapRouter), MAX_INT); uniswapRouter.swapExactTokensForTokens( _supplyTokenAmount, 0, _path, address(this), block.timestamp + 1000 ); uint wildBalance = wildToken.balanceOf(address(this)); uint callerIncentive = wildBalance * callIncentive / 100e18; wildToken.transfer(_incentiveRecipient, callerIncentive); wildToken.transfer(stakingPool, wildBalance - callerIncentive); emit FeeDistribution(wildBalance - callerIncentive); } function setStakingRewards(address _value) external onlyOwner { stakingPool = _value; } function setController(IController _value) external onlyOwner { controller = _value; } function setCallIncentive(uint _value) external onlyOwner { callIncentive = _value; } function permitToken(address _token, bool _value) external onlyOwner { permittedTokens[_token] = _value; } function _validatePath(address[] memory _path) internal view { require(_path[_path.length - 1] == address(wildToken), "FeeConverter: must convert into WILD"); for (uint i; i < _path.length - 1; i++) { if (i > 0) { require(permittedTokens[_path[i]], "FeeConverter: invalid path"); } } } function _validatePath(address[] memory _path) internal view { require(_path[_path.length - 1] == address(wildToken), "FeeConverter: must convert into WILD"); for (uint i; i < _path.length - 1; i++) { if (i > 0) { require(permittedTokens[_path[i]], "FeeConverter: invalid path"); } } } function _validatePath(address[] memory _path) internal view { require(_path[_path.length - 1] == address(wildToken), "FeeConverter: must convert into WILD"); for (uint i; i < _path.length - 1; i++) { if (i > 0) { require(permittedTokens[_path[i]], "FeeConverter: invalid path"); } } } }
5,879,426
[ 1, 3386, 7876, 4501, 26595, 2430, 30, 512, 2455, 16, 463, 18194, 16, 11836, 5528, 16, 678, 38, 15988, 16, 5527, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 30174, 5072, 353, 14223, 6914, 288, 203, 203, 225, 2254, 3238, 5381, 4552, 67, 3217, 273, 576, 636, 5034, 300, 404, 31, 203, 203, 225, 2874, 261, 2867, 516, 1426, 13, 1071, 15498, 5157, 31, 203, 203, 225, 467, 984, 291, 91, 438, 8259, 1071, 640, 291, 91, 438, 8259, 31, 203, 225, 467, 654, 39, 3462, 540, 1071, 23578, 1345, 31, 203, 225, 467, 2933, 565, 1071, 2596, 31, 203, 225, 1758, 3639, 1071, 384, 6159, 2864, 31, 203, 225, 2254, 6647, 1071, 745, 382, 2998, 688, 31, 203, 203, 225, 871, 30174, 9003, 12, 11890, 3844, 1769, 203, 203, 225, 3885, 12, 203, 565, 467, 984, 291, 91, 438, 8259, 389, 318, 291, 91, 438, 8259, 16, 203, 565, 467, 2933, 565, 389, 5723, 16, 203, 565, 467, 654, 39, 3462, 540, 389, 91, 545, 1345, 16, 203, 565, 1758, 3639, 389, 334, 6159, 2864, 16, 203, 565, 2254, 6647, 389, 1991, 382, 2998, 688, 203, 225, 262, 288, 203, 565, 640, 291, 91, 438, 8259, 273, 389, 318, 291, 91, 438, 8259, 31, 203, 565, 2596, 565, 273, 389, 5723, 31, 203, 565, 384, 6159, 2864, 282, 273, 389, 334, 6159, 2864, 31, 203, 565, 745, 382, 2998, 688, 273, 389, 1991, 382, 2998, 688, 31, 203, 565, 23578, 1345, 377, 273, 389, 91, 545, 1345, 31, 203, 225, 289, 203, 203, 225, 445, 1765, 12, 203, 565, 1758, 1850, 389, 267, 2998, 688, 18241, 16, 203, 565, 467, 48, 2846, 4154, 377, 389, 6017, 16, 203, 565, 1758, 8526, 2 ]
./full_match/56/0xC33FfC542DF2fDefB04eF03c5f6b23EB39519531/sources/project_/contracts/ELFIN.sol
* @dev Destroys `amount` tokens from the caller. See {ERC20-_burn}./
function burn(uint256 amount) public virtual onlyOwner{ _burn(_msgSender(), amount); }
3,230,881
[ 1, 9378, 28599, 1375, 8949, 68, 2430, 628, 326, 4894, 18, 2164, 288, 654, 39, 3462, 17, 67, 70, 321, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 12, 11890, 5034, 3844, 13, 1071, 5024, 1338, 5541, 95, 203, 3639, 389, 70, 321, 24899, 3576, 12021, 9334, 3844, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x4e2874B02d97336ADf7e37a28795B8478E54c166/sources/experiments/AveragePrice.sol
overflow is desired
uint32 timeElapsed = blockTimestampCurrent - blockTimestampLast;
9,570,319
[ 1, 11512, 353, 6049, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 1578, 813, 28827, 273, 1203, 4921, 3935, 300, 1203, 4921, 3024, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; /** * @title Holdme Token Sale * * Created by IaM <DEV> (Elky Bachtiar) * https://www.iamdeveloper.io * * */ import './Holdme.sol'; import './TokenController.sol'; import '../installed_contracts/ERC23/contracts/Utils.sol/'; import '../installed_contracts/ERC23/installed_contracts/zeppelin-solidity/contracts/lifecycle/Pausable.sol'; import '../installed_contracts/ERC23/installed_contracts/zeppelin-solidity/contracts/math/SafeMath.sol'; contract HoldmeTokenSale is TokenController, Pausable { using SafeMath for uint256; uint256 public decimals; // To be able to calculate the token amount uint256 public constant TOKEN_PRICE_N = 1; // initial price in wei (numerator) uint256 public constant TOKEN_PRICE_D = 3030; // initial price in wei (denominator) uint256 public constant MAX_GAS_PRICE = 60000000000 wei; // maximum gas price for contribution transactions string public version = "1.0"; uint256 public startTime = 1506729540; // crowdsale start time (in seconds) Presale starts 2017/09/29 23:59:00 uint256 public endTime = 1507420740; // crowdsale end time (in seconds) Presale ends 2017/10/07 23:59:00 uint256 public totalTokenCap = 300000000; // current token cap uint256 public totalTokenIssued = 0; // token issued so far uint256 public totalEtherContributed = 0; // ether contributed so far address public beneficiary = 0x0; // address to receive all ether contributions address public devTeam = 0x0; // Multi sign address Developer Team bool public preLaunch = false; // Set pre-launch to true or false bool public isFinalized = false; // When Pre-Sale or sale is end, isFinalized will set to true // triggered on each contribution event Contribution(address indexed _contributor, uint256 _amount, uint256 _return); event Finalized(); function HoldmeTokenSale (Holdme _token, address _centralAdmin, uint256 _startTime, uint256 _endTime, address _beneficiary, address _devTeam, address[] _whitelists ,uint256 _decimals) TokenController(_token) Whitelist(_whitelists, maxAddresses) { if (_centralAdmin != 0) { owner = _centralAdmin; } else { owner = msg.sender; } startTime = _startTime; endTime = _endTime; beneficiary = _beneficiary; devTeam = _devTeam; decimals = _decimals; } // fallback when investor transfering Ether to the crowdsale contract without calling any functions function() payable { contributeETH(); } // ensures that the current time is between _startTime (inclusive) and _endTime (exclusive) modifier between() { assert((now >= startTime && now < endTime)); _; } // ensures that we didn't reach the token max cap modifier tokenMaxCapNotReached() { assert(totalTokenIssued <= totalTokenCap); _; } // verifies that the gas price is lower than 60 gwei modifier validGasPrice() { assert(tx.gasprice <= MAX_GAS_PRICE); _; } /** * @dev startPresale. Start the Pre-sale * * @return A boolean that indicates if the operation was successful. */ function startPresale() onlyOwner returns (bool success) { require(!preLaunch); preLaunch = true; return true; } /** * @dev setStartTime change the starttime. * for example to be able to start ICO after pre-sale * * @param _newStartTime the new start time to be set * * @return A boolean that indicates if the operation was successful. */ function setStartTime(uint256 _newStartTime) public onlyOwner greaterThanZero(_newStartTime) returns (bool success) { startTime = _newStartTime; return true; } /** * @dev setEndTime change the end time . * for example to be able to start ICO after pre-sale * * @param _newEndTime the new end time to be set * * @return A boolean that indicates if the operation was successful. */ function setEndTime(uint256 _newEndTime) public onlyOwner greaterThanZero(_newEndTime) returns (bool success) { //require(_newEndTime >= startTime); endTime = _newEndTime; return true; } /** * @dev ETH contribution * can only be called during the crowdsale * * @return tokens issued in return */ function contributeETH() public payable between tokenMaxCapNotReached validAddress(msg.sender) greaterThanZero(msg.value) returns (uint256 amount) { require(!isFinalized); uint256 realEther = 1; return processContribution(msg.sender, msg.value, realEther); } /** * @dev COINS contribution * can only be called only by whitelisted address * * @param _contributor the address of the contributor * @param _amount the amount of ether in wei of the contributor * * @return tokens issued in return */ function contributeCoins(address _contributor, uint256 _amount) public addressWhitelisted(msg.sender) validAddress(_contributor) greaterThanZero(_amount) returns (uint256 amount) { require(!isFinalized); uint256 realEther = 0; return processContribution(_contributor, _amount, realEther); } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner { require(!isFinalized); require(hasEnded()); //finalization(); Finalized(); isFinalized = true; } /** @dev computes the number of tokens that should be issued for a given contribution @param _contribution contribution amount @return computed number of tokens */ function computeReturn(uint256 _contribution) public constant returns (uint256 amount) { uint256 calcAmount; uint256 tokenPrice; if (preLaunch) { tokenPrice = TOKEN_PRICE_D.mul(35).div(100); //35% discount on Pre-sale } else { tokenPrice = TOKEN_PRICE_D; } calcAmount = (_contribution.mul(tokenPrice)).div(TOKEN_PRICE_N); calcAmount = removeDecimals(calcAmount); return calcAmount; } /** Sending Company shares for the Team */ function sendShares() internal { uint256 totalShareToIssue = totalTokenIssued.mul(79).div(21); totalTokenIssued = totalTokenIssued.add(totalShareToIssue); uint256 beneficiaryToken = totalTokenIssued.mul(51).div(100); uint256 devTeamToken = totalTokenIssued.mul(15).div(100); uint256 reverseToken = totalTokenIssued.mul(14).div(100); token.issue(beneficiary, beneficiaryToken); token.issue(devTeam, devTeamToken); token.issue(owner, reverseToken); } /** @dev handles contribution logic note that the Contribution event is triggered using the sender as the contributor, regardless of the actual contributor @return tokens issued in return */ function processContribution(address _contributor, uint256 _amount, uint256 _realEther) private returns (uint256 amount) { uint256 tokenAmount = computeReturn(_amount); if (_realEther == 1 && msg.value > 0) { totalEtherContributed = totalEtherContributed.add(msg.value);// update the total contribution amount, only update when real ether has been sent } token.issue(_contributor, tokenAmount); tokenAmount = removeDecimals(tokenAmount); totalTokenIssued = totalTokenIssued.add(tokenAmount); sendShares(); Contribution(_contributor, _amount, tokenAmount); return tokenAmount; } // remove decimals of the tokens function removeDecimals(uint256 _amount) internal returns (uint256 newAmount) { uint256 divider; if (decimals == 0) { divider = 10 ** 18; newAmount = _amount.div(divider); } else if (decimals == 18) { newAmount = _amount; } else { divider = 10 ** (18 - decimals); newAmount = _amount.div(divider); } return newAmount; } }
initial price in wei (denominator)
uint256 public constant TOKEN_PRICE_D = 3030;
14,068,608
[ 1, 6769, 6205, 316, 732, 77, 261, 13002, 26721, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 14275, 67, 7698, 1441, 67, 40, 273, 890, 4630, 20, 31, 7734, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.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 () { 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.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 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; } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./RoleAware.sol"; import "./Fund.sol"; import "./CrossMarginTrading.sol"; import "../libraries/IncentiveReporter.sol"; /** @title Here we support staking for MFI incentives as well as staking to perform the maintenance role. */ contract Admin is RoleAware { /// Margenswap (MFI) token address address public immutable MFI; mapping(address => uint256) public stakes; uint256 public totalStakes; uint256 public constant mfiStakeTranche = 1; uint256 public maintenanceStakePerBlock = 15 ether; mapping(address => address) public nextMaintenanceStaker; mapping(address => mapping(address => bool)) public maintenanceDelegateTo; address public currentMaintenanceStaker; address public prevMaintenanceStaker; uint256 public currentMaintenanceStakerStartBlock; address public immutable lockedMFI; constructor( address _MFI, address _lockedMFI, address lockedMFIDelegate, address _roles ) RoleAware(_roles) { MFI = _MFI; lockedMFI = _lockedMFI; // for initialization purposes and to ensure availability of service // the team's locked MFI participate in maintenance staking only // (not in the incentive staking part) // this implies some trust of the team to execute, which we deem reasonable // since the locked stake is temporary and diminishing as well as the fact // that the team is heavily invested in the protocol and incentivized // by fees like any other maintainer // furthermore others could step in to liquidate via the attacker route // and take away the team fees if they were delinquent nextMaintenanceStaker[_lockedMFI] = _lockedMFI; currentMaintenanceStaker = _lockedMFI; prevMaintenanceStaker = _lockedMFI; maintenanceDelegateTo[_lockedMFI][lockedMFIDelegate]; currentMaintenanceStakerStartBlock = block.number; } /// Maintence stake setter function setMaintenanceStakePerBlock(uint256 amount) external onlyOwnerExec { maintenanceStakePerBlock = amount; } function _stake(address holder, uint256 amount) internal { Fund(fund()).depositFor(holder, MFI, amount); stakes[holder] += amount; totalStakes += amount; IncentiveReporter.addToClaimAmount(MFI, holder, amount); } /// Deposit a stake for sender function depositStake(uint256 amount) external { _stake(msg.sender, amount); } function _withdrawStake( address holder, uint256 amount, address recipient ) internal { // overflow failure desirable stakes[holder] -= amount; totalStakes -= amount; Fund(fund()).withdraw(MFI, recipient, amount); IncentiveReporter.subtractFromClaimAmount(MFI, holder, amount); } /// Withdraw stake for sender function withdrawStake(uint256 amount) external { require( !isAuthorizedStaker(msg.sender), "You can't withdraw while you're authorized staker" ); _withdrawStake(msg.sender, amount, msg.sender); } /// Deposit maintenance stake function depositMaintenanceStake(uint256 amount) external { require( amount + stakes[msg.sender] >= maintenanceStakePerBlock, "Insufficient stake to call even one block" ); _stake(msg.sender, amount); if (nextMaintenanceStaker[msg.sender] == address(0)) { nextMaintenanceStaker[msg.sender] = getUpdatedCurrentStaker(); nextMaintenanceStaker[prevMaintenanceStaker] = msg.sender; } } function getMaintenanceStakerStake(address staker) public view returns (uint256) { if (staker == lockedMFI) { return IERC20(MFI).balanceOf(lockedMFI) / 2; } else { return stakes[staker]; } } function getUpdatedCurrentStaker() public returns (address) { uint256 currentStake = getMaintenanceStakerStake(currentMaintenanceStaker); if ( (block.number - currentMaintenanceStakerStartBlock) * maintenanceStakePerBlock >= currentStake ) { currentMaintenanceStakerStartBlock = block.number; prevMaintenanceStaker = currentMaintenanceStaker; currentMaintenanceStaker = nextMaintenanceStaker[ currentMaintenanceStaker ]; currentStake = getMaintenanceStakerStake(currentMaintenanceStaker); if (maintenanceStakePerBlock > currentStake) { // delete current from daisy chain address nextOne = nextMaintenanceStaker[currentMaintenanceStaker]; nextMaintenanceStaker[prevMaintenanceStaker] = nextOne; nextMaintenanceStaker[currentMaintenanceStaker] = address(0); currentMaintenanceStaker = nextOne; currentStake = getMaintenanceStakerStake( currentMaintenanceStaker ); } } return currentMaintenanceStaker; } function viewCurrentMaintenanceStaker() public view returns (address staker, uint256 startBlock) { staker = currentMaintenanceStaker; uint256 currentStake = getMaintenanceStakerStake(staker); startBlock = currentMaintenanceStakerStartBlock; if ( (block.number - startBlock) * maintenanceStakePerBlock >= currentStake ) { staker = nextMaintenanceStaker[staker]; currentStake = getMaintenanceStakerStake(staker); startBlock = block.number; if (maintenanceStakePerBlock > currentStake) { staker = nextMaintenanceStaker[staker]; } } } /// Add a delegate for staker function addDelegate(address forStaker, address delegate) external { require( msg.sender == forStaker || maintenanceDelegateTo[forStaker][msg.sender], "msg.sender not authorized to delegate for staker" ); maintenanceDelegateTo[forStaker][delegate] = true; } /// Remove a delegate for staker function removeDelegate(address forStaker, address delegate) external { require( msg.sender == forStaker || maintenanceDelegateTo[forStaker][msg.sender], "msg.sender not authorized to delegate for staker" ); maintenanceDelegateTo[forStaker][delegate] = false; } function isAuthorizedStaker(address caller) public returns (bool isAuthorized) { address currentStaker = getUpdatedCurrentStaker(); isAuthorized = currentStaker == caller || maintenanceDelegateTo[currentStaker][caller]; } /// Penalize a staker function penalizeMaintenanceStake( address maintainer, uint256 penalty, address recipient ) external returns (uint256 stakeTaken) { require( isStakePenalizer(msg.sender), "msg.sender not authorized to penalize stakers" ); if (penalty > stakes[maintainer]) { stakeTaken = stakes[maintainer]; } else { stakeTaken = penalty; } _withdrawStake(maintainer, stakeTaken, recipient); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; /// @title Base lending behavior abstract contract BaseLending { uint256 constant FP48 = 2**48; uint256 constant ACCUMULATOR_INIT = 10**18; uint256 constant hoursPerYear = 365 days / (1 hours); uint256 constant CHANGE_POINT = 79; uint256 public normalRatePerPercent = (FP48 * 15) / hoursPerYear / CHANGE_POINT / 100; uint256 public highRatePerPercent = (FP48 * (194 - 15)) / hoursPerYear / (100 - CHANGE_POINT) / 100; struct YieldAccumulator { uint256 accumulatorFP; uint256 lastUpdated; uint256 hourlyYieldFP; } struct LendingMetadata { uint256 totalLending; uint256 totalBorrowed; uint256 lendingCap; } mapping(address => LendingMetadata) public lendingMeta; /// @dev accumulate interest per issuer (like compound indices) mapping(address => YieldAccumulator) public borrowYieldAccumulators; /// @dev simple formula for calculating interest relative to accumulator function applyInterest( uint256 balance, uint256 accumulatorFP, uint256 yieldQuotientFP ) internal pure returns (uint256) { // 1 * FP / FP = 1 return (balance * accumulatorFP) / yieldQuotientFP; } function currentLendingRateFP(uint256 totalLending, uint256 totalBorrowing) internal view returns (uint256 rate) { rate = FP48; uint256 utilizationPercent = (100 * totalBorrowing) / totalLending; if (utilizationPercent < CHANGE_POINT) { rate += utilizationPercent * normalRatePerPercent; } else { rate += CHANGE_POINT * normalRatePerPercent + (utilizationPercent - CHANGE_POINT) * highRatePerPercent; } } /// @dev minimum function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return b; } else { return a; } } /// @dev maximum function max(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a; } else { return b; } } /// Available tokens to this issuance function issuanceBalance(address issuance) internal view virtual returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Fund.sol"; import "../libraries/UniswapStyleLib.sol"; abstract contract BaseRouter { modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "Trade has expired"); _; } // **** SWAP **** /// @dev requires the initial amount to have already been sent to the first pair /// and for pairs to be vetted (which getAmountsIn / getAmountsOut do) function _swap( uint256[] memory amounts, address[] memory pairs, address[] memory tokens, address _to ) internal { for (uint256 i; i < pairs.length; i++) { (address input, address output) = (tokens[i], tokens[i + 1]); (address token0, ) = UniswapStyleLib.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < pairs.length - 1 ? pairs[i + 1] : _to; IUniswapV2Pair pair = IUniswapV2Pair(pairs[i]); pair.swap(amount0Out, amount1Out, to, new bytes(0)); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./Fund.sol"; import "./Lending.sol"; import "./RoleAware.sol"; import "./PriceAware.sol"; // Goal: all external functions only accessible to margintrader role // except for view functions of course struct CrossMarginAccount { uint256 lastDepositBlock; address[] borrowTokens; // borrowed token address => amount mapping(address => uint256) borrowed; // borrowed token => yield quotient mapping(address => uint256) borrowedYieldQuotientsFP; address[] holdingTokens; // token held in portfolio => amount mapping(address => uint256) holdings; // boolean value of whether an account holds a token mapping(address => bool) holdsToken; } abstract contract CrossMarginAccounts is RoleAware, PriceAware { /// @dev gets used in calculating how much accounts can borrow uint256 public leveragePercent = 300; /// @dev percentage of assets held per assets borrowed at which to liquidate uint256 public liquidationThresholdPercent = 115; /// @dev record of all cross margin accounts mapping(address => CrossMarginAccount) internal marginAccounts; /// @dev total token caps mapping(address => uint256) public tokenCaps; /// @dev tracks total of short positions per token mapping(address => uint256) public totalShort; /// @dev tracks total of long positions per token mapping(address => uint256) public totalLong; uint256 public coolingOffPeriod = 10; /// @dev add an asset to be held by account function addHolding( CrossMarginAccount storage account, address token, uint256 depositAmount ) internal { if (!hasHoldingToken(account, token)) { account.holdingTokens.push(token); account.holdsToken[token] = true; } account.holdings[token] += depositAmount; } /// @dev adjust account to reflect borrowing of token amount function borrow( CrossMarginAccount storage account, address borrowToken, uint256 borrowAmount ) internal { if (!hasBorrowedToken(account, borrowToken)) { account.borrowTokens.push(borrowToken); account.borrowedYieldQuotientsFP[borrowToken] = Lending(lending()) .getUpdatedBorrowYieldAccuFP(borrowToken); account.borrowed[borrowToken] = borrowAmount; } else { (uint256 oldBorrowed, uint256 accumulatorFP) = Lending(lending()).applyBorrowInterest( account.borrowed[borrowToken], borrowToken, account.borrowedYieldQuotientsFP[borrowToken] ); account.borrowedYieldQuotientsFP[borrowToken] = accumulatorFP; account.borrowed[borrowToken] = oldBorrowed + borrowAmount; } require(positiveBalance(account), "Insufficient balance"); } /// @dev checks whether account is in the black, deposit + earnings relative to borrowed function positiveBalance(CrossMarginAccount storage account) internal returns (bool) { uint256 loan = loanInPeg(account); uint256 holdings = holdingsInPeg(account); // The following condition should hold: // holdings / loan >= leveragePercent / (leveragePercent - 100) // => return holdings * (leveragePercent - 100) >= loan * leveragePercent; } /// @dev internal function adjusting holding and borrow balances when debt extinguished function extinguishDebt( CrossMarginAccount storage account, address debtToken, uint256 extinguishAmount ) internal { // will throw if insufficient funds (uint256 borrowAmount, uint256 newYieldQuot) = Lending(lending()).applyBorrowInterest( account.borrowed[debtToken], debtToken, account.borrowedYieldQuotientsFP[debtToken] ); uint256 newBorrowAmount = borrowAmount - extinguishAmount; account.borrowed[debtToken] = newBorrowAmount; if (newBorrowAmount > 0) { account.borrowedYieldQuotientsFP[debtToken] = newYieldQuot; } else { delete account.borrowedYieldQuotientsFP[debtToken]; bool decrement = false; uint256 len = account.borrowTokens.length; for (uint256 i; len > i; i++) { address currToken = account.borrowTokens[i]; if (currToken == debtToken) { decrement = true; } else if (decrement) { account.borrowTokens[i - 1] = currToken; } } account.borrowTokens.pop(); } } /// @dev checks whether an account holds a token function hasHoldingToken(CrossMarginAccount storage account, address token) internal view returns (bool) { return account.holdsToken[token]; } /// @dev checks whether an account has borrowed a token function hasBorrowedToken(CrossMarginAccount storage account, address token) internal view returns (bool) { return account.borrowedYieldQuotientsFP[token] > 0; } /// @dev calculate total loan in reference currency, including compound interest function loanInPeg(CrossMarginAccount storage account) internal returns (uint256) { return sumTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); } /// @dev total of assets of account, expressed in reference currency function holdingsInPeg(CrossMarginAccount storage account) internal returns (uint256) { return sumTokensInPeg(account.holdingTokens, account.holdings); } /// @dev check whether an account can/should be liquidated function belowMaintenanceThreshold(CrossMarginAccount storage account) internal returns (bool) { uint256 loan = loanInPeg(account); uint256 holdings = holdingsInPeg(account); // The following should hold: // holdings / loan >= 1.1 // => holdings >= loan * 1.1 return 100 * holdings < liquidationThresholdPercent * loan; } /// @dev go through list of tokens and their amounts, summing up function sumTokensInPeg( address[] storage tokens, mapping(address => uint256) storage amounts ) internal returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += PriceAware.getCurrentPriceInPeg(token, amounts[token]); } } /// @dev go through list of tokens and their amounts, summing up function viewTokensInPeg( address[] storage tokens, mapping(address => uint256) storage amounts ) internal view returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += PriceAware.viewCurrentPriceInPeg(token, amounts[token]); } } /// @dev go through list of tokens and ammounts, summing up with interest function sumTokensInPegWithYield( address[] storage tokens, mapping(address => uint256) storage amounts, mapping(address => uint256) storage yieldQuotientsFP ) internal returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += yieldTokenInPeg( token, amounts[token], yieldQuotientsFP ); } } /// @dev go through list of tokens and ammounts, summing up with interest function viewTokensInPegWithYield( address[] storage tokens, mapping(address => uint256) storage amounts, mapping(address => uint256) storage yieldQuotientsFP ) internal view returns (uint256 totalPeg) { uint256 len = tokens.length; for (uint256 tokenId; tokenId < len; tokenId++) { address token = tokens[tokenId]; totalPeg += viewYieldTokenInPeg( token, amounts[token], yieldQuotientsFP ); } } /// @dev calculate yield for token amount and convert to reference currency function yieldTokenInPeg( address token, uint256 amount, mapping(address => uint256) storage yieldQuotientsFP ) internal returns (uint256) { uint256 yieldFP = Lending(lending()).viewAccumulatedBorrowingYieldFP(token); // 1 * FP / FP = 1 uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token]; return PriceAware.getCurrentPriceInPeg(token, amountInToken); } /// @dev calculate yield for token amount and convert to reference currency function viewYieldTokenInPeg( address token, uint256 amount, mapping(address => uint256) storage yieldQuotientsFP ) internal view returns (uint256) { uint256 yieldFP = Lending(lending()).viewAccumulatedBorrowingYieldFP(token); // 1 * FP / FP = 1 uint256 amountInToken = (amount * yieldFP) / yieldQuotientsFP[token]; return PriceAware.viewCurrentPriceInPeg(token, amountInToken); } /// @dev move tokens from one holding to another function adjustAmounts( CrossMarginAccount storage account, address fromToken, address toToken, uint256 soldAmount, uint256 boughtAmount ) internal { account.holdings[fromToken] = account.holdings[fromToken] - soldAmount; addHolding(account, toToken, boughtAmount); } /// sets borrow and holding to zero function deleteAccount(CrossMarginAccount storage account) internal { uint256 len = account.borrowTokens.length; for (uint256 borrowIdx; len > borrowIdx; borrowIdx++) { address borrowToken = account.borrowTokens[borrowIdx]; totalShort[borrowToken] -= account.borrowed[borrowToken]; account.borrowed[borrowToken] = 0; account.borrowedYieldQuotientsFP[borrowToken] = 0; } len = account.holdingTokens.length; for (uint256 holdingIdx; len > holdingIdx; holdingIdx++) { address holdingToken = account.holdingTokens[holdingIdx]; totalLong[holdingToken] -= account.holdings[holdingToken]; account.holdings[holdingToken] = 0; account.holdsToken[holdingToken] = false; } delete account.borrowTokens; delete account.holdingTokens; } /// @dev minimum function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return b; } else { return a; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./CrossMarginAccounts.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @title Handles liquidation of accounts below maintenance threshold @notice Liquidation can be called by the authorized staker, as determined in the Admin contract. If the authorized staker is delinquent, other participants can jump in and attack, taking their fees and potentially even their stake, depending how delinquent the responsible authorized staker is. */ abstract contract CrossMarginLiquidation is CrossMarginAccounts { event LiquidationShortfall(uint256 amount); event AccountLiquidated(address account); struct Liquidation { uint256 buy; uint256 sell; uint256 blockNum; } /// record kept around until a stake attacker can claim their reward struct AccountLiqRecord { uint256 blockNum; address loser; uint256 amount; address stakeAttacker; } mapping(address => Liquidation) liquidationAmounts; address[] internal liquidationTokens; address[] internal tradersToLiquidate; mapping(address => uint256) public maintenanceFailures; mapping(address => AccountLiqRecord) public stakeAttackRecords; uint256 public avgLiquidationPerCall = 10; uint256 public liqStakeAttackWindow = 5; uint256 public MAINTAINER_CUT_PERCENT = 5; uint256 public failureThreshold = 10; /// Set failure threshold function setFailureThreshold(uint256 threshFactor) external onlyOwnerExec { failureThreshold = threshFactor; } /// Set liquidity stake attack window function setLiqStakeAttackWindow(uint256 window) external onlyOwnerExec { liqStakeAttackWindow = window; } /// Set maintainer's percent cut function setMaintainerCutPercent(uint256 cut) external onlyOwnerExec { MAINTAINER_CUT_PERCENT = cut; } /// @dev calcLiquidationAmounts does a number of tasks in this contract /// and some of them are not straightforward. /// First of all it aggregates liquidation amounts, /// as well as which traders are ripe for liquidation, in storage (not in memory) /// owing to the fact that arrays can't be pushed to and hash maps don't /// exist in memory. /// Then it also returns any stake attack funds if the stake was unsuccessful /// (i.e. current caller is authorized). Also see context below. function calcLiquidationAmounts( address[] memory liquidationCandidates, bool isAuthorized ) internal returns (uint256 attackReturns) { liquidationTokens = new address[](0); tradersToLiquidate = new address[](0); for ( uint256 traderIndex = 0; liquidationCandidates.length > traderIndex; traderIndex++ ) { address traderAddress = liquidationCandidates[traderIndex]; CrossMarginAccount storage account = marginAccounts[traderAddress]; if (belowMaintenanceThreshold(account)) { tradersToLiquidate.push(traderAddress); uint256 len = account.holdingTokens.length; for (uint256 sellIdx = 0; len > sellIdx; sellIdx++) { address token = account.holdingTokens[sellIdx]; Liquidation storage liquidation = liquidationAmounts[token]; if (liquidation.blockNum != block.number) { liquidation.sell = account.holdings[token]; liquidation.buy = 0; liquidation.blockNum = block.number; liquidationTokens.push(token); } else { liquidation.sell += account.holdings[token]; } } len = account.borrowTokens.length; for (uint256 buyIdx = 0; len > buyIdx; buyIdx++) { address token = account.borrowTokens[buyIdx]; Liquidation storage liquidation = liquidationAmounts[token]; (uint256 loanAmount, ) = Lending(lending()).applyBorrowInterest( account.borrowed[token], token, account.borrowedYieldQuotientsFP[token] ); Lending(lending()).payOff(token, loanAmount); if (liquidation.blockNum != block.number) { liquidation.sell = 0; liquidation.buy = loanAmount; liquidation.blockNum = block.number; liquidationTokens.push(token); } else { liquidation.buy += loanAmount; } } } AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[traderAddress]; if (isAuthorized) { attackReturns += _disburseLiqAttack(liqAttackRecord); } } } function _disburseLiqAttack(AccountLiqRecord storage liqAttackRecord) internal returns (uint256 returnAmount) { if (liqAttackRecord.amount > 0) { // validate attack records, if any uint256 blockDiff = min( block.number - liqAttackRecord.blockNum, liqStakeAttackWindow ); uint256 attackerCut = (liqAttackRecord.amount * blockDiff) / liqStakeAttackWindow; Fund(fund()).withdraw( PriceAware.peg, liqAttackRecord.stakeAttacker, attackerCut ); Admin a = Admin(admin()); uint256 penalty = (a.maintenanceStakePerBlock() * attackerCut) / avgLiquidationPerCall; a.penalizeMaintenanceStake( liqAttackRecord.loser, penalty, liqAttackRecord.stakeAttacker ); // return remainder, after cut was taken to authorized stakekr returnAmount = liqAttackRecord.amount - attackerCut; } } /// Disburse liquidity stake attacks function disburseLiqStakeAttacks(address[] memory liquidatedAccounts) external { for (uint256 i = 0; liquidatedAccounts.length > i; i++) { address liqAccount = liquidatedAccounts[i]; AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[liqAccount]; if ( block.number > liqAttackRecord.blockNum + liqStakeAttackWindow ) { _disburseLiqAttack(liqAttackRecord); delete stakeAttackRecords[liqAccount]; } } } function liquidateFromPeg() internal returns (uint256 pegAmount) { uint256 len = liquidationTokens.length; for (uint256 tokenIdx = 0; len > tokenIdx; tokenIdx++) { address buyToken = liquidationTokens[tokenIdx]; Liquidation storage liq = liquidationAmounts[buyToken]; if (liq.buy > liq.sell) { pegAmount += PriceAware.liquidateFromPeg( buyToken, liq.buy - liq.sell ); delete liquidationAmounts[buyToken]; } } } function liquidateToPeg() internal returns (uint256 pegAmount) { uint256 len = liquidationTokens.length; for (uint256 tokenIndex = 0; len > tokenIndex; tokenIndex++) { address token = liquidationTokens[tokenIndex]; Liquidation storage liq = liquidationAmounts[token]; if (liq.sell > liq.buy) { uint256 sellAmount = liq.sell - liq.buy; pegAmount += PriceAware.liquidateToPeg(token, sellAmount); delete liquidationAmounts[token]; } } } function maintainerIsFailing() internal view returns (bool) { (address currentMaintainer, ) = Admin(admin()).viewCurrentMaintenanceStaker(); return maintenanceFailures[currentMaintainer] > failureThreshold * avgLiquidationPerCall; } /// called by maintenance stakers to liquidate accounts below liquidation threshold function liquidate(address[] memory liquidationCandidates) external noIntermediary returns (uint256 maintainerCut) { bool isAuthorized = Admin(admin()).isAuthorizedStaker(msg.sender); bool canTakeNow = isAuthorized || maintainerIsFailing(); // calcLiquidationAmounts does a lot of the work here // * aggregates both sell and buy side targets to be liquidated // * returns attacker cuts to them // * aggregates any returned fees from unauthorized (attacking) attempts maintainerCut = calcLiquidationAmounts( liquidationCandidates, isAuthorized ); uint256 sale2pegAmount = liquidateToPeg(); uint256 peg2targetCost = liquidateFromPeg(); delete liquidationTokens; // this may be a bit imprecise, since individual shortfalls may be obscured // by overall returns and the maintainer cut is taken out of the net total, // but it gives us the general picture uint256 costWithCut = (peg2targetCost * (100 + MAINTAINER_CUT_PERCENT)) / 100; if (costWithCut > sale2pegAmount) { emit LiquidationShortfall(costWithCut - sale2pegAmount); canTakeNow = canTakeNow && IERC20(peg).balanceOf(fund()) > costWithCut; } address loser = address(0); if (!canTakeNow) { // whoever is the current responsible maintenance staker // and liable to lose their stake loser = Admin(admin()).getUpdatedCurrentStaker(); } // iterate over traders and send back their money // as well as giving attackers their due, in case caller isn't authorized for ( uint256 traderIdx = 0; tradersToLiquidate.length > traderIdx; traderIdx++ ) { address traderAddress = tradersToLiquidate[traderIdx]; CrossMarginAccount storage account = marginAccounts[traderAddress]; uint256 holdingsValue = holdingsInPeg(account); uint256 borrowValue = loanInPeg(account); // 5% of value borrowed uint256 maintainerCut4Account = (borrowValue * MAINTAINER_CUT_PERCENT) / 100; maintainerCut += maintainerCut4Account; if (!canTakeNow) { // This could theoretically lead to a previous attackers // record being overwritten, but only if the trader restarts // their account and goes back into the red within the short time window // which would be a costly attack requiring collusion without upside AccountLiqRecord storage liqAttackRecord = stakeAttackRecords[traderAddress]; liqAttackRecord.amount = maintainerCut4Account; liqAttackRecord.stakeAttacker = msg.sender; liqAttackRecord.blockNum = block.number; liqAttackRecord.loser = loser; } // send back trader money // include 1% for protocol uint256 forfeited = maintainerCut4Account + (borrowValue * 101) / 100; if (holdingsValue > forfeited) { // send remaining funds back to trader Fund(fund()).withdraw( PriceAware.peg, traderAddress, holdingsValue - forfeited ); } emit AccountLiquidated(traderAddress); deleteAccount(account); } avgLiquidationPerCall = (avgLiquidationPerCall * 99 + maintainerCut) / 100; if (canTakeNow) { Fund(fund()).withdraw(PriceAware.peg, msg.sender, maintainerCut); } address currentMaintainer = Admin(admin()).getUpdatedCurrentStaker(); if (isAuthorized) { if (maintenanceFailures[currentMaintainer] > maintainerCut) { maintenanceFailures[currentMaintainer] -= maintainerCut; } else { maintenanceFailures[currentMaintainer] = 0; } } else { maintenanceFailures[currentMaintainer] += maintainerCut; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./Fund.sol"; import "./Lending.sol"; import "./RoleAware.sol"; import "./CrossMarginLiquidation.sol"; // Goal: all external functions only accessible to margintrader role // except for view functions of course contract CrossMarginTrading is CrossMarginLiquidation, IMarginTrading { constructor(address _peg, address _roles) RoleAware(_roles) PriceAware(_peg) {} /// @dev admin function to set the token cap function setTokenCap(address token, uint256 cap) external onlyOwnerExecActivator { tokenCaps[token] = cap; } /// @dev setter for cooling off period for withdrawing funds after deposit function setCoolingOffPeriod(uint256 blocks) external onlyOwnerExec { coolingOffPeriod = blocks; } /// @dev admin function to set leverage function setLeveragePercent(uint256 _leveragePercent) external onlyOwnerExec { leveragePercent = _leveragePercent; } /// @dev admin function to set liquidation threshold function setLiquidationThresholdPercent(uint256 threshold) external onlyOwnerExec { liquidationThresholdPercent = threshold; } /// @dev gets called by router to affirm a deposit to an account function registerDeposit( address trader, address token, uint256 depositAmount ) external override returns (uint256 extinguishableDebt) { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; account.lastDepositBlock = block.number; if (account.borrowed[token] > 0) { extinguishableDebt = min(depositAmount, account.borrowed[token]); extinguishDebt(account, token, extinguishableDebt); totalShort[token] -= extinguishableDebt; } // no overflow because depositAmount >= extinguishableDebt uint256 addedHolding = depositAmount - extinguishableDebt; _registerDeposit(account, token, addedHolding); } function _registerDeposit( CrossMarginAccount storage account, address token, uint256 addedHolding ) internal { addHolding(account, token, addedHolding); totalLong[token] += addedHolding; require( tokenCaps[token] >= totalLong[token], "Exceeds global token cap" ); } /// @dev gets called by router to affirm borrowing event function registerBorrow( address trader, address borrowToken, uint256 borrowAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; addHolding(account, borrowToken, borrowAmount); _registerBorrow(account, borrowToken, borrowAmount); } function _registerBorrow( CrossMarginAccount storage account, address borrowToken, uint256 borrowAmount ) internal { totalShort[borrowToken] += borrowAmount; totalLong[borrowToken] += borrowAmount; require( tokenCaps[borrowToken] >= totalShort[borrowToken] && tokenCaps[borrowToken] >= totalLong[borrowToken], "Exceeds global token cap" ); borrow(account, borrowToken, borrowAmount); } /// @dev gets called by router to affirm withdrawal of tokens from account function registerWithdrawal( address trader, address withdrawToken, uint256 withdrawAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; _registerWithdrawal(account, withdrawToken, withdrawAmount); } function _registerWithdrawal( CrossMarginAccount storage account, address withdrawToken, uint256 withdrawAmount ) internal { require( block.number > account.lastDepositBlock + coolingOffPeriod, "No withdrawal soon after deposit" ); totalLong[withdrawToken] -= withdrawAmount; // throws on underflow account.holdings[withdrawToken] = account.holdings[withdrawToken] - withdrawAmount; require(positiveBalance(account), "Insufficient balance"); } /// @dev overcollateralized borrowing on a cross margin account, called by router function registerOvercollateralizedBorrow( address trader, address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; _registerDeposit(account, depositToken, depositAmount); _registerBorrow(account, borrowToken, withdrawAmount); _registerWithdrawal(account, borrowToken, withdrawAmount); account.lastDepositBlock = block.number; } /// @dev gets called by router to register a trade and borrow and extinguish as necessary function registerTradeAndBorrow( address trader, address tokenFrom, address tokenTo, uint256 inAmount, uint256 outAmount ) external override returns (uint256 extinguishableDebt, uint256 borrowAmount) { require(isMarginTrader(msg.sender), "Calling contr. not an authorized"); CrossMarginAccount storage account = marginAccounts[trader]; if (account.borrowed[tokenTo] > 0) { extinguishableDebt = min(outAmount, account.borrowed[tokenTo]); extinguishDebt(account, tokenTo, extinguishableDebt); totalShort[tokenTo] -= extinguishableDebt; } uint256 sellAmount = inAmount; uint256 fromHoldings = account.holdings[tokenFrom]; if (inAmount > fromHoldings) { sellAmount = fromHoldings; /// won't overflow borrowAmount = inAmount - sellAmount; } if (inAmount > borrowAmount) { totalLong[tokenFrom] -= inAmount - borrowAmount; } if (outAmount > extinguishableDebt) { totalLong[tokenTo] += outAmount - extinguishableDebt; } require( tokenCaps[tokenTo] >= totalLong[tokenTo], "Exceeds global token cap" ); adjustAmounts( account, tokenFrom, tokenTo, sellAmount, outAmount - extinguishableDebt ); if (borrowAmount > 0) { totalShort[tokenFrom] += borrowAmount; require( tokenCaps[tokenFrom] >= totalShort[tokenFrom], "Exceeds global token cap" ); borrow(account, tokenFrom, borrowAmount); } } /// @dev can get called by router to register the dissolution of an account function registerLiquidation(address trader) external override { require(isMarginTrader(msg.sender), "Calling contr. not authorized"); CrossMarginAccount storage account = marginAccounts[trader]; require(loanInPeg(account) == 0, "Can't liquidate: borrowing"); deleteAccount(account); } /// @dev currently holding in this token function viewBalanceInToken(address trader, address token) external view returns (uint256) { CrossMarginAccount storage account = marginAccounts[trader]; return account.holdings[token]; } /// @dev view function to display account held assets state function getHoldingAmounts(address trader) external view override returns ( address[] memory holdingTokens, uint256[] memory holdingAmounts ) { CrossMarginAccount storage account = marginAccounts[trader]; holdingTokens = account.holdingTokens; holdingAmounts = new uint256[](account.holdingTokens.length); for (uint256 idx = 0; holdingTokens.length > idx; idx++) { address tokenAddress = holdingTokens[idx]; holdingAmounts[idx] = account.holdings[tokenAddress]; } } /// @dev view function to display account borrowing state function getBorrowAmounts(address trader) external view override returns (address[] memory borrowTokens, uint256[] memory borrowAmounts) { CrossMarginAccount storage account = marginAccounts[trader]; borrowTokens = account.borrowTokens; borrowAmounts = new uint256[](account.borrowTokens.length); for (uint256 idx = 0; borrowTokens.length > idx; idx++) { address tokenAddress = borrowTokens[idx]; borrowAmounts[idx] = Lending(lending()).viewWithBorrowInterest( account.borrowed[tokenAddress], tokenAddress, account.borrowedYieldQuotientsFP[tokenAddress] ); } } /// @dev view function to get loan amount in peg function viewLoanInPeg(address trader) external view returns (uint256 amount) { CrossMarginAccount storage account = marginAccounts[trader]; return viewTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); } /// @dev total of assets of account, expressed in reference currency function viewHoldingsInPeg(address trader) external view returns (uint256) { CrossMarginAccount storage account = marginAccounts[trader]; return viewTokensInPeg(account.holdingTokens, account.holdings); } /// @dev can this trader be liquidated? function canBeLiquidated(address trader) external view returns (bool) { CrossMarginAccount storage account = marginAccounts[trader]; uint256 loan = viewTokensInPegWithYield( account.borrowTokens, account.borrowed, account.borrowedYieldQuotientsFP ); uint256 holdings = viewTokensInPeg(account.holdingTokens, account.holdings); return liquidationThresholdPercent * loan >= 100 * holdings; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IWETH.sol"; import "./RoleAware.sol"; /// @title Manage funding contract Fund is RoleAware { using SafeERC20 for IERC20; /// wrapped ether address public immutable WETH; constructor(address _WETH, address _roles) RoleAware(_roles) { WETH = _WETH; } /// Deposit an active token function deposit(address depositToken, uint256 depositAmount) external { IERC20(depositToken).safeTransferFrom( msg.sender, address(this), depositAmount ); } /// Deposit token on behalf of `sender` function depositFor( address sender, address depositToken, uint256 depositAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized deposit"); IERC20(depositToken).safeTransferFrom( sender, address(this), depositAmount ); } /// Deposit to wrapped ether function depositToWETH() external payable { IWETH(WETH).deposit{value: msg.value}(); } // withdrawers role function withdraw( address withdrawalToken, address recipient, uint256 withdrawalAmount ) external { require(isFundTransferer(msg.sender), "Unauthorized withdraw"); IERC20(withdrawalToken).safeTransfer(recipient, withdrawalAmount); } // withdrawers role function withdrawETH(address recipient, uint256 withdrawalAmount) external { require(isFundTransferer(msg.sender), "Unauthorized withdraw"); IWETH(WETH).withdraw(withdrawalAmount); Address.sendValue(payable(recipient), withdrawalAmount); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./BaseLending.sol"; struct HourlyBond { uint256 amount; uint256 yieldQuotientFP; uint256 moduloHour; } /// @title Here we offer subscriptions to auto-renewing hourly bonds /// Funds are locked in for an 50 minutes per hour, while interest rates float abstract contract HourlyBondSubscriptionLending is BaseLending { mapping(address => YieldAccumulator) hourlyBondYieldAccumulators; uint256 constant RATE_UPDATE_WINDOW = 10 minutes; uint256 public withdrawalWindow = 20 minutes; uint256 constant MAX_HOUR_UPDATE = 4; // issuer => holder => bond record mapping(address => mapping(address => HourlyBond)) public hourlyBondAccounts; uint256 public borrowingFactorPercent = 200; uint256 constant borrowMinAPR = 6; uint256 constant borrowMinHourlyYield = FP48 + (borrowMinAPR * FP48) / 100 / hoursPerYear; function _makeHourlyBond( address issuer, address holder, uint256 amount ) internal { HourlyBond storage bond = hourlyBondAccounts[issuer][holder]; updateHourlyBondAmount(issuer, bond); YieldAccumulator storage yieldAccumulator = hourlyBondYieldAccumulators[issuer]; bond.yieldQuotientFP = yieldAccumulator.accumulatorFP; if (bond.amount == 0) { bond.moduloHour = block.timestamp % (1 hours); } bond.amount += amount; lendingMeta[issuer].totalLending += amount; } function updateHourlyBondAmount(address issuer, HourlyBond storage bond) internal { uint256 yieldQuotientFP = bond.yieldQuotientFP; if (yieldQuotientFP > 0) { YieldAccumulator storage yA = getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); uint256 oldAmount = bond.amount; bond.amount = applyInterest( bond.amount, yA.accumulatorFP, yieldQuotientFP ); uint256 deltaAmount = bond.amount - oldAmount; lendingMeta[issuer].totalLending += deltaAmount; } } // Retrieves bond balance for issuer and holder function viewHourlyBondAmount(address issuer, address holder) public view returns (uint256) { HourlyBond storage bond = hourlyBondAccounts[issuer][holder]; uint256 yieldQuotientFP = bond.yieldQuotientFP; uint256 cumulativeYield = viewCumulativeYieldFP( hourlyBondYieldAccumulators[issuer], block.timestamp ); if (yieldQuotientFP > 0) { return applyInterest(bond.amount, cumulativeYield, yieldQuotientFP); } else { return bond.amount; } } function _withdrawHourlyBond( address issuer, HourlyBond storage bond, uint256 amount ) internal { // how far the current hour has advanced (relative to acccount hourly clock) uint256 currentOffset = (block.timestamp - bond.moduloHour) % (1 hours); require( withdrawalWindow >= currentOffset, "Tried withdrawing outside subscription cancellation time window" ); bond.amount -= amount; lendingMeta[issuer].totalLending -= amount; } function calcCumulativeYieldFP( YieldAccumulator storage yieldAccumulator, uint256 timeDelta ) internal view returns (uint256 accumulatorFP) { uint256 secondsDelta = timeDelta % (1 hours); // linearly interpolate interest for seconds // FP * FP * 1 / (FP * 1) = FP accumulatorFP = yieldAccumulator.accumulatorFP + (yieldAccumulator.accumulatorFP * (yieldAccumulator.hourlyYieldFP - FP48) * secondsDelta) / (FP48 * 1 hours); uint256 hoursDelta = timeDelta / (1 hours); if (hoursDelta > 0) { uint256 accumulatorBeforeFP = accumulatorFP; for (uint256 i = 0; hoursDelta > i && MAX_HOUR_UPDATE > i; i++) { // FP48 * FP48 / FP48 = FP48 accumulatorFP = (accumulatorFP * yieldAccumulator.hourlyYieldFP) / FP48; } // a lot of time has passed if (hoursDelta > MAX_HOUR_UPDATE) { // apply interest in non-compounding way accumulatorFP += ((accumulatorFP - accumulatorBeforeFP) * (hoursDelta - MAX_HOUR_UPDATE)) / MAX_HOUR_UPDATE; } } } /// @dev updates yield accumulators for both borrowing and lending /// issuer address represents a token function updateHourlyYield(address issuer) public returns (uint256 hourlyYield) { return getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ) .hourlyYieldFP; } /// @dev updates yield accumulators for both borrowing and lending function getUpdatedHourlyYield( address issuer, YieldAccumulator storage accumulator, uint256 window ) internal returns (YieldAccumulator storage) { uint256 lastUpdated = accumulator.lastUpdated; uint256 timeDelta = (block.timestamp - lastUpdated); if (timeDelta > window) { YieldAccumulator storage borrowAccumulator = borrowYieldAccumulators[issuer]; accumulator.accumulatorFP = calcCumulativeYieldFP( accumulator, timeDelta ); LendingMetadata storage meta = lendingMeta[issuer]; accumulator.hourlyYieldFP = currentLendingRateFP( meta.totalLending, meta.totalBorrowed ); accumulator.lastUpdated = block.timestamp; updateBorrowYieldAccu(borrowAccumulator); borrowAccumulator.hourlyYieldFP = max( borrowMinHourlyYield, FP48 + (borrowingFactorPercent * (accumulator.hourlyYieldFP - FP48)) / 100 ); } return accumulator; } function updateBorrowYieldAccu(YieldAccumulator storage borrowAccumulator) internal { uint256 timeDelta = block.timestamp - borrowAccumulator.lastUpdated; if (timeDelta > RATE_UPDATE_WINDOW) { borrowAccumulator.accumulatorFP = calcCumulativeYieldFP( borrowAccumulator, timeDelta ); borrowAccumulator.lastUpdated = block.timestamp; } } function getUpdatedBorrowYieldAccuFP(address issuer) external returns (uint256) { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; updateBorrowYieldAccu(yA); return yA.accumulatorFP; } function viewCumulativeYieldFP( YieldAccumulator storage yA, uint256 timestamp ) internal view returns (uint256) { uint256 timeDelta = (timestamp - yA.lastUpdated); if (timeDelta > RATE_UPDATE_WINDOW) { return calcCumulativeYieldFP(yA, timeDelta); } else { return yA.accumulatorFP; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Fund.sol"; import "./HourlyBondSubscriptionLending.sol"; import "../libraries/IncentiveReporter.sol"; // TODO activate bonds for lending /// @title Manage lending for a variety of bond issuers contract Lending is RoleAware, HourlyBondSubscriptionLending { /// mapping issuers to tokens /// (in crossmargin, the issuers are tokens themselves) mapping(address => address) public issuerTokens; /// In case of shortfall, adjust debt mapping(address => uint256) public haircuts; /// map of available issuers mapping(address => bool) public activeIssuers; uint256 constant BORROW_RATE_UPDATE_WINDOW = 60 minutes; constructor(address _roles) RoleAware(_roles) {} /// Make a issuer available for protocol function activateIssuer(address issuer) external { activateIssuer(issuer, issuer); } /// Make issuer != token available for protocol (isol. margin) function activateIssuer(address issuer, address token) public onlyOwnerExecActivator { activeIssuers[issuer] = true; issuerTokens[issuer] = token; } /// Remove a issuer from trading availability function deactivateIssuer(address issuer) external onlyOwnerExecActivator { activeIssuers[issuer] = false; } /// Set lending cap function setLendingCap(address issuer, uint256 cap) external onlyOwnerExecActivator { lendingMeta[issuer].lendingCap = cap; } /// Set withdrawal window function setWithdrawalWindow(uint256 window) external onlyOwnerExec { withdrawalWindow = window; } function setNormalRatePerPercent(uint256 rate) external onlyOwnerExec { normalRatePerPercent = rate; } function setHighRatePerPercent(uint256 rate) external onlyOwnerExec { highRatePerPercent = rate; } /// Set hourly yield APR for issuer function setHourlyYieldAPR(address issuer, uint256 aprPercent) external onlyOwnerExecActivator { YieldAccumulator storage yieldAccumulator = hourlyBondYieldAccumulators[issuer]; if (yieldAccumulator.accumulatorFP == 0) { uint256 yieldFP = FP48 + (FP48 * aprPercent) / 100 / (24 * 365); hourlyBondYieldAccumulators[issuer] = YieldAccumulator({ accumulatorFP: FP48, lastUpdated: block.timestamp, hourlyYieldFP: yieldFP }); } else { YieldAccumulator storage yA = getUpdatedHourlyYield( issuer, yieldAccumulator, RATE_UPDATE_WINDOW ); yA.hourlyYieldFP = (FP48 * (100 + aprPercent)) / 100 / (24 * 365); } } /// @dev how much interest has accrued to a borrowed balance over time function applyBorrowInterest( uint256 balance, address issuer, uint256 yieldQuotientFP ) external returns (uint256 balanceWithInterest, uint256 accumulatorFP) { require(isBorrower(msg.sender), "Not approved call"); YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; updateBorrowYieldAccu(yA); accumulatorFP = yA.accumulatorFP; balanceWithInterest = applyInterest( balance, accumulatorFP, yieldQuotientFP ); uint256 deltaAmount = balanceWithInterest - balance; LendingMetadata storage meta = lendingMeta[issuer]; meta.totalBorrowed += deltaAmount; } /// @dev view function to get balance with borrowing interest applied function viewWithBorrowInterest( uint256 balance, address issuer, uint256 yieldQuotientFP ) external view returns (uint256) { uint256 accumulatorFP = viewCumulativeYieldFP( borrowYieldAccumulators[issuer], block.timestamp ); return applyInterest(balance, accumulatorFP, yieldQuotientFP); } /// @dev gets called by router to register if a trader borrows issuers function registerBorrow(address issuer, uint256 amount) external { require(isBorrower(msg.sender), "Not approved borrower"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalBorrowed += amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], BORROW_RATE_UPDATE_WINDOW ); require( meta.totalLending >= meta.totalBorrowed, "Insufficient lending" ); } /// @dev gets called when external sources provide lending function registerLend(address issuer, uint256 amount) external { require(isLender(msg.sender), "Not an approved lender"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalLending += amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); } /// @dev gets called when external sources pay withdraw their bobnd function registerWithdrawal(address issuer, uint256 amount) external { require(isLender(msg.sender), "Not an approved lender"); require(activeIssuers[issuer], "Not approved issuer"); LendingMetadata storage meta = lendingMeta[issuer]; meta.totalLending -= amount; getUpdatedHourlyYield( issuer, hourlyBondYieldAccumulators[issuer], RATE_UPDATE_WINDOW ); } /// @dev gets called by router if loan is extinguished function payOff(address issuer, uint256 amount) external { require(isBorrower(msg.sender), "Not approved borrower"); lendingMeta[issuer].totalBorrowed -= amount; } /// @dev get the borrow yield for a specific issuer/token function viewAccumulatedBorrowingYieldFP(address issuer) external view returns (uint256) { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; return viewCumulativeYieldFP(yA, block.timestamp); } function viewAPRPer10k(YieldAccumulator storage yA) internal view returns (uint256) { uint256 hourlyYieldFP = yA.hourlyYieldFP; uint256 aprFP = ((hourlyYieldFP * 10_000 - FP48 * 10_000) * 365 days) / (1 hours); return aprFP / FP48; } /// @dev get current borrowing interest per 10k for a token / issuer function viewBorrowAPRPer10k(address issuer) external view returns (uint256) { return viewAPRPer10k(borrowYieldAccumulators[issuer]); } /// @dev get current lending APR per 10k for a token / issuer function viewHourlyBondAPRPer10k(address issuer) external view returns (uint256) { return viewAPRPer10k(hourlyBondYieldAccumulators[issuer]); } /// @dev In a liquidity crunch make a fallback bond until liquidity is good again function makeFallbackBond( address issuer, address holder, uint256 amount ) external { require(isLender(msg.sender), "Not an approved lender"); _makeHourlyBond(issuer, holder, amount); } /// @dev withdraw an hour bond function withdrawHourlyBond(address issuer, uint256 amount) external { HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender]; // apply all interest updateHourlyBondAmount(issuer, bond); super._withdrawHourlyBond(issuer, bond, amount); if (bond.amount == 0) { delete hourlyBondAccounts[issuer][msg.sender]; } disburse(issuer, msg.sender, amount); IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount); } /// Shut down hourly bond account for `issuer` function closeHourlyBondAccount(address issuer) external { HourlyBond storage bond = hourlyBondAccounts[issuer][msg.sender]; // apply all interest updateHourlyBondAmount(issuer, bond); uint256 amount = bond.amount; super._withdrawHourlyBond(issuer, bond, amount); disburse(issuer, msg.sender, amount); delete hourlyBondAccounts[issuer][msg.sender]; IncentiveReporter.subtractFromClaimAmount(issuer, msg.sender, amount); } /// @dev buy hourly bond subscription function buyHourlyBondSubscription(address issuer, uint256 amount) external { require(activeIssuers[issuer], "Not approved issuer"); collectToken(issuer, msg.sender, amount); super._makeHourlyBond(issuer, msg.sender, amount); IncentiveReporter.addToClaimAmount(issuer, msg.sender, amount); } function initBorrowYieldAccumulator(address issuer) external onlyOwnerExecActivator { YieldAccumulator storage yA = borrowYieldAccumulators[issuer]; require(yA.accumulatorFP == 0, "don't re-initialize"); yA.accumulatorFP = FP48; yA.lastUpdated = block.timestamp; yA.hourlyYieldFP = FP48 + (FP48 * borrowMinAPR) / 100 / (365 * 24); } function setBorrowingFactorPercent(uint256 borrowingFactor) external onlyOwnerExec { borrowingFactorPercent = borrowingFactor; } function issuanceBalance(address issuer) internal view override returns (uint256) { address token = issuerTokens[issuer]; if (token == issuer) { // cross margin return IERC20(token).balanceOf(fund()); } else { return lendingMeta[issuer].totalLending - haircuts[issuer]; } } function disburse( address issuer, address recipient, uint256 amount ) internal { uint256 haircutAmount = haircuts[issuer]; if (haircutAmount > 0 && amount > 0) { uint256 totalLending = lendingMeta[issuer].totalLending; uint256 adjustment = (amount * min(totalLending, haircutAmount)) / totalLending; amount = amount - adjustment; haircuts[issuer] -= adjustment; } address token = issuerTokens[issuer]; Fund(fund()).withdraw(token, recipient, amount); } function collectToken( address issuer, address source, uint256 amount ) internal { Fund(fund()).depositFor(source, issuer, amount); } function haircut(uint256 amount) external { haircuts[msg.sender] += amount; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; import "../interfaces/IMarginTrading.sol"; import "./Lending.sol"; import "./Admin.sol"; import "./BaseRouter.sol"; import "../libraries/IncentiveReporter.sol"; /// @title Top level transaction controller contract MarginRouter is RoleAware, BaseRouter { event AccountUpdated(address indexed trader); uint256 public constant mswapFeesPer10k = 10; address public immutable WETH; constructor(address _WETH, address _roles) RoleAware(_roles) { WETH = _WETH; } /////////////////////////// // Cross margin endpoints /////////////////////////// /// @notice traders call this to deposit funds on cross margin function crossDeposit(address depositToken, uint256 depositAmount) external { Fund(fund()).depositFor(msg.sender, depositToken, depositAmount); uint256 extinguishAmount = IMarginTrading(crossMarginTrading()).registerDeposit( msg.sender, depositToken, depositAmount ); if (extinguishAmount > 0) { Lending(lending()).payOff(depositToken, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( depositToken, msg.sender, extinguishAmount ); } emit AccountUpdated(msg.sender); } /// @notice deposit wrapped ehtereum into cross margin account function crossDepositETH() external payable { Fund(fund()).depositToWETH{value: msg.value}(); uint256 extinguishAmount = IMarginTrading(crossMarginTrading()).registerDeposit( msg.sender, WETH, msg.value ); if (extinguishAmount > 0) { Lending(lending()).payOff(WETH, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( WETH, msg.sender, extinguishAmount ); } emit AccountUpdated(msg.sender); } /// @notice withdraw deposits/earnings from cross margin account function crossWithdraw(address withdrawToken, uint256 withdrawAmount) external { IMarginTrading(crossMarginTrading()).registerWithdrawal( msg.sender, withdrawToken, withdrawAmount ); Fund(fund()).withdraw(withdrawToken, msg.sender, withdrawAmount); emit AccountUpdated(msg.sender); } /// @notice withdraw ethereum from cross margin account function crossWithdrawETH(uint256 withdrawAmount) external { IMarginTrading(crossMarginTrading()).registerWithdrawal( msg.sender, WETH, withdrawAmount ); Fund(fund()).withdrawETH(msg.sender, withdrawAmount); emit AccountUpdated(msg.sender); } /// @notice borrow into cross margin trading account function crossBorrow(address borrowToken, uint256 borrowAmount) external { Lending(lending()).registerBorrow(borrowToken, borrowAmount); IMarginTrading(crossMarginTrading()).registerBorrow( msg.sender, borrowToken, borrowAmount ); IncentiveReporter.addToClaimAmount( borrowToken, msg.sender, borrowAmount ); emit AccountUpdated(msg.sender); } /// @notice convenience function to perform overcollateralized borrowing /// against a cross margin account. /// @dev caution: the account still has to have a positive balaance at the end /// of the withdraw. So an underwater account may not be able to withdraw function crossOvercollateralizedBorrow( address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external { Fund(fund()).depositFor(msg.sender, depositToken, depositAmount); Lending(lending()).registerBorrow(borrowToken, withdrawAmount); IMarginTrading(crossMarginTrading()).registerOvercollateralizedBorrow( msg.sender, depositToken, depositAmount, borrowToken, withdrawAmount ); Fund(fund()).withdraw(borrowToken, msg.sender, withdrawAmount); IncentiveReporter.addToClaimAmount( borrowToken, msg.sender, withdrawAmount ); emit AccountUpdated(msg.sender); } /// @notice close an account that is no longer borrowing and return gains function crossCloseAccount() external { (address[] memory holdingTokens, uint256[] memory holdingAmounts) = IMarginTrading(crossMarginTrading()).getHoldingAmounts(msg.sender); // requires all debts paid off IMarginTrading(crossMarginTrading()).registerLiquidation(msg.sender); for (uint256 i; holdingTokens.length > i; i++) { Fund(fund()).withdraw( holdingTokens[i], msg.sender, holdingAmounts[i] ); } emit AccountUpdated(msg.sender); } /// @notice entry point for swapping tokens held in cross margin account function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, bytes32 amms, address[] calldata tokens, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { // calc fees uint256 fees = takeFeesFromInput(amountIn); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( amountIn - fees, amms, tokens ); // checks that trader is within allowed lending bounds registerTrade( msg.sender, tokens[0], tokens[tokens.length - 1], amountIn, amounts[amounts.length - 1] ); _fundSwapExactT4T(amounts, amountOutMin, pairs, tokens); } /// @notice entry point for swapping tokens held in cross margin account function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens, uint256 deadline ) external ensure(deadline) returns (uint256[] memory amounts) { address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut + takeFeesFromOutput(amountOut), amms, tokens ); // checks that trader is within allowed lending bounds registerTrade( msg.sender, tokens[0], tokens[tokens.length - 1], amounts[0], amountOut ); _fundSwapT4ExactT(amounts, amountInMax, pairs, tokens); } /// @dev helper function does all the work of telling other contracts /// about a cross margin trade function registerTrade( address trader, address inToken, address outToken, uint256 inAmount, uint256 outAmount ) internal { (uint256 extinguishAmount, uint256 borrowAmount) = IMarginTrading(crossMarginTrading()).registerTradeAndBorrow( trader, inToken, outToken, inAmount, outAmount ); if (extinguishAmount > 0) { Lending(lending()).payOff(outToken, extinguishAmount); IncentiveReporter.subtractFromClaimAmount( outToken, trader, extinguishAmount ); } if (borrowAmount > 0) { Lending(lending()).registerBorrow(inToken, borrowAmount); IncentiveReporter.addToClaimAmount(inToken, trader, borrowAmount); } emit AccountUpdated(trader); } ///////////// // Helpers ///////////// /// @dev internal helper swapping exact token for token on AMM function _fundSwapExactT4T( uint256[] memory amounts, uint256 amountOutMin, address[] memory pairs, address[] calldata tokens ) internal { require( amounts[amounts.length - 1] >= amountOutMin, "MarginRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]); _swap(amounts, pairs, tokens, fund()); } /// @notice make swaps on AMM using protocol funds, only for authorized contracts function authorizedSwapExactT4T( uint256 amountIn, uint256 amountOutMin, bytes32 amms, address[] calldata tokens ) external returns (uint256[] memory amounts) { require( isAuthorizedFundTrader(msg.sender), "Calling contract is not authorized to trade with protocl funds" ); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsOut( amountIn, amms, tokens ); _fundSwapExactT4T(amounts, amountOutMin, pairs, tokens); } // @dev internal helper swapping exact token for token on on AMM function _fundSwapT4ExactT( uint256[] memory amounts, uint256 amountInMax, address[] memory pairs, address[] calldata tokens ) internal { require( amounts[0] <= amountInMax, "MarginRouter: EXCESSIVE_INPUT_AMOUNT" ); Fund(fund()).withdraw(tokens[0], pairs[0], amounts[0]); _swap(amounts, pairs, tokens, fund()); } //// @notice swap protocol funds on AMM, only for authorized function authorizedSwapT4ExactT( uint256 amountOut, uint256 amountInMax, bytes32 amms, address[] calldata tokens ) external returns (uint256[] memory amounts) { require( isAuthorizedFundTrader(msg.sender), "Calling contract is not authorized to trade with protocl funds" ); address[] memory pairs; (amounts, pairs) = UniswapStyleLib.getAmountsIn( amountOut, amms, tokens ); _fundSwapT4ExactT(amounts, amountInMax, pairs, tokens); } function takeFeesFromOutput(uint256 amount) internal pure returns (uint256 fees) { fees = (mswapFeesPer10k * amount) / 10_000; } function takeFeesFromInput(uint256 amount) internal pure returns (uint256 fees) { fees = (mswapFeesPer10k * amount) / (10_000 + mswapFeesPer10k); } function getAmountsOut( uint256 inAmount, bytes32 amms, address[] calldata tokens ) external view returns (uint256[] memory amounts) { (amounts, ) = UniswapStyleLib.getAmountsOut(inAmount, amms, tokens); } function getAmountsIn( uint256 outAmount, bytes32 amms, address[] calldata tokens ) external view returns (uint256[] memory amounts) { (amounts, ) = UniswapStyleLib.getAmountsIn(outAmount, amms, tokens); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./RoleAware.sol"; import "./MarginRouter.sol"; import "../libraries/UniswapStyleLib.sol"; /// Stores how many of token you could get for 1k of peg struct TokenPrice { uint256 lastUpdated; uint256 priceFP; address[] liquidationTokens; bytes32 amms; address[] inverseLiquidationTokens; bytes32 inverseAmms; } struct VolatilitySetting { uint256 priceUpdateWindow; uint256 updateRatePermil; uint256 voluntaryUpdateWindow; } struct PairPrice { uint256 cumulative; uint256 lastUpdated; uint256 priceFP; } /// @title The protocol features several mechanisms to prevent vulnerability to /// price manipulation: /// 1) global exposure caps on all tokens which need to be raised gradually /// during the process of introducing a new token, making attacks unprofitable /// due to lack of scale /// 2) Exponential moving average with cautious price update. Prices for estimating /// how much a trader can borrow need not be extremely current and precise, mainly /// they must be resilient against extreme manipulation /// 3) Liquidators may not call from a contract address, to prevent extreme forms of /// of front-running and other price manipulation. abstract contract PriceAware is RoleAware { uint256 constant FP112 = 2**112; address public immutable peg; mapping(address => TokenPrice) public tokenPrices; mapping(address => mapping(address => PairPrice)) public pairPrices; /// update window in blocks // TODO uint256 public priceUpdateWindow = 20 minutes; uint256 public voluntaryUpdateWindow = 5 minutes; uint256 public UPDATE_RATE_PERMIL = 400; VolatilitySetting[] public volatilitySettings; constructor(address _peg) { peg = _peg; } /// Set window for price updates function setPriceUpdateWindow(uint16 window, uint256 voluntaryWindow) external onlyOwnerExec { priceUpdateWindow = window; voluntaryUpdateWindow = voluntaryWindow; } /// Add a new volatility setting function addVolatilitySetting( uint256 _priceUpdateWindow, uint256 _updateRatePermil, uint256 _voluntaryUpdateWindow ) external onlyOwnerExec { volatilitySettings.push( VolatilitySetting({ priceUpdateWindow: _priceUpdateWindow, updateRatePermil: _updateRatePermil, voluntaryUpdateWindow: _voluntaryUpdateWindow }) ); } /// Choose a volatitlity setting function chooseVolatilitySetting(uint256 index) external onlyOwnerExecDisabler { VolatilitySetting storage vs = volatilitySettings[index]; if (vs.updateRatePermil > 0) { UPDATE_RATE_PERMIL = vs.updateRatePermil; priceUpdateWindow = vs.priceUpdateWindow; voluntaryUpdateWindow = vs.voluntaryUpdateWindow; } } /// Set rate for updates function setUpdateRate(uint256 rate) external onlyOwnerExec { UPDATE_RATE_PERMIL = rate; } function getCurrentPriceInPeg(address token, uint256 inAmount) internal returns (uint256) { return getCurrentPriceInPeg(token, inAmount, false); } function getCurrentPriceInPeg( address token, uint256 inAmount, bool voluntary ) public returns (uint256 priceInPeg) { if (token == peg) { return inAmount; } else { TokenPrice storage tokenPrice = tokenPrices[token]; uint256 timeDelta = block.timestamp - tokenPrice.lastUpdated; if ( timeDelta > priceUpdateWindow || tokenPrice.priceFP == 0 || (voluntary && timeDelta > voluntaryUpdateWindow) ) { // update the currently cached price uint256 priceUpdateFP; priceUpdateFP = getPriceByPairs( tokenPrice.liquidationTokens, tokenPrice.amms ); _setPriceVal(tokenPrice, priceUpdateFP, UPDATE_RATE_PERMIL); } priceInPeg = (inAmount * tokenPrice.priceFP) / FP112; } } /// Get view of current price of token in peg function viewCurrentPriceInPeg(address token, uint256 inAmount) public view returns (uint256 priceInPeg) { if (token == peg) { return inAmount; } else { TokenPrice storage tokenPrice = tokenPrices[token]; uint256 priceFP = tokenPrice.priceFP; priceInPeg = (inAmount * priceFP) / FP112; } } function _setPriceVal( TokenPrice storage tokenPrice, uint256 updateFP, uint256 weightPerMil ) internal { tokenPrice.priceFP = (tokenPrice.priceFP * (1000 - weightPerMil) + updateFP * weightPerMil) / 1000; tokenPrice.lastUpdated = block.timestamp; } /// add path from token to current liquidation peg function setLiquidationPath(bytes32 amms, address[] memory tokens) external onlyOwnerExecActivator { address token = tokens[0]; if (token != peg) { TokenPrice storage tokenPrice = tokenPrices[token]; tokenPrice.amms = amms; tokenPrice.liquidationTokens = tokens; tokenPrice.inverseLiquidationTokens = new address[](tokens.length); bytes32 inverseAmms; for (uint256 i = 0; tokens.length - 1 > i; i++) { initPairPrice(tokens[i], tokens[i + 1], amms[i]); bytes32 shifted = bytes32(amms[i]) >> ((tokens.length - 2 - i) * 8); inverseAmms = inverseAmms | shifted; } tokenPrice.inverseAmms = inverseAmms; for (uint256 i = 0; tokens.length > i; i++) { tokenPrice.inverseLiquidationTokens[i] = tokens[ tokens.length - i - 1 ]; } tokenPrice.priceFP = getPriceByPairs(tokens, amms); tokenPrice.lastUpdated = block.timestamp; } } function liquidateToPeg(address token, uint256 amount) internal returns (uint256) { if (token == peg) { return amount; } else { TokenPrice storage tP = tokenPrices[token]; uint256[] memory amounts = MarginRouter(marginRouter()).authorizedSwapExactT4T( amount, 0, tP.amms, tP.liquidationTokens ); uint256 outAmount = amounts[amounts.length - 1]; return outAmount; } } function liquidateFromPeg(address token, uint256 targetAmount) internal returns (uint256) { if (token == peg) { return targetAmount; } else { TokenPrice storage tP = tokenPrices[token]; uint256[] memory amounts = MarginRouter(marginRouter()).authorizedSwapT4ExactT( targetAmount, type(uint256).max, tP.amms, tP.inverseLiquidationTokens ); return amounts[0]; } } function getPriceByPairs(address[] memory tokens, bytes32 amms) internal returns (uint256 priceFP) { priceFP = FP112; for (uint256 i; i < tokens.length - 1; i++) { address inToken = tokens[i]; address outToken = tokens[i + 1]; address pair = amms[i] == 0 ? UniswapStyleLib.pairForUni(inToken, outToken) : UniswapStyleLib.pairForSushi(inToken, outToken); PairPrice storage pairPrice = pairPrices[pair][inToken]; (, , uint256 pairLastUpdated) = IUniswapV2Pair(pair).getReserves(); uint256 timeDelta = pairLastUpdated - pairPrice.lastUpdated; if (timeDelta > voluntaryUpdateWindow) { // we are in business (address token0, ) = UniswapStyleLib.sortTokens(inToken, outToken); uint256 cumulative = inToken == token0 ? IUniswapV2Pair(pair).price0CumulativeLast() : IUniswapV2Pair(pair).price1CumulativeLast(); uint256 pairPriceFP = (cumulative - pairPrice.cumulative) / timeDelta; priceFP = (priceFP * pairPriceFP) / FP112; pairPrice.priceFP = pairPriceFP; pairPrice.cumulative = cumulative; pairPrice.lastUpdated = pairLastUpdated; } else { priceFP = (priceFP * pairPrice.priceFP) / FP112; } } } function initPairPrice( address inToken, address outToken, bytes1 amm ) internal { address pair = amm == 0 ? UniswapStyleLib.pairForUni(inToken, outToken) : UniswapStyleLib.pairForSushi(inToken, outToken); PairPrice storage pairPrice = pairPrices[pair][inToken]; if (pairPrice.lastUpdated == 0) { (uint112 reserve0, uint112 reserve1, uint256 pairLastUpdated) = IUniswapV2Pair(pair).getReserves(); (address token0, ) = UniswapStyleLib.sortTokens(inToken, outToken); if (inToken == token0) { pairPrice.priceFP = (FP112 * reserve1) / reserve0; pairPrice.cumulative = IUniswapV2Pair(pair) .price0CumulativeLast(); } else { pairPrice.priceFP = (FP112 * reserve0) / reserve1; pairPrice.cumulative = IUniswapV2Pair(pair) .price1CumulativeLast(); } pairPrice.lastUpdated = block.timestamp; pairPrice.lastUpdated = pairLastUpdated; } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "./Roles.sol"; /// @title Role management behavior /// Main characters are for service discovery /// Whereas roles are for access control contract RoleAware { Roles public immutable roles; mapping(uint256 => address) public mainCharacterCache; mapping(address => mapping(uint256 => bool)) public roleCache; constructor(address _roles) { require(_roles != address(0), "Please provide valid roles address"); roles = Roles(_roles); } modifier noIntermediary() { require( msg.sender == tx.origin, "Currently no intermediaries allowed for this function call" ); _; } // @dev Throws if called by any account other than the owner or executor modifier onlyOwnerExec() { require( owner() == msg.sender || executor() == msg.sender, "Roles: caller is not the owner" ); _; } modifier onlyOwnerExecDisabler() { require( owner() == msg.sender || executor() == msg.sender || disabler() == msg.sender, "Caller is not the owner, executor or authorized disabler" ); _; } modifier onlyOwnerExecActivator() { require( owner() == msg.sender || executor() == msg.sender || isTokenActivator(msg.sender), "Caller is not the owner, executor or authorized activator" ); _; } function updateRoleCache(uint256 role, address contr) public virtual { roleCache[contr][role] = roles.getRole(role, contr); } function updateMainCharacterCache(uint256 role) public virtual { mainCharacterCache[role] = roles.mainCharacters(role); } function owner() internal view returns (address) { return roles.owner(); } function executor() internal returns (address) { return roles.executor(); } function disabler() internal view returns (address) { return mainCharacterCache[DISABLER]; } function fund() internal view returns (address) { return mainCharacterCache[FUND]; } function lending() internal view returns (address) { return mainCharacterCache[LENDING]; } function marginRouter() internal view returns (address) { return mainCharacterCache[MARGIN_ROUTER]; } function crossMarginTrading() internal view returns (address) { return mainCharacterCache[CROSS_MARGIN_TRADING]; } function feeController() internal view returns (address) { return mainCharacterCache[FEE_CONTROLLER]; } function price() internal view returns (address) { return mainCharacterCache[PRICE_CONTROLLER]; } function admin() internal view returns (address) { return mainCharacterCache[ADMIN]; } function incentiveDistributor() internal view returns (address) { return mainCharacterCache[INCENTIVE_DISTRIBUTION]; } function tokenAdmin() internal view returns (address) { return mainCharacterCache[TOKEN_ADMIN]; } function isBorrower(address contr) internal view returns (bool) { return roleCache[contr][BORROWER]; } function isFundTransferer(address contr) internal view returns (bool) { return roleCache[contr][FUND_TRANSFERER]; } function isMarginTrader(address contr) internal view returns (bool) { return roleCache[contr][MARGIN_TRADER]; } function isFeeSource(address contr) internal view returns (bool) { return roleCache[contr][FEE_SOURCE]; } function isMarginCaller(address contr) internal view returns (bool) { return roleCache[contr][MARGIN_CALLER]; } function isLiquidator(address contr) internal view returns (bool) { return roleCache[contr][LIQUIDATOR]; } function isAuthorizedFundTrader(address contr) internal view returns (bool) { return roleCache[contr][AUTHORIZED_FUND_TRADER]; } function isIncentiveReporter(address contr) internal view returns (bool) { return roleCache[contr][INCENTIVE_REPORTER]; } function isTokenActivator(address contr) internal view returns (bool) { return roleCache[contr][TOKEN_ACTIVATOR]; } function isStakePenalizer(address contr) internal view returns (bool) { return roleCache[contr][STAKE_PENALIZER]; } function isLender(address contr) internal view returns (bool) { return roleCache[contr][LENDER]; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IDependencyController.sol"; // we chose not to go with an enum // to make this list easy to extend uint256 constant FUND_TRANSFERER = 1; uint256 constant MARGIN_CALLER = 2; uint256 constant BORROWER = 3; uint256 constant MARGIN_TRADER = 4; uint256 constant FEE_SOURCE = 5; uint256 constant LIQUIDATOR = 6; uint256 constant AUTHORIZED_FUND_TRADER = 7; uint256 constant INCENTIVE_REPORTER = 8; uint256 constant TOKEN_ACTIVATOR = 9; uint256 constant STAKE_PENALIZER = 10; uint256 constant LENDER = 11; uint256 constant FUND = 101; uint256 constant LENDING = 102; uint256 constant MARGIN_ROUTER = 103; uint256 constant CROSS_MARGIN_TRADING = 104; uint256 constant FEE_CONTROLLER = 105; uint256 constant PRICE_CONTROLLER = 106; uint256 constant ADMIN = 107; uint256 constant INCENTIVE_DISTRIBUTION = 108; uint256 constant TOKEN_ADMIN = 109; uint256 constant DISABLER = 1001; uint256 constant DEPENDENCY_CONTROLLER = 1002; /// @title Manage permissions of contracts and ownership of everything /// owned by a multisig wallet (0xEED9D1c6B4cdEcB3af070D85bfd394E7aF179CBd) during /// beta and will then be transfered to governance /// https://github.com/marginswap/governance contract Roles is Ownable { mapping(address => mapping(uint256 => bool)) public roles; mapping(uint256 => address) public mainCharacters; constructor() Ownable() { // token activation from the get-go roles[msg.sender][TOKEN_ACTIVATOR] = true; } /// @dev Throws if called by any account other than the owner. modifier onlyOwnerExecDepController() { require( owner() == msg.sender || executor() == msg.sender || mainCharacters[DEPENDENCY_CONTROLLER] == msg.sender, "Roles: caller is not the owner" ); _; } function giveRole(uint256 role, address actor) external onlyOwnerExecDepController { roles[actor][role] = true; } function removeRole(uint256 role, address actor) external onlyOwnerExecDepController { roles[actor][role] = false; } function setMainCharacter(uint256 role, address actor) external onlyOwnerExecDepController { mainCharacters[role] = actor; } function getRole(uint256 role, address contr) external view returns (bool) { return roles[contr][role]; } /// @dev current executor function executor() public returns (address exec) { address depController = mainCharacters[DEPENDENCY_CONTROLLER]; if (depController != address(0)) { exec = IDependencyController(depController).currentExecutor(); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface IDependencyController { function currentExecutor() external returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface IMarginTrading { function registerDeposit( address trader, address token, uint256 amount ) external returns (uint256 extinguishAmount); function registerWithdrawal( address trader, address token, uint256 amount ) external; function registerBorrow( address trader, address token, uint256 amount ) external; function registerTradeAndBorrow( address trader, address inToken, address outToken, uint256 inAmount, uint256 outAmount ) external returns (uint256 extinguishAmount, uint256 borrowAmount); function registerOvercollateralizedBorrow( address trader, address depositToken, uint256 depositAmount, address borrowToken, uint256 withdrawAmount ) external; function registerLiquidation(address trader) external; function getHoldingAmounts(address trader) external view returns ( address[] memory holdingTokens, uint256[] memory holdingAmounts ); function getBorrowAmounts(address trader) external view returns (address[] memory borrowTokens, uint256[] memory borrowAmounts); } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } library IncentiveReporter { event AddToClaim(address topic, address indexed claimant, uint256 amount); event SubtractFromClaim( address topic, address indexed claimant, uint256 amount ); /// Start / increase amount of claim function addToClaimAmount( address topic, address recipient, uint256 claimAmount ) internal { emit AddToClaim(topic, recipient, claimAmount); } /// Decrease amount of claim function subtractFromClaimAmount( address topic, address recipient, uint256 subtractAmount ) internal { emit SubtractFromClaim(topic, recipient, subtractAmount); } } pragma solidity >=0.5.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; library UniswapStyleLib { address constant UNISWAP_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address constant SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "Identical address!"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "Zero address!"); } // fetches and sorts the reserves for a pair function getReserves( address pair, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = reserveIn * 1_000 + amountInWithFee; amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn * amountOut * 1_000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( uint256 amountIn, bytes32 amms, address[] memory tokens ) internal view returns (uint256[] memory amounts, address[] memory pairs) { require(tokens.length >= 2, "token path too short"); amounts = new uint256[](tokens.length); amounts[0] = amountIn; pairs = new address[](tokens.length - 1); for (uint256 i; i < tokens.length - 1; i++) { address inToken = tokens[i]; address outToken = tokens[i + 1]; address pair = amms[i] == 0 ? pairForUni(inToken, outToken) : pairForSushi(inToken, outToken); pairs[i] = pair; (uint256 reserveIn, uint256 reserveOut) = getReserves(pair, inToken, outToken); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn( uint256 amountOut, bytes32 amms, address[] memory tokens ) internal view returns (uint256[] memory amounts, address[] memory pairs) { require(tokens.length >= 2, "token path too short"); amounts = new uint256[](tokens.length); amounts[amounts.length - 1] = amountOut; pairs = new address[](tokens.length - 1); for (uint256 i = tokens.length - 1; i > 0; i--) { address inToken = tokens[i - 1]; address outToken = tokens[i]; address pair = amms[i - 1] == 0 ? pairForUni(inToken, outToken) : pairForSushi(inToken, outToken); pairs[i - 1] = pair; (uint256 reserveIn, uint256 reserveOut) = getReserves(pair, inToken, outToken); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } // calculates the CREATE2 address for a pair without making any external calls function pairForUni(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", UNISWAP_FACTORY, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } function pairForSushi(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", SUSHI_FACTORY, keccak256(abi.encodePacked(token0, token1)), hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" // init code hash ) ) ) ) ); } }
throws on underflow
function _registerWithdrawal( CrossMarginAccount storage account, address withdrawToken, uint256 withdrawAmount ) internal { require( block.number > account.lastDepositBlock + coolingOffPeriod, "No withdrawal soon after deposit" ); totalLong[withdrawToken] -= withdrawAmount; account.holdings[withdrawToken] = account.holdings[withdrawToken] - withdrawAmount; require(positiveBalance(account), "Insufficient balance"); }
563,811
[ 1, 15069, 603, 3613, 2426, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4861, 1190, 9446, 287, 12, 203, 3639, 19742, 9524, 3032, 2502, 2236, 16, 203, 3639, 1758, 598, 9446, 1345, 16, 203, 3639, 2254, 5034, 598, 9446, 6275, 203, 565, 262, 2713, 288, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 2696, 405, 2236, 18, 2722, 758, 1724, 1768, 397, 27367, 310, 7210, 5027, 16, 203, 5411, 315, 2279, 598, 9446, 287, 17136, 1839, 443, 1724, 6, 203, 3639, 11272, 203, 203, 3639, 2078, 3708, 63, 1918, 9446, 1345, 65, 3947, 598, 9446, 6275, 31, 203, 3639, 2236, 18, 21056, 899, 63, 1918, 9446, 1345, 65, 273, 203, 5411, 2236, 18, 21056, 899, 63, 1918, 9446, 1345, 65, 300, 203, 5411, 598, 9446, 6275, 31, 203, 3639, 2583, 12, 21094, 13937, 12, 4631, 3631, 315, 5048, 11339, 11013, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract LockableToken is ERC721Enumerable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; address public minter; mapping (uint => uint) public tokenLockedFromTimestamp; mapping (uint => bytes32) public tokenUnlockCodeHashes; mapping (uint => bool) public tokenUnlocked; string private _baseTokenURI; event TokenUnlocked(uint tokenId, address unlockerAddress); constructor(string memory name, string memory symbol, string memory baseTokenURI) ERC721(name, symbol) { _baseTokenURI = baseTokenURI; minter = msg.sender; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override { require(tokenLockedFromTimestamp[tokenId] > block.timestamp || tokenUnlocked[tokenId], "LockableToken: Token locked"); super._beforeTokenTransfer(from, to, tokenId); } function unlockToken(bytes32 unlockHash, uint256 tokenId) public { require(msg.sender == ownerOf(tokenId), "LockableToken: Only the Owner can unlock the Token"); //not 100% sure about that one yet require(keccak256(abi.encode(unlockHash)) == tokenUnlockCodeHashes[tokenId], "LockableToken: Unlock Code Incorrect"); tokenUnlocked[tokenId] = true; emit TokenUnlocked(tokenId, msg.sender); } /** * This one is the mint function that sets the unlock code, then calls the parent mint */ function mint(address to, uint lockedFromTimestamp, bytes32 unlockHash) public { tokenLockedFromTimestamp[_tokenIds.current()] = lockedFromTimestamp; tokenUnlockCodeHashes[_tokenIds.current()] = unlockHash; require(msg.sender == minter, "LockableToken: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIds.current()); _tokenIds.increment(); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { return string(abi.encodePacked(super.tokenURI(tokenId),".json")); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } contract AisthisiToken is LockableToken { constructor() LockableToken("AisthisiToken", "AIS", "https://aisthisi.art/metadata/") {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping (bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "./extensions/IERC721Enumerable.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}. 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 || 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 _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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // 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; // 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; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // 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; // 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)); } }
not 100% sure about that one yet
require(msg.sender == ownerOf(tokenId), "LockableToken: Only the Owner can unlock the Token");
5,880,521
[ 1, 902, 2130, 9, 3071, 2973, 716, 1245, 4671, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 951, 12, 2316, 548, 3631, 315, 2531, 429, 1345, 30, 5098, 326, 16837, 848, 7186, 326, 3155, 8863, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.0; //////////////////////////////////////////////////////////////////////////////// // XXX: Do not use in production until this code has been audited. //////////////////////////////////////////////////////////////////////////////// /** **************************************************************************** @notice on-chain verification of verifiable-random-function (VRF) proofs as described in https://eprint.iacr.org/2017/099.pdf (security proofs) and https://tools.ietf.org/html/draft-goldbe-vrf-01#section-5 (spec) **************************************************************************** @dev PURPOSE @dev Reggie the Random Oracle (not his real job) wants to provide randomness to Vera the verifier in such a way that Vera can be sure he's not making his output up to suit himself. Reggie provides Vera a public key to which he knows the secret key. Each time Vera provides a seed to Reggie, he gives back a value which is computed completely deterministically from the seed and the secret key, but which is indistinguishable from randomness to Vera. Nonetheless, Vera is able to verify that Reggie's output came from her seed and his secret key. @dev The purpose of this contract is to perform that verification. **************************************************************************** @dev USAGE @dev The main entry point is isValidVRFOutput. See its docstring. Design notes ------------ An elliptic curve point is generally represented in the solidity code as a uint256[2], corresponding to its affine coordinates in GF(fieldSize). For the sake of efficiency, this implementation deviates from the spec in some minor ways: - Keccak hash rather than SHA256. This is because it's provided natively by the EVM, and therefore costs much less gas. The impact on security should be minor. - Secp256k1 curve instead of P-256. It abuses ECRECOVER for the most expensive ECC arithmetic. - scalarFromCurve recursively hashes and takes the relevant hash bits until it finds a point less than the group order. This results in uniform sampling over the the possible values scalarFromCurve could take. The spec recommends just uing the first hash output as a uint256, which is a slightly biased sample. See the zqHash function. - hashToCurve recursively hashes until it finds a curve x-ordinate. The spec recommends that the initial input should be concatenated with a nonce and then hashed, and this input should be rehashed with the nonce updated until an x-ordinate is found. Recursive hashing is slightly more efficient. The spec also recommends (https://tools.ietf.org/html/rfc8032#section-5.1.3 , by the specification of RS2ECP) that the x-ordinate should be rejected if it is greater than the modulus. - In the calculation of the challenge value "c", the "u" value (or "k*g", if you know the secret nonce) The spec also requires the y ordinate of the hashToCurve to be negated if y is odd. See http://www.secg.org/sec1-v2.pdf#page=17 . This sacrifices one bit of entropy in the random output. Instead, here y is chosen based on whether an extra hash of the inputs is even or odd. */ contract VRF { // See https://en.bitcoin.it/wiki/Secp256k1 for these constants. uint256 constant public GROUP_ORDER = // Number of points in Secp256k1 // solium-disable-next-line indentation 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; // Prime characteristic of the galois field over which Secp256k1 is defined // solium-disable-next-line zeppelin/no-arithmetic-operations uint256 constant public FIELD_SIZE = // solium-disable-next-line indentation 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // solium-disable zeppelin/no-arithmetic-operations uint256 constant public MINUS_ONE = FIELD_SIZE - 1; uint256 constant public MULTIPLICATIVE_GROUP_ORDER = FIELD_SIZE - 1; // pow(x, SQRT_POWER, FIELD_SIZE) == √x, since FIELD_SIZE % 4 = 3 // https://en.wikipedia.org/wiki/Modular_square_root#Prime_or_prime_power_modulus uint256 constant public SQRT_POWER = (FIELD_SIZE + 1) >> 2; uint256 constant public WORD_LENGTH_BYTES = 0x20; // (base**exponent) % modulus // Cribbed from https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4 function bigModExp(uint256 base, uint256 exponent, uint256 modulus) public view returns (uint256 exponentiation) { uint256 callResult; uint256[6] memory bigModExpContractInputs; bigModExpContractInputs[0] = WORD_LENGTH_BYTES; // Length of base bigModExpContractInputs[1] = WORD_LENGTH_BYTES; // Length of exponent bigModExpContractInputs[2] = WORD_LENGTH_BYTES; // Length of modulus bigModExpContractInputs[3] = base; bigModExpContractInputs[4] = exponent; bigModExpContractInputs[5] = modulus; uint256[1] memory output; assembly { // solhint-disable-line no-inline-assembly callResult := staticcall(13056, // Gas cost. See EIP-198's 1st e.g. 0x05, // Bigmodexp contract address bigModExpContractInputs, 0xc0, // Length of input segment output, 0x20) // Length of output segment } if (callResult == 0) {revert("bigModExp failure!");} return output[0]; } // Computes a s.t. a^2 = x in the field. Assumes x is a square. function squareRoot(uint256 x) public view returns (uint256) { return bigModExp(x, SQRT_POWER, FIELD_SIZE); } function ySquared(uint256 x) public view returns (uint256) { // Curve equation is y^2=x^3+7. See return (bigModExp(x, 3, FIELD_SIZE) + 7) % FIELD_SIZE; } // Hash x uniformly into {0, ..., q-1}. Expects x to ALREADY have the // necessary entropy... If x < q, returns x! function zqHash(uint256 q, uint256 x) public pure returns (uint256 x_) { x_ = x; while (x_ >= q) { x_ = uint256(keccak256(abi.encodePacked(x_))); } } // One-way hash function onto the curve. function hashToCurve(uint256[2] memory k, uint256 input) public view returns (uint256[2] memory rv) { bytes32 hash = keccak256(abi.encodePacked(k, input)); rv[0] = zqHash(FIELD_SIZE, uint256(hash)); while (true) { rv[0] = zqHash(FIELD_SIZE, uint256(keccak256(abi.encodePacked(rv[0])))); rv[1] = squareRoot(ySquared(rv[0])); if (mulmod(rv[1], rv[1], FIELD_SIZE) == ySquared(rv[0])) { break; } } // Two possible y ordinates for x ordinate rv[0]; pick one "randomly" if (uint256(keccak256(abi.encodePacked(rv[0], input))) % 2 == 0) { rv[1] = -rv[1]; } } // Bits used in Ethereum address uint256 constant public BOTTOM_160_BITS = 2**161 - 1; // Returns the ethereum address associated with point. function pointAddress(uint256[2] calldata point) external pure returns(address) { bytes memory packedPoint = abi.encodePacked(point); // Lower 160 bits of the keccak hash of (x,y) as 64 bytes return address(uint256(keccak256(packedPoint)) & BOTTOM_160_BITS); } // Returns true iff q==scalar*x, with cryptographically high probability. // Based on Vitalik Buterin's idea in above ethresear.ch post. function ecmulVerify(uint256[2] memory x, uint256 scalar, uint256[2] memory q) public pure returns(bool) { // This ecrecover returns the address associated with c*R. See // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 // The point corresponding to the address returned by ecrecover(0,v,r,s=c*r) // is (r⁻¹ mod Q) * (c*r * R - 0 * g) = c * R, where R is the point // specified by (v, r). See https://crypto.stackexchange.com/a/18106 bytes32 cTimesX0 = bytes32(mulmod(scalar, x[0], GROUP_ORDER)); uint8 parity = x[1] % 2 != 0 ? 28 : 27; return ecrecover(bytes32(0), parity, bytes32(x[0]), cTimesX0) == address(uint256(keccak256(abi.encodePacked(q))) & BOTTOM_160_BITS); } // Returns x1/z1+x2/z2=(x1z2+x2z1)/(z1z2) in projective coordinates on P¹(𝔽ₙ) function projectiveAdd(uint256 x1, uint256 z1, uint256 x2, uint256 z2) external pure returns(uint256 x3, uint256 z3) { uint256 crossMultNumerator1 = mulmod(z2, x1, FIELD_SIZE); uint256 crossMultNumerator2 = mulmod(z1, x2, FIELD_SIZE); uint256 denom = mulmod(z1, z2, FIELD_SIZE); uint256 numerator = addmod(crossMultNumerator1, crossMultNumerator2, FIELD_SIZE); return (numerator, denom); } // Returns x1/z1-x2/z2=(x1z2+x2z1)/(z1z2) in projective coordinates on P¹(𝔽ₙ) function projectiveSub(uint256 x1, uint256 z1, uint256 x2, uint256 z2) public pure returns(uint256 x3, uint256 z3) { uint256 num1 = mulmod(z2, x1, FIELD_SIZE); uint256 num2 = mulmod(FIELD_SIZE - x2, z1, FIELD_SIZE); (x3, z3) = (addmod(num1, num2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE)); } // Returns x1/z1*x2/z2=(x1x2)/(z1z2), in projective coordinates on P¹(𝔽ₙ) function projectiveMul(uint256 x1, uint256 z1, uint256 x2, uint256 z2) public pure returns(uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE)); } // Returns x1/z1/(x2/z2)=(x1z2)/(x2z1), in projective coordinates on P¹(𝔽ₙ) function projectiveDiv(uint256 x1, uint256 z1, uint256 x2, uint256 z2) external pure returns(uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, FIELD_SIZE), mulmod(z1, x2, FIELD_SIZE)); } /** ************************************************************************** @notice Computes elliptic-curve sum, in projective co-ordinates @dev Using projective coordinates avoids costly divisions @dev To use this with x and y in affine coordinates, compute projectiveECAdd(x[0], x[1], 1, y[0], y[1], 1) @dev This can be used to calculate the z which is the inverse to zInv in isValidVRFOutput. But consider using a faster re-implementation. @dev This function assumes [x1,y1,z1],[x2,y2,z2] are valid projective coordinates of secp256k1 points. That is safe in this contract, because this method is only used by linearCombination, which checks points are on the curve via ecrecover, and ensures valid projective coordinates by passing z1=z2=1. ************************************************************************** @param x1 The first affine coordinate of the first summand @param y1 The second affine coordinate of the first summand @param x2 The first affine coordinate of the second summand @param y2 The second affine coordinate of the second summand ************************************************************************** @return [x1,y1,z1]+[x2,y2,z2] as points on secp256k1, in P²(𝔽ₙ) */ function projectiveECAdd(uint256 x1, uint256 y1, uint256 x2, uint256 y2) public pure returns(uint256 x3, uint256 y3, uint256 z3) { // See "Group law for E/K : y^2 = x^3 + ax + b", in section 3.1.2, p. 80, // "Guide to Elliptic Curve Cryptography" by Hankerson, Menezes and Vanstone // We take the equations there for (x3,y3), and homogenize them to // projective coordinates. That way, no inverses are required, here, and we // only need the one inverse in affineECAdd. // We only need the "point addition" equations from Hankerson et al. Can // skip the "point doubling" equations because p1 == p2 is cryptographically // impossible, and require'd not to be the case in linearCombination. // Add extra "projective coordinate" to the two points (uint256 z1, uint256 z2) = (1, 1); // (lx, lz) = (y2-y1)/(x2-x1), i.e., gradient of secant line. uint256 lx = addmod(y2, FIELD_SIZE - y1, FIELD_SIZE); uint256 lz = addmod(x2, FIELD_SIZE - x1, FIELD_SIZE); uint256 dx; // Accumulates denominator from x3 calculation // x3=((y2-y1)/(x2-x1))^2-x1-x2 (x3, dx) = projectiveMul(lx, lz, lx, lz); // ((y2-y1)/(x2-x1))^2 (x3, dx) = projectiveSub(x3, dx, x1, z1); // ((y2-y1)/(x2-x1))^2-x1 (x3, dx) = projectiveSub(x3, dx, x2, z2); // ((y2-y1)/(x2-x1))^2-x1-x2 uint256 dy; // Accumulates denominator from y3 calculation // y3=((y2-y1)/(x2-x1))(x1-x3)-y1 (y3, dy) = projectiveSub(x1, z1, x3, dx); // x1-x3 (y3, dy) = projectiveMul(y3, dy, lx, lz); // ((y2-y1)/(x2-x1))(x1-x3) (y3, dy) = projectiveSub(y3, dy, y1, z1); // ((y2-y1)/(x2-x1))(x1-x3)-y1 if (dx != dy) { // Cross-multiply to put everything over a common denominator x3 = mulmod(x3, dy, FIELD_SIZE); y3 = mulmod(y3, dx, FIELD_SIZE); z3 = mulmod(dx, dy, FIELD_SIZE); } else { z3 = dx; } } // Returns p1+p2, as affine points on secp256k1. invZ must be the inverse of // the z returned by projectiveECAdd(p1, p2). It is computed off-chain to // save gas. function affineECAdd( uint256[2] memory p1, uint256[2] memory p2, uint256 invZ) public pure returns (uint256[2] memory) { uint256 x; uint256 y; uint256 z; (x, y, z) = projectiveECAdd(p1[0], p1[1], p2[0], p2[1]); require(mulmod(z, invZ, FIELD_SIZE) == 1, "_invZ must be inverse of z"); // Clear the z ordinate of the projective representation by dividing through // by it, to obtain the affine representation return [mulmod(x, invZ, FIELD_SIZE), mulmod(y, invZ, FIELD_SIZE)]; } // Returns true iff address(c*p+s*g) == lcWitness, where g is generator. function verifyLinearCombinationWithGenerator( uint256 c, uint256[2] memory p, uint256 s, address lcWitness) public pure returns (bool) { // ecrecover returns 0x0 in certain failure modes. Ensure witness differs. require(lcWitness != address(0), "bad witness"); // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 // The point corresponding to the address returned by // ecrecover(-s*p[0],v,_p[0],_c*p[0]) is // (p[0]⁻¹ mod GROUP_ORDER)*(c*p[0]-(-s)*p[0]*g)=_c*p+s*g, where v // is the parity of p[1]. See https://crypto.stackexchange.com/a/18106 bytes32 pseudoHash = bytes32(GROUP_ORDER - mulmod(p[0], s, GROUP_ORDER)); // https://bitcoin.stackexchange.com/questions/38351/ecdsa-v-r-s-what-is-v uint8 v = (p[1] % 2 == 0) ? 27 : 28; bytes32 pseudoSignature = bytes32(mulmod(c, p[0], GROUP_ORDER)); address computed = ecrecover(pseudoHash, v, bytes32(p[0]), pseudoSignature); return computed == lcWitness; } // c*p1 + s*p2 function linearCombination( uint256 c, uint256[2] memory p1, uint256[2] memory cp1Witness, uint256 s, uint256[2] memory p2, uint256[2] memory sp2Witness, uint256 zInv) public pure returns (uint256[2] memory) { require(cp1Witness[0] != sp2Witness[0], "points must differ in sum"); require(ecmulVerify(p1, c, cp1Witness), "First multiplication check failed"); require(ecmulVerify(p2, s, sp2Witness), "Second multiplication check failed"); return affineECAdd(cp1Witness, sp2Witness, zInv); } // Pseudo-random number from inputs. Corresponds to vrf.go/scalarFromCurve. function scalarFromCurve( uint256[2] memory hash, uint256[2] memory pk, uint256[2] memory gamma, address uWitness, uint256[2] memory v) public pure returns (uint256 s) { bytes32 iHash = keccak256(abi.encodePacked(hash, pk, gamma, v, uWitness)); return zqHash(GROUP_ORDER, uint256(iHash)); } // True if (gamma, c, s) is a correctly constructed randomness proof from pk // and seed. zInv must be the inverse of the third ordinate from // projectiveECAdd applied to cGammaWitness and sHashWitness function verifyVRFProof( uint256[2] memory pk, uint256[2] memory gamma, uint256 c, uint256 s, uint256 seed, address uWitness, uint256[2] memory cGammaWitness, uint256[2] memory sHashWitness, uint256 zInv) public view returns (bool) { // NB: Curve operations already check that (pkX, pkY), (gammaX, gammaY) // are valid curve points. No need to do that explicitly. require( verifyLinearCombinationWithGenerator(c, pk, s, uWitness), "Could not verify that address(c*pk+s*generator)=_uWitness"); uint256[2] memory hash = hashToCurve(pk, seed); uint256[2] memory v = linearCombination( c, gamma, cGammaWitness, s, hash, sHashWitness, zInv); return (c == scalarFromCurve(hash, pk, gamma, uWitness, v)); } /** ************************************************************************** @notice isValidVRFOutput returns true iff the proof can be verified as showing that output was generated as mandated. @dev See the invocation of verifyVRFProof in VRF.js, for an example. ************************************************************************** @dev Let x be the secret key associated with the public key pk @param pk Affine coordinates of the secp256k1 public key for this VRF @param gamma Intermediate output of the VRF as an affine secp256k1 point @param c The challenge value for proof that gamma = x*hashToCurve(seed) See the variable c on p. 28 of https://www.cs.bu.edu/~goldbe/papers/VRF_ietf99_print.pdf @param s The response value for the proof. See s on p. 28 @param seed The input seed from which the VRF output is computed @param uWitness The ethereum address of c*pk + s*<generator>, in elliptic-curve arithmetic @param cGammaWitness c*gamma on the elliptic-curve @param sHashWitness s*hashToCurve(seed) on the elliptic-curve @param zInv Inverse of the third ordinate of the return value from projectiveECAdd(c*gamma, s*hashToCurve(seed)). Passed in here to save gas, because computing modular inverses is expensive in the EVM. @param output The actual output of the VRF. ************************************************************************** @return True iff all the above parameters are correct */ function isValidVRFOutput( uint256[2] calldata pk, uint256[2] calldata gamma, uint256 c, uint256 s, uint256 seed, address uWitness, uint256[2] calldata cGammaWitness, uint256[2] calldata sHashWitness, uint256 zInv, uint256 output) external view returns (bool) { return verifyVRFProof( pk, gamma, c, s, seed, uWitness, cGammaWitness, sHashWitness, zInv) && (uint256(keccak256(abi.encodePacked(gamma))) == output); } }
Pseudo-random number from inputs. Corresponds to vrf.go/scalarFromCurve.
public pure returns (uint256 s) { bytes32 iHash = keccak256(abi.encodePacked(hash, pk, gamma, v, uWitness)); return zqHash(GROUP_ORDER, uint256(iHash)); }
12,662,703
[ 1, 26716, 17, 9188, 1300, 628, 4540, 18, 9557, 455, 12545, 358, 20466, 18, 3240, 19, 8748, 1265, 9423, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1071, 16618, 1135, 261, 11890, 5034, 272, 13, 288, 203, 1377, 1731, 1578, 277, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2816, 16, 2365, 16, 9601, 16, 331, 16, 582, 24007, 10019, 203, 1377, 327, 998, 85, 2310, 12, 8468, 67, 7954, 16, 2254, 5034, 12, 77, 2310, 10019, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-28 */ // SPDX-License-Identifier: Unlicensed /* Tax : 0%( 24% if sold within 24 hours after buying $YAUTJA) Telegram : https://t.me/YautjaInuETH */ 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) { return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev 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 this function * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _createInitialSupply(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SignedSafeMath { /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { return a * b; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { return a / b; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { return a - b; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { return a + b; } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } contract YAUTJAINU is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public enableEarlySellTax = true; uint256 public maxSellTransactionAmount = 10000000 * (10**18); uint256 public maxBuyTransactionAmount = 150000 * (10**18); uint256 public swapTokensAtAmount = 15000 * (10**18); uint256 public maxWalletToken = 300000 * (10**18); uint256 private buyTotalFees = 0; uint256 public sellTotalFees = 0; uint256 public earlySellTotalFee = 24; // auto burn fee uint256 public burnFee = 0; address public deadWallet = 0x000000000000000000000000000000000000dEaD; // distribute the collected tax percentage wise uint256 public liquidityPercent = 0; // 0% of total collected tax uint256 public marketingPercent = 50; // 50% of total collected tax uint256 public devPercent = 50; // 50% of total collected tax address payable public marketingWallet = payable(0xddC1D120DCb5017fCDFc97136FE450Cd5AdaF132); address payable public devWallet = payable(0xddC1D120DCb5017fCDFc97136FE450Cd5AdaF132); // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; // 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; mapping (address => uint256) public lastTxTimestamp; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensIntoLiqudity, uint256 ethReceived ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() ERC20("Yautja Inu", "YAUTJA") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // pancakeswap v2 router address // Create a uniswap pair for this new token address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(marketingWallet, true); excludeFromFees(devWallet, true); excludeFromFees(address(this), true); /* an internal function that is only called here, and CANNOT be called ever again */ _createInitialSupply(owner(), 10000000 * (10**18)); } receive() external payable { } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "KCoin: The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IUniswapV2Router02(newAddress); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "KCoin: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "KCoin: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; // if any account belongs to _isExcludedFromFee account then remove the fee if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 24 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 tokensForLiquidity = contractTokenBalance.mul(liquidityPercent).div(100); // split the Liquidity token balance into halves uint256 half = tokensForLiquidity.div(2); uint256 otherHalf = tokensForLiquidity.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); // swap and Send Eth to marketing, dev wallets swapTokensForEth(contractTokenBalance.sub(tokensForLiquidity)); marketingWallet.transfer(address(this).balance.mul(marketingPercent).div(marketingPercent.add(devPercent))); devWallet.transfer(address(this).balance); emit SwapAndLiquify(half, newBalance); } 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(); if(allowance(address(this), address(uniswapV2Router)) < tokenAmount) { _approve(address(this), address(uniswapV2Router), ~uint256(0)); } // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function setMaxSellTransaction(uint256 _maxSellTxAmount) public onlyOwner { maxSellTransactionAmount = _maxSellTxAmount; require(maxSellTransactionAmount>totalSupply().div(1000), "value is too low"); } function setMaxBuyTransaction(uint256 _maxBuyTxAmount) public onlyOwner { maxBuyTransactionAmount = _maxBuyTxAmount; require(maxBuyTransactionAmount>totalSupply().div(1000), "value is too low"); } function setSwapTokensAtAmouunt(uint256 _newAmount) public onlyOwner { swapTokensAtAmount = _newAmount; } function setMarketingWallet(address payable wallet) public onlyOwner { marketingWallet = wallet; } function setDevWallet(address payable wallet) public onlyOwner { devWallet = wallet; } function updateBuyTotalTax(uint256 _buyTotalFees) public onlyOwner { buyTotalFees = _buyTotalFees; require(buyTotalFees <= 10, "Fee too high"); } function updateSellTotalTax(uint256 _sellTotalFees) public onlyOwner { sellTotalFees = _sellTotalFees; require(sellTotalFees <= 25, "Fee too high"); } function updateEarlySellTotalTax(uint256 _earlySellTotalFee) public onlyOwner { earlySellTotalFee = _earlySellTotalFee; require(earlySellTotalFee <= 25, "Fee too high"); } function updateTaxDistributionPercentage(uint256 _liquidityPercent, uint256 _marketingPercent, uint256 _devPercent) public onlyOwner { require(_liquidityPercent.add(_marketingPercent).add(_devPercent) == 100, "total percentage must be equal to 100"); liquidityPercent = _liquidityPercent; marketingPercent = _marketingPercent; devPercent = _devPercent; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } function setAutoBurn(uint256 _burnFee) external onlyOwner { require(_burnFee <= 5, "value too high"); burnFee = _burnFee; } function setMaxWalletToken(uint256 _maxToken) external onlyOwner { maxWalletToken = _maxToken; require(maxWalletToken>totalSupply().div(1000), "value is too low"); } }
Create a uniswap pair for this new token exclude from paying fees or having max transaction amount
constructor() ERC20("Yautja Inu", "YAUTJA") { address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); excludeFromFees(owner(), true); excludeFromFees(marketingWallet, true); excludeFromFees(devWallet, true); excludeFromFees(address(this), true); an internal function that is only called here, and CANNOT be called ever again _createInitialSupply(owner(), 10000000 * (10**18));
2,022,800
[ 1, 1684, 279, 640, 291, 91, 438, 3082, 364, 333, 394, 1147, 4433, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 61, 5854, 12333, 657, 89, 3113, 315, 61, 37, 1693, 46, 37, 7923, 288, 203, 203, 3639, 1758, 389, 318, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 10756, 203, 5411, 263, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 389, 318, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 24899, 318, 291, 91, 438, 58, 22, 4154, 16, 638, 1769, 203, 203, 3639, 4433, 1265, 2954, 281, 12, 8443, 9334, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 3355, 21747, 16936, 16, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 5206, 16936, 16, 638, 1769, 203, 3639, 4433, 1265, 2954, 281, 12, 2867, 12, 2211, 3631, 638, 1769, 203, 540, 203, 5411, 392, 2713, 445, 716, 353, 1338, 2566, 2674, 16, 203, 5411, 471, 385, 16791, 506, 2566, 14103, 3382, 203, 3639, 389, 2640, 4435, 3088, 1283, 12, 8443, 9334, 2130, 11706, 380, 261, 2163, 636, 2643, 10019, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xee8C904D2c17a02407fe92d2685E51a38ECe8e31/sources/contracts/token/TenderToken.sol
@inheritdoc ITenderToken
function mint(address _recipient, uint256 _amount) external override onlyOwner returns (bool) { _mintShares(_recipient, _tokensToShares(_amount)); return true; }
7,035,293
[ 1, 36, 10093, 24142, 2345, 1345, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 389, 20367, 16, 2254, 5034, 389, 8949, 13, 3903, 3849, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 389, 81, 474, 24051, 24899, 20367, 16, 389, 7860, 774, 24051, 24899, 8949, 10019, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.7; contract SafeTransfer { function _SAFETRANSFER911(ERC20Token _token, address _to, uint256 _value) internal returns (bool result) { //inject NONSTANDARD NAMING _token.TRANSFER494(_to, _value); assembly { switch returndatasize() case 0 { result := not(0) } case 32 { returndatacopy(0, 0, 32) result := mload(0) } default { revert(0, 0) } } require(result, "Unsuccessful token transfer"); } function _SAFETRANSFERFROM345( //inject NONSTANDARD NAMING ERC20Token _token, address _from, address _to, uint256 _value ) internal returns (bool result) { _token.TRANSFERFROM513(_from, _to, _value); assembly { switch returndatasize() case 0 { result := not(0) } case 32 { returndatacopy(0, 0, 32) result := mload(0) } default { revert(0, 0) } } require(result, "Unsuccessful token transfer"); } } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 interface ERC20Token { function TRANSFER494(address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function APPROVE813(address _spender, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function TRANSFERFROM513(address _from, address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function BALANCEOF691(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function ALLOWANCE536(address _owner, address _spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING function TOTALSUPPLY245() external view returns (uint256 supply); //inject NONSTANDARD NAMING event TRANSFER151(address indexed _from, address indexed _to, uint256 _value); //inject NONSTANDARD NAMING event APPROVAL845(address indexed _owner, address indexed _spender, uint256 _value); //inject NONSTANDARD NAMING } contract Ownable { address private _owner; event OWNERSHIPTRANSFERRED396(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = msg.sender; emit OWNERSHIPTRANSFERRED396(address(0), _owner); } function OWNER296() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER677() { //inject NONSTANDARD NAMING require(ISOWNER71(), "Only the contract's owner can invoke this function"); _; } function _SETOWNER235(address _newOwner) internal { //inject NONSTANDARD NAMING _owner = _newOwner; } function ISOWNER71() public view returns (bool) { //inject NONSTANDARD NAMING return msg.sender == _owner; } function RENOUNCEOWNERSHIP275() external ONLYOWNER677 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED396(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP770(address _newOwner) external ONLYOWNER677 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP486(_newOwner); } function _TRANSFEROWNERSHIP486(address _newOwner) internal { //inject NONSTANDARD NAMING require(_newOwner != address(0), "New owner cannot be address(0)"); emit OWNERSHIPTRANSFERRED396(_owner, _newOwner); _owner = _newOwner; } } contract ReentrancyGuard { bool public locked = false; modifier REENTRANCYGUARD399() { //inject NONSTANDARD NAMING require(!locked, "Reentrant call detected!"); locked = true; _; locked = false; } } contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" event UPGRADED572(address indexed implementation); //inject NONSTANDARD NAMING function UPDATECODEADDRESS579(address newAddress) internal { //inject NONSTANDARD NAMING require( bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).PROXIABLEUUID20(), "Not compatible" ); assembly { // solium-disable-line sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) } emit UPGRADED572(newAddress); } function PROXIABLEUUID20() public pure returns (bytes32) { //inject NONSTANDARD NAMING return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } bool internal _initialized; function ISINITIALIZED692() public view returns(bool) { //inject NONSTANDARD NAMING return _initialized; } } contract SecuredFunctions is Ownable { mapping(address => bool) public allowedContracts; modifier ONLYALLOWEDCONTRACTS234 { //inject NONSTANDARD NAMING require(allowedContracts[msg.sender] || msg.sender == address(this), "Only allowed contracts can invoke this function"); _; } function SETALLOWEDCONTRACT466 ( //inject NONSTANDARD NAMING address _contract, bool _allowed ) public ONLYOWNER677 { allowedContracts[_contract] = _allowed; } } contract MessageSigned { constructor() internal {} function _RECOVERADDRESS15(bytes32 _signHash, bytes memory _messageSignature) //inject NONSTANDARD NAMING internal pure returns(address) { uint8 v; bytes32 r; bytes32 s; (v,r,s) = SIGNATURESPLIT549(_messageSignature); return ecrecover(_signHash, v, r, s); } function _GETSIGNHASH525(bytes32 _hash) internal pure returns (bytes32 signHash) { //inject NONSTANDARD NAMING signHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)); } function SIGNATURESPLIT549(bytes memory _signature) //inject NONSTANDARD NAMING internal pure returns (uint8 v, bytes32 r, bytes32 s) { require(_signature.length == 65, "Bad signature length"); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(_signature, 65)), 0xff) } if (v < 27) { v += 27; } require(v == 27 || v == 28, "Bad signature version"); } } contract ApproveAndCallFallBack { function RECEIVEAPPROVAL139(address from, uint256 _amount, address _token, bytes memory _data) public; //inject NONSTANDARD NAMING } contract License is Ownable, ApproveAndCallFallBack, SafeTransfer, Proxiable { uint256 public price; ERC20Token token; address burnAddress; struct LicenseDetails { uint price; uint creationTime; } address[] public licenseOwners; mapping(address => uint) public idxLicenseOwners; mapping(address => LicenseDetails) public licenseDetails; event BOUGHT91(address buyer, uint256 price); //inject NONSTANDARD NAMING event PRICECHANGED925(uint256 _price); //inject NONSTANDARD NAMING event BURNADDRESSCHANGED16(address sender, address prevBurnAddress, address newBurnAddress); //inject NONSTANDARD NAMING function SETBURNADDRESS147(address payable _burnAddress) external ONLYOWNER677 { //inject NONSTANDARD NAMING emit BURNADDRESSCHANGED16(msg.sender, burnAddress, _burnAddress); burnAddress = _burnAddress; } constructor(address _tokenAddress, uint256 _price, address _burnAddress) public { INIT444(_tokenAddress, _price, _burnAddress); } function INIT444( //inject NONSTANDARD NAMING address _tokenAddress, uint256 _price, address _burnAddress ) public { assert(_initialized == false); _initialized = true; price = _price; token = ERC20Token(_tokenAddress); burnAddress = _burnAddress; _SETOWNER235(msg.sender); } function UPDATECODE511(address newCode) public ONLYOWNER677 { //inject NONSTANDARD NAMING UPDATECODEADDRESS579(newCode); } function ISLICENSEOWNER342(address _address) public view returns (bool) { //inject NONSTANDARD NAMING return licenseDetails[_address].price != 0 && licenseDetails[_address].creationTime != 0; } function BUY699() external returns(uint) { //inject NONSTANDARD NAMING uint id = _BUYFROM536(msg.sender); return id; } function _BUYFROM536(address _licenseOwner) internal returns(uint) { //inject NONSTANDARD NAMING require(licenseDetails[_licenseOwner].creationTime == 0, "License already bought"); licenseDetails[_licenseOwner] = LicenseDetails({ price: price, creationTime: block.timestamp }); uint idx = licenseOwners.push(_licenseOwner); idxLicenseOwners[_licenseOwner] = idx; emit BOUGHT91(_licenseOwner, price); require(_SAFETRANSFERFROM345(token, _licenseOwner, burnAddress, price), "Unsuccessful token transfer"); return idx; } function SETPRICE121(uint256 _price) external ONLYOWNER677 { //inject NONSTANDARD NAMING price = _price; emit PRICECHANGED925(_price); } function GETNUMLICENSEOWNERS215() external view returns (uint256) { //inject NONSTANDARD NAMING return licenseOwners.length; } function RECEIVEAPPROVAL139(address _from, uint256 _amount, address _token, bytes memory _data) public { //inject NONSTANDARD NAMING require(_amount == price, "Wrong value"); require(_token == address(token), "Wrong token"); require(_token == address(msg.sender), "Wrong call"); require(_data.length == 4, "Wrong data length"); require(_ABIDECODEBUY25(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()")) _BUYFROM536(_from); } function _ABIDECODEBUY25(bytes memory _data) internal pure returns(bytes4 sig) { //inject NONSTANDARD NAMING assembly { sig := mload(add(_data, add(0x20, 0))) } } } contract IEscrow { enum EscrowStatus {CREATED, FUNDED, PAID, RELEASED, CANCELED} struct EscrowTransaction { uint256 offerId; address token; uint256 tokenAmount; uint256 expirationTime; uint256 sellerRating; uint256 buyerRating; uint256 fiatAmount; address payable buyer; address payable seller; address payable arbitrator; address payable destination; EscrowStatus status; } function CREATEESCROW_RELAYED829( //inject NONSTANDARD NAMING address payable _sender, uint _offerId, uint _tokenAmount, uint _fiatAmount, address payable _destination, string calldata _contactData, string calldata _location, string calldata _username ) external returns(uint escrowId); function PAY204(uint _escrowId) external; //inject NONSTANDARD NAMING function PAY_RELAYED312(address _sender, uint _escrowId) external; //inject NONSTANDARD NAMING function CANCEL601(uint _escrowId) external; //inject NONSTANDARD NAMING function CANCEL_RELAYED801(address _sender, uint _escrowId) external; //inject NONSTANDARD NAMING function OPENCASE508(uint _escrowId, uint8 _motive) external; //inject NONSTANDARD NAMING function OPENCASE_RELAYED502(address _sender, uint256 _escrowId, uint8 _motive) external; //inject NONSTANDARD NAMING function RATETRANSACTION74(uint _escrowId, uint _rate) external; //inject NONSTANDARD NAMING function RATETRANSACTION_RELAYED289(address _sender, uint _escrowId, uint _rate) external; //inject NONSTANDARD NAMING function GETBASICTRADEDATA166(uint _escrowId) external view returns(address payable buyer, address payable seller, address token, uint tokenAmount); //inject NONSTANDARD NAMING } contract Pausable is Ownable { event PAUSED628(); //inject NONSTANDARD NAMING event UNPAUSED643(); //inject NONSTANDARD NAMING bool public paused; constructor () internal { paused = false; } modifier WHENNOTPAUSED504() { //inject NONSTANDARD NAMING require(!paused, "Contract must be unpaused"); _; } modifier WHENPAUSED494() { //inject NONSTANDARD NAMING require(paused, "Contract must be paused"); _; } function PAUSE819() external ONLYOWNER677 WHENNOTPAUSED504 { //inject NONSTANDARD NAMING paused = true; emit PAUSED628(); } function UNPAUSE973() external ONLYOWNER677 WHENPAUSED494 { //inject NONSTANDARD NAMING paused = false; emit UNPAUSED643(); } } contract ArbitrationLicense is License { enum RequestStatus {NONE,AWAIT,ACCEPTED,REJECTED,CLOSED} struct Request{ address seller; address arbitrator; RequestStatus status; uint date; } struct ArbitratorLicenseDetails { uint id; bool acceptAny;// accept any seller } mapping(address => ArbitratorLicenseDetails) public arbitratorlicenseDetails; mapping(address => mapping(address => bool)) public permissions; mapping(address => mapping(address => bool)) public blacklist; mapping(bytes32 => Request) public requests; event ARBITRATORREQUESTED586(bytes32 id, address indexed seller, address indexed arbitrator); //inject NONSTANDARD NAMING event REQUESTACCEPTED10(bytes32 id, address indexed arbitrator, address indexed seller); //inject NONSTANDARD NAMING event REQUESTREJECTED172(bytes32 id, address indexed arbitrator, address indexed seller); //inject NONSTANDARD NAMING event REQUESTCANCELED901(bytes32 id, address indexed arbitrator, address indexed seller); //inject NONSTANDARD NAMING event BLACKLISTSELLER899(address indexed arbitrator, address indexed seller); //inject NONSTANDARD NAMING event UNBLACKLISTSELLER540(address indexed arbitrator, address indexed seller); //inject NONSTANDARD NAMING constructor(address _tokenAddress, uint256 _price, address _burnAddress) License(_tokenAddress, _price, _burnAddress) public {} function BUY699() external returns(uint) { //inject NONSTANDARD NAMING return _BUY66(msg.sender, false); } function BUY699(bool _acceptAny) external returns(uint) { //inject NONSTANDARD NAMING return _BUY66(msg.sender, _acceptAny); } function _BUY66(address _sender, bool _acceptAny) internal returns (uint id) { //inject NONSTANDARD NAMING id = _BUYFROM536(_sender); arbitratorlicenseDetails[_sender].id = id; arbitratorlicenseDetails[_sender].acceptAny = _acceptAny; } function CHANGEACCEPTANY798(bool _acceptAny) public { //inject NONSTANDARD NAMING require(ISLICENSEOWNER342(msg.sender), "Message sender should have a valid arbitrator license"); require(arbitratorlicenseDetails[msg.sender].acceptAny != _acceptAny, "Message sender should pass parameter different from the current one"); arbitratorlicenseDetails[msg.sender].acceptAny = _acceptAny; } function REQUESTARBITRATOR791(address _arbitrator) public { //inject NONSTANDARD NAMING require(ISLICENSEOWNER342(_arbitrator), "Arbitrator should have a valid license"); require(!arbitratorlicenseDetails[_arbitrator].acceptAny, "Arbitrator already accepts all cases"); bytes32 _id = keccak256(abi.encodePacked(_arbitrator, msg.sender)); RequestStatus _status = requests[_id].status; require(_status != RequestStatus.AWAIT && _status != RequestStatus.ACCEPTED, "Invalid request status"); if(_status == RequestStatus.REJECTED || _status == RequestStatus.CLOSED){ require(requests[_id].date + 3 days < block.timestamp, "Must wait 3 days before requesting the arbitrator again"); } requests[_id] = Request({ seller: msg.sender, arbitrator: _arbitrator, status: RequestStatus.AWAIT, date: block.timestamp }); emit ARBITRATORREQUESTED586(_id, msg.sender, _arbitrator); } function GETID524(address _arbitrator, address _account) external pure returns(bytes32){ //inject NONSTANDARD NAMING return keccak256(abi.encodePacked(_arbitrator,_account)); } function ACCEPTREQUEST19(bytes32 _id) public { //inject NONSTANDARD NAMING require(ISLICENSEOWNER342(msg.sender), "Arbitrator should have a valid license"); require(requests[_id].status == RequestStatus.AWAIT, "This request is not pending"); require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator already accepts all cases"); require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator"); requests[_id].status = RequestStatus.ACCEPTED; address _seller = requests[_id].seller; permissions[msg.sender][_seller] = true; emit REQUESTACCEPTED10(_id, msg.sender, requests[_id].seller); } function REJECTREQUEST397(bytes32 _id) public { //inject NONSTANDARD NAMING require(ISLICENSEOWNER342(msg.sender), "Arbitrator should have a valid license"); require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status"); require(!arbitratorlicenseDetails[msg.sender].acceptAny, "Arbitrator accepts all cases"); require(requests[_id].arbitrator == msg.sender, "Invalid arbitrator"); requests[_id].status = RequestStatus.REJECTED; requests[_id].date = block.timestamp; address _seller = requests[_id].seller; permissions[msg.sender][_seller] = false; emit REQUESTREJECTED172(_id, msg.sender, requests[_id].seller); } function CANCELREQUEST262(bytes32 _id) public { //inject NONSTANDARD NAMING require(requests[_id].seller == msg.sender, "This request id does not belong to the message sender"); require(requests[_id].status == RequestStatus.AWAIT || requests[_id].status == RequestStatus.ACCEPTED, "Invalid request status"); address arbitrator = requests[_id].arbitrator; requests[_id].status = RequestStatus.CLOSED; requests[_id].date = block.timestamp; address _arbitrator = requests[_id].arbitrator; permissions[_arbitrator][msg.sender] = false; emit REQUESTCANCELED901(_id, arbitrator, requests[_id].seller); } function BLACKLISTSELLER470(address _seller) public { //inject NONSTANDARD NAMING require(ISLICENSEOWNER342(msg.sender), "Arbitrator should have a valid license"); blacklist[msg.sender][_seller] = true; emit BLACKLISTSELLER899(msg.sender, _seller); } function UNBLACKLISTSELLER351(address _seller) public { //inject NONSTANDARD NAMING require(ISLICENSEOWNER342(msg.sender), "Arbitrator should have a valid license"); blacklist[msg.sender][_seller] = false; emit UNBLACKLISTSELLER540(msg.sender, _seller); } function ISALLOWED574(address _seller, address _arbitrator) public view returns(bool) { //inject NONSTANDARD NAMING return (arbitratorlicenseDetails[_arbitrator].acceptAny && !blacklist[_arbitrator][_seller]) || permissions[_arbitrator][_seller]; } function RECEIVEAPPROVAL139(address _from, uint256 _amount, address _token, bytes memory _data) public { //inject NONSTANDARD NAMING require(_amount == price, "Wrong value"); require(_token == address(token), "Wrong token"); require(_token == address(msg.sender), "Wrong call"); require(_data.length == 4, "Wrong data length"); require(_ABIDECODEBUY25(_data) == bytes4(0xa6f2ae3a), "Wrong method selector"); //bytes4(keccak256("buy()")) _BUY66(_from, false); } } contract UserStore is MessageSigned, SecuredFunctions, Proxiable { struct User { string contactData; string location; string username; } License public sellingLicenses; ArbitrationLicense public arbitrationLicenses; mapping(address => User) public users; mapping(address => uint) public user_nonce; constructor(address _sellingLicenses, address _arbitrationLicenses) public { INIT444(_sellingLicenses, _arbitrationLicenses); } function INIT444( //inject NONSTANDARD NAMING address _sellingLicenses, address _arbitrationLicenses ) public { assert(_initialized == false); _initialized = true; sellingLicenses = License(_sellingLicenses); arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses); _SETOWNER235(msg.sender); } function UPDATECODE511(address newCode) public ONLYOWNER677 { //inject NONSTANDARD NAMING UPDATECODEADDRESS579(newCode); } event LICENSESCHANGED569(address sender, address oldSellingLicenses, address newSellingLicenses, address oldArbitrationLicenses, address newArbitrationLicenses); //inject NONSTANDARD NAMING function SETLICENSES678( //inject NONSTANDARD NAMING address _sellingLicenses, address _arbitrationLicenses ) public ONLYOWNER677 { emit LICENSESCHANGED569(msg.sender, address(sellingLicenses), address(_sellingLicenses), address(arbitrationLicenses), (_arbitrationLicenses)); sellingLicenses = License(_sellingLicenses); arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses); } function _DATAHASH273(string memory _username, string memory _contactData, uint _nonce) internal view returns (bytes32) { //inject NONSTANDARD NAMING return keccak256(abi.encodePacked(address(this), _username, _contactData, _nonce)); } function GETDATAHASH823(string calldata _username, string calldata _contactData) external view returns (bytes32) { //inject NONSTANDARD NAMING return _DATAHASH273(_username, _contactData, user_nonce[msg.sender]); } function _GETSIGNER107( //inject NONSTANDARD NAMING string memory _username, string memory _contactData, uint _nonce, bytes memory _signature ) internal view returns(address) { bytes32 signHash = _GETSIGNHASH525(_DATAHASH273(_username, _contactData, _nonce)); return _RECOVERADDRESS15(signHash, _signature); } function GETMESSAGESIGNER993( //inject NONSTANDARD NAMING string calldata _username, string calldata _contactData, uint _nonce, bytes calldata _signature ) external view returns(address) { return _GETSIGNER107(_username, _contactData, _nonce, _signature); } function _ADDORUPDATEUSER76( //inject NONSTANDARD NAMING address _user, string memory _contactData, string memory _location, string memory _username ) internal { User storage u = users[_user]; u.contactData = _contactData; u.location = _location; u.username = _username; } function ADDORUPDATEUSER850( //inject NONSTANDARD NAMING bytes calldata _signature, string calldata _contactData, string calldata _location, string calldata _username, uint _nonce ) external returns(address payable _user) { _user = address(uint160(_GETSIGNER107(_username, _contactData, _nonce, _signature))); require(_nonce == user_nonce[_user], "Invalid nonce"); user_nonce[_user]++; _ADDORUPDATEUSER76(_user, _contactData, _location, _username); return _user; } function ADDORUPDATEUSER850( //inject NONSTANDARD NAMING string calldata _contactData, string calldata _location, string calldata _username ) external { _ADDORUPDATEUSER76(msg.sender, _contactData, _location, _username); } function ADDORUPDATEUSER850( //inject NONSTANDARD NAMING address _sender, string calldata _contactData, string calldata _location, string calldata _username ) external ONLYALLOWEDCONTRACTS234 { _ADDORUPDATEUSER76(_sender, _contactData, _location, _username); } } contract Stakable is Ownable, SafeTransfer { uint public basePrice = 0.01 ether; address payable public burnAddress; struct Stake { uint amount; address payable owner; address token; } mapping(uint => Stake) public stakes; mapping(address => uint) public stakeCounter; event BURNADDRESSCHANGED16(address sender, address prevBurnAddress, address newBurnAddress); //inject NONSTANDARD NAMING event BASEPRICECHANGED745(address sender, uint prevPrice, uint newPrice); //inject NONSTANDARD NAMING event STAKED319(uint indexed itemId, address indexed owner, uint amount); //inject NONSTANDARD NAMING event UNSTAKED65(uint indexed itemId, address indexed owner, uint amount); //inject NONSTANDARD NAMING event SLASHED89(uint indexed itemId, address indexed owner, address indexed slasher, uint amount); //inject NONSTANDARD NAMING constructor(address payable _burnAddress) public { burnAddress = _burnAddress; } function SETBURNADDRESS147(address payable _burnAddress) external ONLYOWNER677 { //inject NONSTANDARD NAMING emit BURNADDRESSCHANGED16(msg.sender, burnAddress, _burnAddress); burnAddress = _burnAddress; } function SETBASEPRICE977(uint _basePrice) external ONLYOWNER677 { //inject NONSTANDARD NAMING emit BASEPRICECHANGED745(msg.sender, basePrice, _basePrice); basePrice = _basePrice; } function _STAKE330(uint _itemId, address payable _owner, address _tokenAddress) internal { //inject NONSTANDARD NAMING require(stakes[_itemId].owner == address(0), "Already has/had a stake"); stakeCounter[_owner]++; uint stakeAmount = basePrice * stakeCounter[_owner] * stakeCounter[_owner]; // y = basePrice * x^2 // Using only ETH as stake for phase 0 _tokenAddress = address(0); require(msg.value == stakeAmount, "ETH amount is required"); // Uncomment to support tokens stakes[_itemId].amount = stakeAmount; stakes[_itemId].owner = _owner; stakes[_itemId].token = _tokenAddress; emit STAKED319(_itemId, _owner, stakeAmount); } function GETAMOUNTTOSTAKE537(address _owner) public view returns(uint){ //inject NONSTANDARD NAMING uint stakeCnt = stakeCounter[_owner] + 1; return basePrice * stakeCnt * stakeCnt; // y = basePrice * x^2 } function _UNSTAKE786(uint _itemId) internal { //inject NONSTANDARD NAMING Stake storage s = stakes[_itemId]; if (s.amount == 0) return; // No stake for item uint amount = s.amount; s.amount = 0; assert(stakeCounter[s.owner] > 0); stakeCounter[s.owner]--; if (s.token == address(0)) { (bool success, ) = s.owner.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_SAFETRANSFER911(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds"); } emit UNSTAKED65(_itemId, s.owner, amount); } function _SLASH319(uint _itemId) internal { //inject NONSTANDARD NAMING Stake storage s = stakes[_itemId]; // TODO: what happens if offer was previosly validated and the user removed the stake? if (s.amount == 0) return; uint amount = s.amount; s.amount = 0; if (s.token == address(0)) { (bool success, ) = burnAddress.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_SAFETRANSFER911(ERC20Token(s.token), burnAddress, amount), "Couldn't transfer funds"); } emit SLASHED89(_itemId, s.owner, msg.sender, amount); } function _REFUNDSTAKE66(uint _itemId) internal { //inject NONSTANDARD NAMING Stake storage s = stakes[_itemId]; if (s.amount == 0) return; uint amount = s.amount; s.amount = 0; stakeCounter[s.owner]--; if (amount != 0) { if (s.token == address(0)) { (bool success, ) = s.owner.call.value(amount)(""); require(success, "Transfer failed."); } else { require(_SAFETRANSFER911(ERC20Token(s.token), s.owner, amount), "Couldn't transfer funds"); } } } } contract OfferStore is Stakable, SecuredFunctions, Proxiable { struct Offer { int16 margin; uint[] paymentMethods; uint limitL; uint limitU; address asset; string currency; address payable owner; address payable arbitrator; bool deleted; } License public sellingLicenses; ArbitrationLicense public arbitrationLicenses; UserStore public userStore; Offer[] public offers; mapping(address => uint256[]) public addressToOffers; mapping(address => mapping (uint256 => bool)) public offerWhitelist; event OFFERADDED246( //inject NONSTANDARD NAMING address owner, uint256 offerId, address asset, string location, string currency, string username, uint[] paymentMethods, uint limitL, uint limitU, int16 margin ); event OFFERREMOVED496(address owner, uint256 offerId); //inject NONSTANDARD NAMING constructor(address _userStore, address _sellingLicenses, address _arbitrationLicenses, address payable _burnAddress) public Stakable(_burnAddress) { INIT444(_userStore, _sellingLicenses, _arbitrationLicenses, _burnAddress); } function INIT444( //inject NONSTANDARD NAMING address _userStore, address _sellingLicenses, address _arbitrationLicenses, address payable _burnAddress ) public { assert(_initialized == false); _initialized = true; userStore = UserStore(_userStore); sellingLicenses = License(_sellingLicenses); arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses); burnAddress = _burnAddress; basePrice = 0.01 ether; _SETOWNER235(msg.sender); } function UPDATECODE511(address newCode) public ONLYOWNER677 { //inject NONSTANDARD NAMING UPDATECODEADDRESS579(newCode); } event LICENSESCHANGED569(address sender, address oldSellingLicenses, address newSellingLicenses, address oldArbitrationLicenses, address newArbitrationLicenses); //inject NONSTANDARD NAMING function SETLICENSES678( //inject NONSTANDARD NAMING address _sellingLicenses, address _arbitrationLicenses ) public ONLYOWNER677 { emit LICENSESCHANGED569(msg.sender, address(sellingLicenses), address(_sellingLicenses), address(arbitrationLicenses), (_arbitrationLicenses)); sellingLicenses = License(_sellingLicenses); arbitrationLicenses = ArbitrationLicense(_arbitrationLicenses); } function ADDOFFER296( //inject NONSTANDARD NAMING address _asset, string memory _contactData, string memory _location, string memory _currency, string memory _username, uint[] memory _paymentMethods, uint _limitL, uint _limitU, int16 _margin, address payable _arbitrator ) public payable { //require(sellingLicenses.isLicenseOwner(msg.sender), "Not a license owner"); // @TODO: limit number of offers if the sender is unlicensed? require(arbitrationLicenses.ISALLOWED574(msg.sender, _arbitrator), "Arbitrator does not allow this transaction"); require(_limitL <= _limitU, "Invalid limits"); require(msg.sender != _arbitrator, "Cannot arbitrate own offers"); userStore.ADDORUPDATEUSER850( msg.sender, _contactData, _location, _username ); Offer memory newOffer = Offer( _margin, _paymentMethods, _limitL, _limitU, _asset, _currency, msg.sender, _arbitrator, false ); uint256 offerId = offers.push(newOffer) - 1; offerWhitelist[msg.sender][offerId] = true; addressToOffers[msg.sender].push(offerId); emit OFFERADDED246( msg.sender, offerId, _asset, _location, _currency, _username, _paymentMethods, _limitL, _limitU, _margin); _STAKE330(offerId, msg.sender, _asset); } function REMOVEOFFER618(uint256 _offerId) external { //inject NONSTANDARD NAMING require(offerWhitelist[msg.sender][_offerId], "Offer does not exist"); offers[_offerId].deleted = true; offerWhitelist[msg.sender][_offerId] = false; emit OFFERREMOVED496(msg.sender, _offerId); _UNSTAKE786(_offerId); } function OFFER296(uint256 _id) external view returns ( //inject NONSTANDARD NAMING address asset, string memory currency, int16 margin, uint[] memory paymentMethods, uint limitL, uint limitU, address payable owner, address payable arbitrator, bool deleted ) { Offer memory theOffer = offers[_id]; // In case arbitrator rejects the seller address payable offerArbitrator = theOffer.arbitrator; if(!arbitrationLicenses.ISALLOWED574(theOffer.owner, offerArbitrator)){ offerArbitrator = address(0); } return ( theOffer.asset, theOffer.currency, theOffer.margin, theOffer.paymentMethods, theOffer.limitL, theOffer.limitU, theOffer.owner, offerArbitrator, theOffer.deleted ); } function GETOFFEROWNER81(uint256 _id) external view returns (address payable) { //inject NONSTANDARD NAMING return (offers[_id].owner); } function GETASSET816(uint256 _id) external view returns (address) { //inject NONSTANDARD NAMING return (offers[_id].asset); } function GETARBITRATOR107(uint256 _id) external view returns (address payable) { //inject NONSTANDARD NAMING return (offers[_id].arbitrator); } function OFFERSSIZE507() external view returns (uint256) { //inject NONSTANDARD NAMING return offers.length; } function GETOFFERIDS508(address _address) external view returns (uint256[] memory) { //inject NONSTANDARD NAMING return addressToOffers[_address]; } function SLASHSTAKE918(uint _offerId) external ONLYALLOWEDCONTRACTS234 { //inject NONSTANDARD NAMING _SLASH319(_offerId); } function REFUNDSTAKE487(uint _offerId) external ONLYALLOWEDCONTRACTS234 { //inject NONSTANDARD NAMING _REFUNDSTAKE66(_offerId); } } contract Fees is Ownable, ReentrancyGuard, SafeTransfer { address payable public feeDestination; uint public feeMilliPercent; mapping(address => uint) public feeTokenBalances; mapping(uint => bool) public feePaid; event FEEDESTINATIONCHANGED311(address payable); //inject NONSTANDARD NAMING event FEEMILLIPERCENTCHANGED580(uint amount); //inject NONSTANDARD NAMING event FEESWITHDRAWN828(uint amount, address token); //inject NONSTANDARD NAMING constructor(address payable _feeDestination, uint _feeMilliPercent) public { feeDestination = _feeDestination; feeMilliPercent = _feeMilliPercent; } function SETFEEDESTINATIONADDRESS891(address payable _addr) external ONLYOWNER677 { //inject NONSTANDARD NAMING feeDestination = _addr; emit FEEDESTINATIONCHANGED311(_addr); } function SETFEEAMOUNT608(uint _feeMilliPercent) external ONLYOWNER677 { //inject NONSTANDARD NAMING feeMilliPercent = _feeMilliPercent; emit FEEMILLIPERCENTCHANGED580(_feeMilliPercent); } function _RELEASEFEE319(address payable _arbitrator, uint _value, address _tokenAddress, bool _isDispute) internal REENTRANCYGUARD399 { //inject NONSTANDARD NAMING uint _milliPercentToArbitrator; if (_isDispute) { _milliPercentToArbitrator = 100000; // 100% } else { _milliPercentToArbitrator = 10000; // 10% } uint feeAmount = _GETVALUEOFFMILLIPERCENT932(_value, feeMilliPercent); uint arbitratorValue = _GETVALUEOFFMILLIPERCENT932(feeAmount, _milliPercentToArbitrator); uint destinationValue = feeAmount - arbitratorValue; if (_tokenAddress != address(0)) { ERC20Token tokenToPay = ERC20Token(_tokenAddress); require(_SAFETRANSFER911(tokenToPay, _arbitrator, arbitratorValue), "Unsuccessful token transfer - arbitrator"); if (destinationValue > 0) { require(_SAFETRANSFER911(tokenToPay, feeDestination, destinationValue), "Unsuccessful token transfer - destination"); } } else { // EIP1884 fix (bool success, ) = _arbitrator.call.value(arbitratorValue)(""); require(success, "Transfer failed."); if (destinationValue > 0) { // EIP1884 fix (bool success, ) = feeDestination.call.value(destinationValue)(""); require(success, "Transfer failed."); } } } function _GETVALUEOFFMILLIPERCENT932(uint _value, uint _milliPercent) internal pure returns(uint) { //inject NONSTANDARD NAMING // To get the factor, we divide like 100 like a normal percent, but we multiply that by 1000 because it's a milliPercent // Eg: 1 % = 1000 millipercent => Factor is 0.01, so 1000 divided by 100 * 1000 return (_value * _milliPercent) / (100 * 1000); } function _PAYFEE642(address _from, uint _id, uint _value, address _tokenAddress) internal { //inject NONSTANDARD NAMING if (feePaid[_id]) return; feePaid[_id] = true; uint feeAmount = _GETVALUEOFFMILLIPERCENT932(_value, feeMilliPercent); feeTokenBalances[_tokenAddress] += feeAmount; if (_tokenAddress != address(0)) { require(msg.value == 0, "Cannot send ETH with token address different from 0"); ERC20Token tokenToPay = ERC20Token(_tokenAddress); require(_SAFETRANSFERFROM345(tokenToPay, _from, address(this), feeAmount + _value), "Unsuccessful token transfer"); } else { require(msg.value == (_value + feeAmount), "ETH amount is required"); } } } contract Arbitrable { enum ArbitrationResult {UNSOLVED, BUYER, SELLER} enum ArbitrationMotive {NONE, UNRESPONSIVE, PAYMENT_ISSUE, OTHER} ArbitrationLicense public arbitratorLicenses; mapping(uint => ArbitrationCase) public arbitrationCases; address public fallbackArbitrator; struct ArbitrationCase { bool open; address openBy; address arbitrator; uint arbitratorTimeout; ArbitrationResult result; ArbitrationMotive motive; } event ARBITRATORCHANGED687(address arbitrator); //inject NONSTANDARD NAMING event ARBITRATIONCANCELED782(uint escrowId); //inject NONSTANDARD NAMING event ARBITRATIONREQUIRED867(uint escrowId, uint timeout); //inject NONSTANDARD NAMING event ARBITRATIONRESOLVED296(uint escrowId, ArbitrationResult result, address arbitrator); //inject NONSTANDARD NAMING constructor(address _arbitratorLicenses, address _fallbackArbitrator) public { arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses); fallbackArbitrator = _fallbackArbitrator; } function _SOLVEDISPUTE500(uint _escrowId, bool _releaseFunds, address _arbitrator) internal; //inject NONSTANDARD NAMING function _GETARBITRATOR209(uint _escrowId) internal view returns(address); //inject NONSTANDARD NAMING function ISDISPUTED635(uint _escrowId) public view returns (bool) { //inject NONSTANDARD NAMING return _ISDISPUTED184(_escrowId); } function _ISDISPUTED184(uint _escrowId) internal view returns (bool) { //inject NONSTANDARD NAMING return arbitrationCases[_escrowId].open || arbitrationCases[_escrowId].result != ArbitrationResult.UNSOLVED; } function HADDISPUTE385(uint _escrowId) public view returns (bool) { //inject NONSTANDARD NAMING return arbitrationCases[_escrowId].result != ArbitrationResult.UNSOLVED; } function CANCELARBITRATION839(uint _escrowId) external { //inject NONSTANDARD NAMING require(arbitrationCases[_escrowId].openBy == msg.sender, "Arbitration can only be canceled by the opener"); require(arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED && arbitrationCases[_escrowId].open, "Arbitration already solved or not open"); delete arbitrationCases[_escrowId]; emit ARBITRATIONCANCELED782(_escrowId); } function _OPENDISPUTE139(uint _escrowId, address _openBy, uint8 _motive) internal { //inject NONSTANDARD NAMING require(arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED && !arbitrationCases[_escrowId].open, "Arbitration already solved or has been opened before"); address arbitratorAddress = _GETARBITRATOR209(_escrowId); require(arbitratorAddress != address(0), "Arbitrator is required"); uint timeout = block.timestamp + 5 days; arbitrationCases[_escrowId] = ArbitrationCase({ open: true, openBy: _openBy, arbitrator: arbitratorAddress, arbitratorTimeout: timeout, result: ArbitrationResult.UNSOLVED, motive: ArbitrationMotive(_motive) }); emit ARBITRATIONREQUIRED867(_escrowId, timeout); } function SETARBITRATIONRESULT710(uint _escrowId, ArbitrationResult _result) external { //inject NONSTANDARD NAMING require(arbitrationCases[_escrowId].open && arbitrationCases[_escrowId].result == ArbitrationResult.UNSOLVED, "Case must be open and unsolved"); require(_result != ArbitrationResult.UNSOLVED, "Arbitration does not have result"); require(arbitratorLicenses.ISLICENSEOWNER342(msg.sender), "Only arbitrators can invoke this function"); if (block.timestamp > arbitrationCases[_escrowId].arbitratorTimeout) { require(arbitrationCases[_escrowId].arbitrator == msg.sender || msg.sender == fallbackArbitrator, "Invalid escrow arbitrator"); } else { require(arbitrationCases[_escrowId].arbitrator == msg.sender, "Invalid escrow arbitrator"); } arbitrationCases[_escrowId].open = false; arbitrationCases[_escrowId].result = _result; emit ARBITRATIONRESOLVED296(_escrowId, _result, msg.sender); if(_result == ArbitrationResult.BUYER){ _SOLVEDISPUTE500(_escrowId, true, msg.sender); } else { _SOLVEDISPUTE500(_escrowId, false, msg.sender); } } } contract Escrow is IEscrow, Pausable, MessageSigned, Fees, Arbitrable, Proxiable { EscrowTransaction[] public transactions; address public relayer; OfferStore public offerStore; UserStore public userStore; event CREATED284(uint indexed offerId, address indexed seller, address indexed buyer, uint escrowId); //inject NONSTANDARD NAMING event FUNDED669(uint indexed escrowId, address indexed buyer, uint expirationTime, uint amount); //inject NONSTANDARD NAMING event PAID949(uint indexed escrowId, address indexed seller); //inject NONSTANDARD NAMING event RELEASED780(uint indexed escrowId, address indexed seller, address indexed buyer, address destination, bool isDispute); //inject NONSTANDARD NAMING event CANCELED731(uint indexed escrowId, address indexed seller, address indexed buyer, bool isDispute); //inject NONSTANDARD NAMING event RATING242(uint indexed offerId, address indexed participant, uint indexed escrowId, uint rating, bool ratingSeller); //inject NONSTANDARD NAMING constructor( address _relayer, address _fallbackArbitrator, address _arbitratorLicenses, address _offerStore, address _userStore, address payable _feeDestination, uint _feeMilliPercent) Fees(_feeDestination, _feeMilliPercent) Arbitrable(_arbitratorLicenses, _fallbackArbitrator) public { _initialized = true; relayer = _relayer; offerStore = OfferStore(_offerStore); userStore = UserStore(_userStore); } function INIT444( //inject NONSTANDARD NAMING address _fallbackArbitrator, address _relayer, address _arbitratorLicenses, address _offerStore, address _userStore, address payable _feeDestination, uint _feeMilliPercent ) external { assert(_initialized == false); _initialized = true; fallbackArbitrator = _fallbackArbitrator; arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses); offerStore = OfferStore(_offerStore); userStore = UserStore(_userStore); relayer = _relayer; feeDestination = _feeDestination; feeMilliPercent = _feeMilliPercent; paused = false; _SETOWNER235(msg.sender); } function UPDATECODE511(address newCode) public ONLYOWNER677 { //inject NONSTANDARD NAMING UPDATECODEADDRESS579(newCode); } function SETRELAYER20(address _relayer) external ONLYOWNER677 { //inject NONSTANDARD NAMING relayer = _relayer; } function SETFALLBACKARBITRATOR834(address _fallbackArbitrator) external ONLYOWNER677 { //inject NONSTANDARD NAMING fallbackArbitrator = _fallbackArbitrator; } function SETARBITRATORLICENSE102(address _arbitratorLicenses) external ONLYOWNER677 { //inject NONSTANDARD NAMING arbitratorLicenses = ArbitrationLicense(_arbitratorLicenses); } function SETMETADATASTORE408(address _offerStore, address _userStore) external ONLYOWNER677 { //inject NONSTANDARD NAMING offerStore = OfferStore(_offerStore); userStore = UserStore(_userStore); } function _CREATETRANSACTION768( //inject NONSTANDARD NAMING address payable _buyer, address payable _destination, uint _offerId, uint _tokenAmount, uint _fiatAmount ) internal WHENNOTPAUSED504 returns(uint escrowId) { address payable seller; address payable arbitrator; bool deleted; address token; (token, , , , , , seller, arbitrator, deleted) = offerStore.OFFER296(_offerId); require(!deleted, "Offer is not valid"); require(seller != _buyer, "Seller and Buyer must be different"); require(arbitrator != _buyer && arbitrator != address(0), "Cannot buy offers where buyer is arbitrator"); require(_tokenAmount != 0 && _fiatAmount != 0, "Trade amounts cannot be 0"); escrowId = transactions.length++; EscrowTransaction storage trx = transactions[escrowId]; trx.offerId = _offerId; trx.token = token; trx.buyer = _buyer; trx.seller = seller; trx.destination = _destination; trx.arbitrator = arbitrator; trx.tokenAmount = _tokenAmount; trx.fiatAmount = _fiatAmount; emit CREATED284( _offerId, seller, _buyer, escrowId ); } function CREATEESCROW324( //inject NONSTANDARD NAMING uint _offerId, uint _tokenAmount, uint _fiatAmount, address payable _destination, string memory _contactData, string memory _location, string memory _username ) public returns(uint escrowId) { userStore.ADDORUPDATEUSER850(msg.sender, _contactData, _location, _username); escrowId = _CREATETRANSACTION768(msg.sender, _destination, _offerId, _tokenAmount, _fiatAmount); } function CREATEESCROW324( //inject NONSTANDARD NAMING uint _offerId, uint _tokenAmount, uint _fiatAmount, address payable _destination, string memory _contactData, string memory _location, string memory _username, uint _nonce, bytes memory _signature ) public returns(uint escrowId) { address payable _buyer = userStore.ADDORUPDATEUSER850(_signature, _contactData, _location, _username, _nonce); escrowId = _CREATETRANSACTION768(_buyer, _destination, _offerId, _tokenAmount, _fiatAmount); } function CREATEESCROW_RELAYED829( //inject NONSTANDARD NAMING address payable _sender, uint _offerId, uint _tokenAmount, uint _fiatAmount, address payable _destination, string calldata _contactData, string calldata _location, string calldata _username ) external returns(uint escrowId) { assert(msg.sender == relayer); userStore.ADDORUPDATEUSER850(_sender, _contactData, _location, _username); escrowId = _CREATETRANSACTION768(_sender, _destination, _offerId, _tokenAmount, _fiatAmount); } function FUND899(uint _escrowId) external payable WHENNOTPAUSED504 { //inject NONSTANDARD NAMING _FUND192(msg.sender, _escrowId); } function _FUND192(address _from, uint _escrowId) internal WHENNOTPAUSED504 { //inject NONSTANDARD NAMING require(transactions[_escrowId].seller == _from, "Only the seller can invoke this function"); require(transactions[_escrowId].status == EscrowStatus.CREATED, "Invalid escrow status"); transactions[_escrowId].expirationTime = block.timestamp + 5 days; transactions[_escrowId].status = EscrowStatus.FUNDED; uint tokenAmount = transactions[_escrowId].tokenAmount; address token = transactions[_escrowId].token; _PAYFEE642(_from, _escrowId, tokenAmount, token); emit FUNDED669(_escrowId, transactions[_escrowId].buyer, block.timestamp + 5 days, tokenAmount); } function CREATEANDFUND840 ( //inject NONSTANDARD NAMING uint _offerId, uint _tokenAmount, uint _fiatAmount, string memory _bContactData, string memory _bLocation, string memory _bUsername, uint _bNonce, bytes memory _bSignature ) public payable returns(uint escrowId) { address payable _buyer = userStore.ADDORUPDATEUSER850(_bSignature, _bContactData, _bLocation, _bUsername, _bNonce); escrowId = _CREATETRANSACTION768(_buyer, _buyer, _offerId, _tokenAmount, _fiatAmount); _FUND192(msg.sender, escrowId); } function _PAY687(address _sender, uint _escrowId) internal { //inject NONSTANDARD NAMING EscrowTransaction storage trx = transactions[_escrowId]; require(trx.status == EscrowStatus.FUNDED, "Transaction is not funded"); require(trx.expirationTime > block.timestamp, "Transaction already expired"); require(trx.buyer == _sender, "Only the buyer can invoke this function"); trx.status = EscrowStatus.PAID; emit PAID949(_escrowId, trx.seller); } function PAY204(uint _escrowId) external { //inject NONSTANDARD NAMING _PAY687(msg.sender, _escrowId); } function PAY_RELAYED312(address _sender, uint _escrowId) external { //inject NONSTANDARD NAMING assert(msg.sender == relayer); _PAY687(_sender, _escrowId); } function PAYSIGNHASH991(uint _escrowId) public view returns(bytes32){ //inject NONSTANDARD NAMING return keccak256( abi.encodePacked( address(this), "pay(uint256)", _escrowId ) ); } function PAY204(uint _escrowId, bytes calldata _signature) external { //inject NONSTANDARD NAMING address sender = _RECOVERADDRESS15(_GETSIGNHASH525(PAYSIGNHASH991(_escrowId)), _signature); _PAY687(sender, _escrowId); } function _RELEASE35(uint _escrowId, EscrowTransaction storage _trx, bool _isDispute) internal { //inject NONSTANDARD NAMING require(_trx.status != EscrowStatus.RELEASED, "Already released"); _trx.status = EscrowStatus.RELEASED; if(!_isDispute){ offerStore.REFUNDSTAKE487(_trx.offerId); } address token = _trx.token; if(token == address(0)){ (bool success, ) = _trx.destination.call.value(_trx.tokenAmount)(""); require(success, "Transfer failed."); } else { require(_SAFETRANSFER911(ERC20Token(token), _trx.buyer, _trx.tokenAmount), "Couldn't transfer funds"); } _RELEASEFEE319(_trx.arbitrator, _trx.tokenAmount, token, _isDispute); emit RELEASED780(_escrowId, _trx.seller, _trx.buyer, _trx.destination, _isDispute); } function RELEASE349(uint _escrowId) external { //inject NONSTANDARD NAMING EscrowStatus mStatus = transactions[_escrowId].status; require(transactions[_escrowId].seller == msg.sender, "Only the seller can invoke this function"); require(mStatus == EscrowStatus.PAID || mStatus == EscrowStatus.FUNDED, "Invalid transaction status"); require(!_ISDISPUTED184(_escrowId), "Can't release a transaction that has an arbitration process"); _RELEASE35(_escrowId, transactions[_escrowId], false); } function CANCEL601(uint _escrowId) external WHENNOTPAUSED504 { //inject NONSTANDARD NAMING EscrowTransaction storage trx = transactions[_escrowId]; EscrowStatus mStatus = trx.status; require(mStatus == EscrowStatus.FUNDED || mStatus == EscrowStatus.CREATED, "Only transactions in created or funded state can be canceled"); require(trx.buyer == msg.sender || trx.seller == msg.sender, "Only participants can invoke this function"); if(mStatus == EscrowStatus.FUNDED){ if(msg.sender == trx.seller){ require(trx.expirationTime < block.timestamp, "Can only be canceled after expiration"); } } _CANCEL322(_escrowId, trx, false); } // Same as cancel, but relayed by a contract so we get the sender as param function CANCEL_RELAYED801(address _sender, uint _escrowId) external { //inject NONSTANDARD NAMING assert(msg.sender == relayer); EscrowTransaction storage trx = transactions[_escrowId]; EscrowStatus mStatus = trx.status; require(trx.buyer == _sender, "Only the buyer can invoke this function"); require(mStatus == EscrowStatus.FUNDED || mStatus == EscrowStatus.CREATED, "Only transactions in created or funded state can be canceled"); _CANCEL322(_escrowId, trx, false); } function _CANCEL322(uint _escrowId, EscrowTransaction storage trx, bool isDispute) internal { //inject NONSTANDARD NAMING EscrowStatus origStatus = trx.status; require(trx.status != EscrowStatus.CANCELED, "Already canceled"); trx.status = EscrowStatus.CANCELED; if (origStatus == EscrowStatus.FUNDED) { address token = trx.token; uint amount = trx.tokenAmount; if (!isDispute) { amount += _GETVALUEOFFMILLIPERCENT932(trx.tokenAmount, feeMilliPercent); } if (token == address(0)) { (bool success, ) = trx.seller.call.value(amount)(""); require(success, "Transfer failed."); } else { ERC20Token erc20token = ERC20Token(token); require(_SAFETRANSFER911(erc20token, trx.seller, amount), "Transfer failed"); } } trx.status = EscrowStatus.CANCELED; emit CANCELED731(_escrowId, trx.seller, trx.buyer, isDispute); } function _RATETRANSACTION102(address _sender, uint _escrowId, uint _rate) internal { //inject NONSTANDARD NAMING require(_rate >= 1, "Rating needs to be at least 1"); require(_rate <= 5, "Rating needs to be at less than or equal to 5"); EscrowTransaction storage trx = transactions[_escrowId]; require(trx.status == EscrowStatus.RELEASED || HADDISPUTE385(_escrowId), "Transaction not completed yet"); if (trx.buyer == _sender) { require(trx.sellerRating == 0, "Transaction already rated"); emit RATING242(trx.offerId, trx.seller, _escrowId, _rate, true); trx.sellerRating = _rate; } else if (trx.seller == _sender) { require(trx.buyerRating == 0, "Transaction already rated"); emit RATING242(trx.offerId, trx.buyer, _escrowId, _rate, false); trx.buyerRating = _rate; } else { revert("Only participants can invoke this function"); } } function RATETRANSACTION74(uint _escrowId, uint _rate) external { //inject NONSTANDARD NAMING _RATETRANSACTION102(msg.sender, _escrowId, _rate); } // Same as rateTransaction, but relayed by a contract so we get the sender as param function RATETRANSACTION_RELAYED289(address _sender, uint _escrowId, uint _rate) external { //inject NONSTANDARD NAMING assert(msg.sender == relayer); _RATETRANSACTION102(_sender, _escrowId, _rate); } function GETBASICTRADEDATA166(uint _escrowId) //inject NONSTANDARD NAMING external view returns(address payable buyer, address payable seller, address token, uint tokenAmount) { buyer = transactions[_escrowId].buyer; seller = transactions[_escrowId].seller; tokenAmount = transactions[_escrowId].tokenAmount; token = transactions[_escrowId].token; return (buyer, seller, token, tokenAmount); } function OPENCASE508(uint _escrowId, uint8 _motive) external { //inject NONSTANDARD NAMING EscrowTransaction storage trx = transactions[_escrowId]; require(!ISDISPUTED635(_escrowId), "Case already exist"); require(trx.buyer == msg.sender || trx.seller == msg.sender, "Only participants can invoke this function"); require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions"); _OPENDISPUTE139(_escrowId, msg.sender, _motive); } function OPENCASE_RELAYED502(address _sender, uint256 _escrowId, uint8 _motive) external { //inject NONSTANDARD NAMING assert(msg.sender == relayer); EscrowTransaction storage trx = transactions[_escrowId]; require(!ISDISPUTED635(_escrowId), "Case already exist"); require(trx.buyer == _sender, "Only the buyer can invoke this function"); require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions"); _OPENDISPUTE139(_escrowId, _sender, _motive); } function OPENCASE508(uint _escrowId, uint8 _motive, bytes calldata _signature) external { //inject NONSTANDARD NAMING EscrowTransaction storage trx = transactions[_escrowId]; require(!ISDISPUTED635(_escrowId), "Case already exist"); require(trx.status == EscrowStatus.PAID, "Cases can only be open for paid transactions"); address senderAddress = _RECOVERADDRESS15(_GETSIGNHASH525(OPENCASESIGNHASH754(_escrowId, _motive)), _signature); require(trx.buyer == senderAddress || trx.seller == senderAddress, "Only participants can invoke this function"); _OPENDISPUTE139(_escrowId, msg.sender, _motive); } function _SOLVEDISPUTE500(uint _escrowId, bool _releaseFunds, address _arbitrator) internal { //inject NONSTANDARD NAMING EscrowTransaction storage trx = transactions[_escrowId]; require(trx.buyer != _arbitrator && trx.seller != _arbitrator, "Arbitrator cannot be part of transaction"); if (_releaseFunds) { _RELEASE35(_escrowId, trx, true); offerStore.SLASHSTAKE918(trx.offerId); } else { _CANCEL322(_escrowId, trx, true); _RELEASEFEE319(trx.arbitrator, trx.tokenAmount, trx.token, true); } } function _GETARBITRATOR209(uint _escrowId) internal view returns(address) { //inject NONSTANDARD NAMING return transactions[_escrowId].arbitrator; } function OPENCASESIGNHASH754(uint _escrowId, uint8 _motive) public view returns(bytes32){ //inject NONSTANDARD NAMING return keccak256( abi.encodePacked( address(this), "openCase(uint256)", _escrowId, _motive ) ); } function RECEIVEAPPROVAL139(address _from, uint256 _amount, address _token, bytes memory _data) public { //inject NONSTANDARD NAMING require(_token == address(msg.sender), "Wrong call"); require(_data.length == 36, "Wrong data length"); bytes4 sig; uint256 escrowId; (sig, escrowId) = _ABIDECODEFUNDCALL446(_data); if (sig == bytes4(0xca1d209d)){ // fund(uint256) uint tokenAmount = transactions[escrowId].tokenAmount; require(_amount == tokenAmount + _GETVALUEOFFMILLIPERCENT932(tokenAmount, feeMilliPercent), "Invalid amount"); _FUND192(_from, escrowId); } else { revert("Wrong method selector"); } } function _ABIDECODEFUNDCALL446(bytes memory _data) internal pure returns (bytes4 sig, uint256 escrowId) { //inject NONSTANDARD NAMING assembly { sig := mload(add(_data, add(0x20, 0))) escrowId := mload(add(_data, 36)) } } function WITHDRAW_EMERGENCY162(uint _escrowId) external WHENPAUSED494 { //inject NONSTANDARD NAMING EscrowTransaction storage trx = transactions[_escrowId]; require(trx.status == EscrowStatus.FUNDED, "Cannot withdraw from escrow in a stage different from FUNDED. Open a case"); _CANCEL322(_escrowId, trx, false); } }
inject NONSTANDARD NAMING
function GETOFFERIDS508(address _address) external view returns (uint256[] memory) {
12,593,911
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4978, 8797, 654, 19516, 3361, 28, 12, 2867, 389, 2867, 13, 3903, 1476, 1135, 261, 11890, 5034, 8526, 3778, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./lib/ReEncryptionValidator.sol"; import "./lib/SignatureVerifier.sol"; import "./StakingEscrow.sol"; import "./proxy/Upgradeable.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/math/Math.sol"; /** * @title Adjudicator * @notice Supervises stakers' behavior and punishes when something's wrong. * @dev |v2.1.2| */ contract Adjudicator is Upgradeable { using SafeMath for uint256; using UmbralDeserializer for bytes; event CFragEvaluated( bytes32 indexed evaluationHash, address indexed investigator, bool correctness ); event IncorrectCFragVerdict( bytes32 indexed evaluationHash, address indexed worker, address indexed staker ); // used only for upgrading bytes32 constant RESERVED_CAPSULE_AND_CFRAG_BYTES = bytes32(0); address constant RESERVED_ADDRESS = address(0); StakingEscrow public immutable escrow; SignatureVerifier.HashAlgorithm public immutable hashAlgorithm; uint256 public immutable basePenalty; uint256 public immutable penaltyHistoryCoefficient; uint256 public immutable percentagePenaltyCoefficient; uint256 public immutable rewardCoefficient; mapping (address => uint256) public penaltyHistory; mapping (bytes32 => bool) public evaluatedCFrags; /** * @param _escrow Escrow contract * @param _hashAlgorithm Hashing algorithm * @param _basePenalty Base for the penalty calculation * @param _penaltyHistoryCoefficient Coefficient for calculating the penalty depending on the history * @param _percentagePenaltyCoefficient Coefficient for calculating the percentage penalty * @param _rewardCoefficient Coefficient for calculating the reward */ constructor( StakingEscrow _escrow, SignatureVerifier.HashAlgorithm _hashAlgorithm, uint256 _basePenalty, uint256 _penaltyHistoryCoefficient, uint256 _percentagePenaltyCoefficient, uint256 _rewardCoefficient ) { // Sanity checks. require(_escrow.secondsPerPeriod() > 0 && // This contract has an escrow, and it's not the null address. // The reward and penalty coefficients are set. _percentagePenaltyCoefficient != 0 && _rewardCoefficient != 0); escrow = _escrow; hashAlgorithm = _hashAlgorithm; basePenalty = _basePenalty; percentagePenaltyCoefficient = _percentagePenaltyCoefficient; penaltyHistoryCoefficient = _penaltyHistoryCoefficient; rewardCoefficient = _rewardCoefficient; } /** * @notice Submit proof that a worker created wrong CFrag * @param _capsuleBytes Serialized capsule * @param _cFragBytes Serialized CFrag * @param _cFragSignature Signature of CFrag by worker * @param _taskSignature Signature of task specification by Bob * @param _requesterPublicKey Bob's signing public key, also known as "stamp" * @param _workerPublicKey Worker's signing public key, also known as "stamp" * @param _workerIdentityEvidence Signature of worker's public key by worker's eth-key * @param _preComputedData Additional pre-computed data for CFrag correctness verification */ function evaluateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _cFragSignature, bytes memory _taskSignature, bytes memory _requesterPublicKey, bytes memory _workerPublicKey, bytes memory _workerIdentityEvidence, bytes memory _preComputedData ) public { // 1. Check that CFrag is not evaluated yet bytes32 evaluationHash = SignatureVerifier.hash( abi.encodePacked(_capsuleBytes, _cFragBytes), hashAlgorithm); require(!evaluatedCFrags[evaluationHash], "This CFrag has already been evaluated."); evaluatedCFrags[evaluationHash] = true; // 2. Verify correctness of re-encryption bool cFragIsCorrect = ReEncryptionValidator.validateCFrag(_capsuleBytes, _cFragBytes, _preComputedData); emit CFragEvaluated(evaluationHash, msg.sender, cFragIsCorrect); // 3. Verify associated public keys and signatures require(ReEncryptionValidator.checkSerializedCoordinates(_workerPublicKey), "Staker's public key is invalid"); require(ReEncryptionValidator.checkSerializedCoordinates(_requesterPublicKey), "Requester's public key is invalid"); UmbralDeserializer.PreComputedData memory precomp = _preComputedData.toPreComputedData(); // Verify worker's signature of CFrag require(SignatureVerifier.verify( _cFragBytes, abi.encodePacked(_cFragSignature, precomp.lostBytes[1]), _workerPublicKey, hashAlgorithm), "CFrag signature is invalid" ); // Verify worker's signature of taskSignature and that it corresponds to cfrag.proof.metadata UmbralDeserializer.CapsuleFrag memory cFrag = _cFragBytes.toCapsuleFrag(); require(SignatureVerifier.verify( _taskSignature, abi.encodePacked(cFrag.proof.metadata, precomp.lostBytes[2]), _workerPublicKey, hashAlgorithm), "Task signature is invalid" ); // Verify that _taskSignature is bob's signature of the task specification. // A task specification is: capsule + ursula pubkey + alice address + blockhash bytes32 stampXCoord; assembly { stampXCoord := mload(add(_workerPublicKey, 32)) } bytes memory stamp = abi.encodePacked(precomp.lostBytes[4], stampXCoord); require(SignatureVerifier.verify( abi.encodePacked(_capsuleBytes, stamp, _workerIdentityEvidence, precomp.alicesKeyAsAddress, bytes32(0)), abi.encodePacked(_taskSignature, precomp.lostBytes[3]), _requesterPublicKey, hashAlgorithm), "Specification signature is invalid" ); // 4. Extract worker address from stamp signature. address worker = SignatureVerifier.recover( SignatureVerifier.hashEIP191(stamp, byte(0x45)), // Currently, we use version E (0x45) of EIP191 signatures _workerIdentityEvidence); address staker = escrow.stakerFromWorker(worker); require(staker != address(0), "Worker must be related to a staker"); // 5. Check that staker can be slashed uint256 stakerValue = escrow.getAllTokens(staker); require(stakerValue > 0, "Staker has no tokens"); // 6. If CFrag was incorrect, slash staker if (!cFragIsCorrect) { (uint256 penalty, uint256 reward) = calculatePenaltyAndReward(staker, stakerValue); escrow.slashStaker(staker, penalty, msg.sender, reward); emit IncorrectCFragVerdict(evaluationHash, worker, staker); } } /** * @notice Calculate penalty to the staker and reward to the investigator * @param _staker Staker's address * @param _stakerValue Amount of tokens that belong to the staker */ function calculatePenaltyAndReward(address _staker, uint256 _stakerValue) internal returns (uint256 penalty, uint256 reward) { penalty = basePenalty.add(penaltyHistoryCoefficient.mul(penaltyHistory[_staker])); penalty = Math.min(penalty, _stakerValue.div(percentagePenaltyCoefficient)); reward = penalty.div(rewardCoefficient); // TODO add maximum condition or other overflow protection or other penalty condition (#305?) penaltyHistory[_staker] = penaltyHistory[_staker].add(1); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); require(delegateGet(_testTarget, this.evaluatedCFrags.selector, evaluationCFragHash) == (evaluatedCFrags[evaluationCFragHash] ? 1 : 0)); require(delegateGet(_testTarget, this.penaltyHistory.selector, bytes32(bytes20(RESERVED_ADDRESS))) == penaltyHistory[RESERVED_ADDRESS]); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // preparation for the verifyState method bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); evaluatedCFrags[evaluationCFragHash] = true; penaltyHistory[RESERVED_ADDRESS] = 123; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./UmbralDeserializer.sol"; import "./SignatureVerifier.sol"; /** * @notice Validates re-encryption correctness. */ library ReEncryptionValidator { using UmbralDeserializer for bytes; //------------------------------// // Umbral-specific constants // //------------------------------// // See parameter `u` of `UmbralParameters` class in pyUmbral // https://github.com/nucypher/pyUmbral/blob/master/umbral/params.py uint8 public constant UMBRAL_PARAMETER_U_SIGN = 0x02; uint256 public constant UMBRAL_PARAMETER_U_XCOORD = 0x03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f; uint256 public constant UMBRAL_PARAMETER_U_YCOORD = 0x7880ed56962d7c0ae44d6f14bb53b5fe64b31ea44a41d0316f3a598778f0f936; //------------------------------// // SECP256K1-specific constants // //------------------------------// // Base field order uint256 constant FIELD_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // -2 mod FIELD_ORDER uint256 constant MINUS_2 = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2d; // (-1/2) mod FIELD_ORDER uint256 constant MINUS_ONE_HALF = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff7ffffe17; // /** * @notice Check correctness of re-encryption * @param _capsuleBytes Capsule * @param _cFragBytes Capsule frag * @param _precomputedBytes Additional precomputed data */ function validateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _precomputedBytes ) internal pure returns (bool) { UmbralDeserializer.Capsule memory _capsule = _capsuleBytes.toCapsule(); UmbralDeserializer.CapsuleFrag memory _cFrag = _cFragBytes.toCapsuleFrag(); UmbralDeserializer.PreComputedData memory _precomputed = _precomputedBytes.toPreComputedData(); // Extract Alice's address and check that it corresponds to the one provided address alicesAddress = SignatureVerifier.recover( _precomputed.hashedKFragValidityMessage, abi.encodePacked(_cFrag.proof.kFragSignature, _precomputed.lostBytes[0]) ); require(alicesAddress == _precomputed.alicesKeyAsAddress, "Bad KFrag signature"); // Compute proof's challenge scalar h, used in all ZKP verification equations uint256 h = computeProofChallengeScalar(_capsule, _cFrag); ////// // Verifying 1st equation: z*E == h*E_1 + E_2 ////// // Input validation: E require(checkCompressedPoint( _capsule.pointE.sign, _capsule.pointE.xCoord, _precomputed.pointEyCoord), "Precomputed Y coordinate of E doesn't correspond to compressed E point" ); // Input validation: z*E require(isOnCurve(_precomputed.pointEZxCoord, _precomputed.pointEZyCoord), "Point zE is not a valid EC point" ); require(ecmulVerify( _capsule.pointE.xCoord, // E_x _precomputed.pointEyCoord, // E_y _cFrag.proof.bnSig, // z _precomputed.pointEZxCoord, // zE_x _precomputed.pointEZyCoord), // zE_y "Precomputed z*E value is incorrect" ); // Input validation: E1 require(checkCompressedPoint( _cFrag.pointE1.sign, // E1_sign _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord), // E1_y "Precomputed Y coordinate of E1 doesn't correspond to compressed E1 point" ); // Input validation: h*E1 require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord), "Point h*E1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord, // E1_y h, _precomputed.pointE1HxCoord, // hE1_x _precomputed.pointE1HyCoord), // hE1_y "Precomputed h*E1 value is incorrect" ); // Input validation: E2 require(checkCompressedPoint( _cFrag.proof.pointE2.sign, // E2_sign _cFrag.proof.pointE2.xCoord, // E2_x _precomputed.pointE2yCoord), // E2_y "Precomputed Y coordinate of E2 doesn't correspond to compressed E2 point" ); bool equation_holds = eqAffineJacobian( [_precomputed.pointEZxCoord, _precomputed.pointEZyCoord], addAffineJacobian( [_cFrag.proof.pointE2.xCoord, _precomputed.pointE2yCoord], [_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 2nd equation: z*V == h*V_1 + V_2 ////// // Input validation: V require(checkCompressedPoint( _capsule.pointV.sign, _capsule.pointV.xCoord, _precomputed.pointVyCoord), "Precomputed Y coordinate of V doesn't correspond to compressed V point" ); // Input validation: z*V require(isOnCurve(_precomputed.pointVZxCoord, _precomputed.pointVZyCoord), "Point zV is not a valid EC point" ); require(ecmulVerify( _capsule.pointV.xCoord, // V_x _precomputed.pointVyCoord, // V_y _cFrag.proof.bnSig, // z _precomputed.pointVZxCoord, // zV_x _precomputed.pointVZyCoord), // zV_y "Precomputed z*V value is incorrect" ); // Input validation: V1 require(checkCompressedPoint( _cFrag.pointV1.sign, // V1_sign _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord), // V1_y "Precomputed Y coordinate of V1 doesn't correspond to compressed V1 point" ); // Input validation: h*V1 require(isOnCurve(_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord), "Point h*V1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord, // V1_y h, _precomputed.pointV1HxCoord, // h*V1_x _precomputed.pointV1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: V2 require(checkCompressedPoint( _cFrag.proof.pointV2.sign, // V2_sign _cFrag.proof.pointV2.xCoord, // V2_x _precomputed.pointV2yCoord), // V2_y "Precomputed Y coordinate of V2 doesn't correspond to compressed V2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointVZxCoord, _precomputed.pointVZyCoord], addAffineJacobian( [_cFrag.proof.pointV2.xCoord, _precomputed.pointV2yCoord], [_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 3rd equation: z*U == h*U_1 + U_2 ////// // We don't have to validate U since it's fixed and hard-coded // Input validation: z*U require(isOnCurve(_precomputed.pointUZxCoord, _precomputed.pointUZyCoord), "Point z*U is not a valid EC point" ); require(ecmulVerify( UMBRAL_PARAMETER_U_XCOORD, // U_x UMBRAL_PARAMETER_U_YCOORD, // U_y _cFrag.proof.bnSig, // z _precomputed.pointUZxCoord, // zU_x _precomputed.pointUZyCoord), // zU_y "Precomputed z*U value is incorrect" ); // Input validation: U1 (a.k.a. KFragCommitment) require(checkCompressedPoint( _cFrag.proof.pointKFragCommitment.sign, // U1_sign _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord), // U1_y "Precomputed Y coordinate of U1 doesn't correspond to compressed U1 point" ); // Input validation: h*U1 require(isOnCurve(_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord), "Point h*U1 is not a valid EC point" ); require(ecmulVerify( _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord, // U1_y h, _precomputed.pointU1HxCoord, // h*V1_x _precomputed.pointU1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: U2 (a.k.a. KFragPok ("proof of knowledge")) require(checkCompressedPoint( _cFrag.proof.pointKFragPok.sign, // U2_sign _cFrag.proof.pointKFragPok.xCoord, // U2_x _precomputed.pointU2yCoord), // U2_y "Precomputed Y coordinate of U2 doesn't correspond to compressed U2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointUZxCoord, _precomputed.pointUZyCoord], addAffineJacobian( [_cFrag.proof.pointKFragPok.xCoord, _precomputed.pointU2yCoord], [_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord] ) ); return equation_holds; } function computeProofChallengeScalar( UmbralDeserializer.Capsule memory _capsule, UmbralDeserializer.CapsuleFrag memory _cFrag ) internal pure returns (uint256) { // Compute h = hash_to_bignum(e, e1, e2, v, v1, v2, u, u1, u2, metadata) bytes memory hashInput = abi.encodePacked( // Point E _capsule.pointE.sign, _capsule.pointE.xCoord, // Point E1 _cFrag.pointE1.sign, _cFrag.pointE1.xCoord, // Point E2 _cFrag.proof.pointE2.sign, _cFrag.proof.pointE2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point V _capsule.pointV.sign, _capsule.pointV.xCoord, // Point V1 _cFrag.pointV1.sign, _cFrag.pointV1.xCoord, // Point V2 _cFrag.proof.pointV2.sign, _cFrag.proof.pointV2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point U bytes1(UMBRAL_PARAMETER_U_SIGN), bytes32(UMBRAL_PARAMETER_U_XCOORD), // Point U1 _cFrag.proof.pointKFragCommitment.sign, _cFrag.proof.pointKFragCommitment.xCoord, // Point U2 _cFrag.proof.pointKFragPok.sign, _cFrag.proof.pointKFragPok.xCoord, // Re-encryption metadata _cFrag.proof.metadata ); uint256 h = extendedKeccakToBN(hashInput); return h; } function extendedKeccakToBN (bytes memory _data) internal pure returns (uint256) { bytes32 upper; bytes32 lower; // Umbral prepends to the data a customization string of 64-bytes. // In the case of hash_to_curvebn is 'hash_to_curvebn', padded with zeroes. bytes memory input = abi.encodePacked(bytes32("hash_to_curvebn"), bytes32(0x00), _data); (upper, lower) = (keccak256(abi.encodePacked(uint8(0x00), input)), keccak256(abi.encodePacked(uint8(0x01), input))); // Let n be the order of secp256k1's group (n = 2^256 - 0x1000003D1) // n_minus_1 = n - 1 // delta = 2^256 mod n_minus_1 uint256 delta = 0x14551231950b75fc4402da1732fc9bec0; uint256 n_minus_1 = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140; uint256 upper_half = mulmod(uint256(upper), delta, n_minus_1); return 1 + addmod(upper_half, uint256(lower), n_minus_1); } /// @notice Tests if a compressed point is valid, wrt to its corresponding Y coordinate /// @param _pointSign The sign byte from the compressed notation: 0x02 if the Y coord is even; 0x03 otherwise /// @param _pointX The X coordinate of an EC point in affine representation /// @param _pointY The Y coordinate of an EC point in affine representation /// @return true iff _pointSign and _pointX are the compressed representation of (_pointX, _pointY) function checkCompressedPoint( uint8 _pointSign, uint256 _pointX, uint256 _pointY ) internal pure returns(bool) { bool correct_sign = _pointY % 2 == _pointSign - 2; return correct_sign && isOnCurve(_pointX, _pointY); } /// @notice Tests if the given serialized coordinates represent a valid EC point /// @param _coords The concatenation of serialized X and Y coordinates /// @return true iff coordinates X and Y are a valid point function checkSerializedCoordinates(bytes memory _coords) internal pure returns(bool) { require(_coords.length == 64, "Serialized coordinates should be 64 B"); uint256 coordX; uint256 coordY; assembly { coordX := mload(add(_coords, 32)) coordY := mload(add(_coords, 64)) } return isOnCurve(coordX, coordY); } /// @notice Tests if a point is on the secp256k1 curve /// @param Px The X coordinate of an EC point in affine representation /// @param Py The Y coordinate of an EC point in affine representation /// @return true if (Px, Py) is a valid secp256k1 point; false otherwise function isOnCurve(uint256 Px, uint256 Py) internal pure returns (bool) { uint256 p = FIELD_ORDER; if (Px >= p || Py >= p){ return false; } uint256 y2 = mulmod(Py, Py, p); uint256 x3_plus_7 = addmod(mulmod(mulmod(Px, Px, p), Px, p), 7, p); return y2 == x3_plus_7; } // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/4 function ecmulVerify( uint256 x1, uint256 y1, uint256 scalar, uint256 qx, uint256 qy ) internal pure returns(bool) { uint256 curve_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; address signer = ecrecover(0, uint8(27 + (y1 % 2)), bytes32(x1), bytes32(mulmod(scalar, x1, curve_order))); address xyAddress = address(uint256(keccak256(abi.encodePacked(qx, qy))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return xyAddress == signer; } /// @notice Equality test of two points, in affine and Jacobian coordinates respectively /// @param P An EC point in affine coordinates /// @param Q An EC point in Jacobian coordinates /// @return true if P and Q represent the same point in affine coordinates; false otherwise function eqAffineJacobian( uint256[2] memory P, uint256[3] memory Q ) internal pure returns(bool){ uint256 Qz = Q[2]; if(Qz == 0){ return false; // Q is zero but P isn't. } uint256 p = FIELD_ORDER; uint256 Q_z_squared = mulmod(Qz, Qz, p); return mulmod(P[0], Q_z_squared, p) == Q[0] && mulmod(P[1], mulmod(Q_z_squared, Qz, p), p) == Q[1]; } /// @notice Adds two points in affine coordinates, with the result in Jacobian /// @dev Based on the addition formulas from http://www.hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2001-b.op3 /// @param P An EC point in affine coordinates /// @param Q An EC point in affine coordinates /// @return R An EC point in Jacobian coordinates with the sum, represented by an array of 3 uint256 function addAffineJacobian( uint[2] memory P, uint[2] memory Q ) internal pure returns (uint[3] memory R) { uint256 p = FIELD_ORDER; uint256 a = P[0]; uint256 c = P[1]; uint256 t0 = Q[0]; uint256 t1 = Q[1]; if ((a == t0) && (c == t1)){ return doubleJacobian([a, c, 1]); } uint256 d = addmod(t1, p-c, p); // d = t1 - c uint256 b = addmod(t0, p-a, p); // b = t0 - a uint256 e = mulmod(b, b, p); // e = b^2 uint256 f = mulmod(e, b, p); // f = b^3 uint256 g = mulmod(a, e, p); R[0] = addmod(mulmod(d, d, p), p-addmod(mulmod(2, g, p), f, p), p); R[1] = addmod(mulmod(d, addmod(g, p-R[0], p), p), p-mulmod(c, f, p), p); R[2] = b; } /// @notice Point doubling in Jacobian coordinates /// @param P An EC point in Jacobian coordinates. /// @return Q An EC point in Jacobian coordinates function doubleJacobian(uint[3] memory P) internal pure returns (uint[3] memory Q) { uint256 z = P[2]; if (z == 0) return Q; uint256 p = FIELD_ORDER; uint256 x = P[0]; uint256 _2y = mulmod(2, P[1], p); uint256 _4yy = mulmod(_2y, _2y, p); uint256 s = mulmod(_4yy, x, p); uint256 m = mulmod(3, mulmod(x, x, p), p); uint256 t = addmod(mulmod(m, m, p), mulmod(MINUS_2, s, p),p); Q[0] = t; Q[1] = addmod(mulmod(m, addmod(s, p - t, p), p), mulmod(MINUS_ONE_HALF, mulmod(_4yy, _4yy, p), p), p); Q[2] = mulmod(_2y, z, p); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @notice Deserialization library for Umbral objects */ library UmbralDeserializer { struct Point { uint8 sign; uint256 xCoord; } struct Capsule { Point pointE; Point pointV; uint256 bnSig; } struct CorrectnessProof { Point pointE2; Point pointV2; Point pointKFragCommitment; Point pointKFragPok; uint256 bnSig; bytes kFragSignature; // 64 bytes bytes metadata; // any length } struct CapsuleFrag { Point pointE1; Point pointV1; bytes32 kFragId; Point pointPrecursor; CorrectnessProof proof; } struct PreComputedData { uint256 pointEyCoord; uint256 pointEZxCoord; uint256 pointEZyCoord; uint256 pointE1yCoord; uint256 pointE1HxCoord; uint256 pointE1HyCoord; uint256 pointE2yCoord; uint256 pointVyCoord; uint256 pointVZxCoord; uint256 pointVZyCoord; uint256 pointV1yCoord; uint256 pointV1HxCoord; uint256 pointV1HyCoord; uint256 pointV2yCoord; uint256 pointUZxCoord; uint256 pointUZyCoord; uint256 pointU1yCoord; uint256 pointU1HxCoord; uint256 pointU1HyCoord; uint256 pointU2yCoord; bytes32 hashedKFragValidityMessage; address alicesKeyAsAddress; bytes5 lostBytes; } uint256 constant BIGNUM_SIZE = 32; uint256 constant POINT_SIZE = 33; uint256 constant SIGNATURE_SIZE = 64; uint256 constant CAPSULE_SIZE = 2 * POINT_SIZE + BIGNUM_SIZE; uint256 constant CORRECTNESS_PROOF_SIZE = 4 * POINT_SIZE + BIGNUM_SIZE + SIGNATURE_SIZE; uint256 constant CAPSULE_FRAG_SIZE = 3 * POINT_SIZE + BIGNUM_SIZE; uint256 constant FULL_CAPSULE_FRAG_SIZE = CAPSULE_FRAG_SIZE + CORRECTNESS_PROOF_SIZE; uint256 constant PRECOMPUTED_DATA_SIZE = (20 * BIGNUM_SIZE) + 32 + 20 + 5; /** * @notice Deserialize to capsule (not activated) */ function toCapsule(bytes memory _capsuleBytes) internal pure returns (Capsule memory capsule) { require(_capsuleBytes.length == CAPSULE_SIZE); uint256 pointer = getPointer(_capsuleBytes); pointer = copyPoint(pointer, capsule.pointE); pointer = copyPoint(pointer, capsule.pointV); capsule.bnSig = uint256(getBytes32(pointer)); } /** * @notice Deserialize to correctness proof * @param _pointer Proof bytes memory pointer * @param _proofBytesLength Proof bytes length */ function toCorrectnessProof(uint256 _pointer, uint256 _proofBytesLength) internal pure returns (CorrectnessProof memory proof) { require(_proofBytesLength >= CORRECTNESS_PROOF_SIZE); _pointer = copyPoint(_pointer, proof.pointE2); _pointer = copyPoint(_pointer, proof.pointV2); _pointer = copyPoint(_pointer, proof.pointKFragCommitment); _pointer = copyPoint(_pointer, proof.pointKFragPok); proof.bnSig = uint256(getBytes32(_pointer)); _pointer += BIGNUM_SIZE; proof.kFragSignature = new bytes(SIGNATURE_SIZE); // TODO optimize, just two mload->mstore (#1500) _pointer = copyBytes(_pointer, proof.kFragSignature, SIGNATURE_SIZE); if (_proofBytesLength > CORRECTNESS_PROOF_SIZE) { proof.metadata = new bytes(_proofBytesLength - CORRECTNESS_PROOF_SIZE); copyBytes(_pointer, proof.metadata, proof.metadata.length); } } /** * @notice Deserialize to correctness proof */ function toCorrectnessProof(bytes memory _proofBytes) internal pure returns (CorrectnessProof memory proof) { uint256 pointer = getPointer(_proofBytes); return toCorrectnessProof(pointer, _proofBytes.length); } /** * @notice Deserialize to CapsuleFrag */ function toCapsuleFrag(bytes memory _cFragBytes) internal pure returns (CapsuleFrag memory cFrag) { uint256 cFragBytesLength = _cFragBytes.length; require(cFragBytesLength >= FULL_CAPSULE_FRAG_SIZE); uint256 pointer = getPointer(_cFragBytes); pointer = copyPoint(pointer, cFrag.pointE1); pointer = copyPoint(pointer, cFrag.pointV1); cFrag.kFragId = getBytes32(pointer); pointer += BIGNUM_SIZE; pointer = copyPoint(pointer, cFrag.pointPrecursor); cFrag.proof = toCorrectnessProof(pointer, cFragBytesLength - CAPSULE_FRAG_SIZE); } /** * @notice Deserialize to precomputed data */ function toPreComputedData(bytes memory _preComputedData) internal pure returns (PreComputedData memory data) { require(_preComputedData.length == PRECOMPUTED_DATA_SIZE); uint256 initial_pointer = getPointer(_preComputedData); uint256 pointer = initial_pointer; data.pointEyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.hashedKFragValidityMessage = getBytes32(pointer); pointer += 32; data.alicesKeyAsAddress = address(bytes20(getBytes32(pointer))); pointer += 20; // Lost bytes: a bytes5 variable holding the following byte values: // 0: kfrag signature recovery value v // 1: cfrag signature recovery value v // 2: metadata signature recovery value v // 3: specification signature recovery value v // 4: ursula pubkey sign byte data.lostBytes = bytes5(getBytes32(pointer)); pointer += 5; require(pointer == initial_pointer + PRECOMPUTED_DATA_SIZE); } // TODO extract to external library if needed (#1500) /** * @notice Get the memory pointer for start of array */ function getPointer(bytes memory _bytes) internal pure returns (uint256 pointer) { assembly { pointer := add(_bytes, 32) // skip array length } } /** * @notice Copy point data from memory in the pointer position */ function copyPoint(uint256 _pointer, Point memory _point) internal pure returns (uint256 resultPointer) { // TODO optimize, copy to point memory directly (#1500) uint8 temp; uint256 xCoord; assembly { temp := byte(0, mload(_pointer)) xCoord := mload(add(_pointer, 1)) } _point.sign = temp; _point.xCoord = xCoord; resultPointer = _pointer + POINT_SIZE; } /** * @notice Read 1 byte from memory in the pointer position */ function getByte(uint256 _pointer) internal pure returns (byte result) { bytes32 word; assembly { word := mload(_pointer) } result = word[0]; return result; } /** * @notice Read 32 bytes from memory in the pointer position */ function getBytes32(uint256 _pointer) internal pure returns (bytes32 result) { assembly { result := mload(_pointer) } } /** * @notice Copy bytes from the source pointer to the target array * @dev Assumes that enough memory has been allocated to store in target. * Also assumes that '_target' was the last thing that was allocated * @param _bytesPointer Source memory pointer * @param _target Target array * @param _bytesLength Number of bytes to copy */ function copyBytes(uint256 _bytesPointer, bytes memory _target, uint256 _bytesLength) internal pure returns (uint256 resultPointer) { // Exploiting the fact that '_target' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. assembly { // evm operations on words let words := div(add(_bytesLength, 31), 32) let source := _bytesPointer let destination := add(_target, 32) for { let i := 0 } // start at arr + 32 -> first byte corresponds to length lt(i, words) { i := add(i, 1) } { let offset := mul(i, 32) mstore(add(destination, offset), mload(add(source, offset))) } mstore(add(_target, add(32, mload(_target))), 0) } resultPointer = _bytesPointer + _bytesLength; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @notice Library to recover address and verify signatures * @dev Simple wrapper for `ecrecover` */ library SignatureVerifier { enum HashAlgorithm {KECCAK256, SHA256, RIPEMD160} // Header for Version E as defined by EIP191. First byte ('E') is also the version bytes25 constant EIP191_VERSION_E_HEADER = "Ethereum Signed Message:\n"; /** * @notice Recover signer address from hash and signature * @param _hash 32 bytes message hash * @param _signature Signature of hash - 32 bytes r + 32 bytes s + 1 byte v (could be 0, 1, 27, 28) */ function recover(bytes32 _hash, bytes memory _signature) internal pure returns (address) { require(_signature.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28); return ecrecover(_hash, v, r, s); } /** * @notice Transform public key to address * @param _publicKey secp256k1 public key */ function toAddress(bytes memory _publicKey) internal pure returns (address) { return address(uint160(uint256(keccak256(_publicKey)))); } /** * @notice Hash using one of pre built hashing algorithm * @param _message Signed message * @param _algorithm Hashing algorithm */ function hash(bytes memory _message, HashAlgorithm _algorithm) internal pure returns (bytes32 result) { if (_algorithm == HashAlgorithm.KECCAK256) { result = keccak256(_message); } else if (_algorithm == HashAlgorithm.SHA256) { result = sha256(_message); } else { result = ripemd160(_message); } } /** * @notice Verify ECDSA signature * @dev Uses one of pre built hashing algorithm * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _algorithm Hashing algorithm */ function verify( bytes memory _message, bytes memory _signature, bytes memory _publicKey, HashAlgorithm _algorithm ) internal pure returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hash(_message, _algorithm), _signature); } /** * @notice Hash message according to EIP191 signature specification * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Message to sign * @param _version EIP191 version to use */ function hashEIP191( bytes memory _message, byte _version ) internal view returns (bytes32 result) { if(_version == byte(0x00)){ // Version 0: Data with intended validator address validator = address(this); return keccak256(abi.encodePacked(byte(0x19), byte(0x00), validator, _message)); } else if (_version == byte(0x45)){ // Version E: personal_sign messages uint256 length = _message.length; require(length > 0, "Empty message not allowed for version E"); // Compute text-encoded length of message uint256 digits = 0; while (length != 0) { digits++; length /= 10; } bytes memory lengthAsText = new bytes(digits); length = _message.length; uint256 index = digits - 1; while (length != 0) { lengthAsText[index--] = byte(uint8(48 + length % 10)); length /= 10; } return keccak256(abi.encodePacked(byte(0x19), EIP191_VERSION_E_HEADER, lengthAsText, _message)); } else { revert("Unsupported EIP191 version"); } } /** * @notice Verify EIP191 signature * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _version EIP191 version to use */ function verifyEIP191( bytes memory _message, bytes memory _signature, bytes memory _publicKey, byte _version ) internal view returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hashEIP191(_message, _version), _signature); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../aragon/interfaces/IERC900History.sol"; import "./Issuer.sol"; import "./lib/Bits.sol"; import "./lib/Snapshot.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; /** * @notice PolicyManager interface */ interface PolicyManagerInterface { function secondsPerPeriod() external view returns (uint32); function register(address _node, uint16 _period) external; function migrate(address _node) external; function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external; } /** * @notice Adjudicator interface */ interface AdjudicatorInterface { function rewardCoefficient() external view returns (uint32); } /** * @notice WorkLock interface */ interface WorkLockInterface { function token() external view returns (NuCypherToken); } /** * @title StakingEscrowStub * @notice Stub is used to deploy main StakingEscrow after all other contract and make some variables immutable * @dev |v1.0.0| */ contract StakingEscrowStub is Upgradeable { using AdditionalMath for uint32; NuCypherToken public immutable token; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; uint16 public immutable minLockedPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; /** * @notice Predefines some variables for use when deploying other contracts * @param _token Token contract * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked */ constructor( NuCypherToken _token, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens ) { require(_token.totalSupply() > 0 && _hoursPerPeriod != 0 && _genesisHoursPerPeriod != 0 && _genesisHoursPerPeriod <= _hoursPerPeriod && _minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); // we have to use real values even though this is a stub require(address(delegateGet(_testTarget, this.token.selector)) == address(token)); // TODO uncomment after merging this PR #2579 // require(uint32(delegateGet(_testTarget, this.genesisSecondsPerPeriod.selector)) == genesisSecondsPerPeriod); require(uint32(delegateGet(_testTarget, this.secondsPerPeriod.selector)) == secondsPerPeriod); require(uint16(delegateGet(_testTarget, this.minLockedPeriods.selector)) == minLockedPeriods); require(delegateGet(_testTarget, this.minAllowableLockedTokens.selector) == minAllowableLockedTokens); require(delegateGet(_testTarget, this.maxAllowableLockedTokens.selector) == maxAllowableLockedTokens); } } /** * @title StakingEscrow * @notice Contract holds and locks stakers tokens. * Each staker that locks their tokens will receive some compensation * @dev |v5.7.1| */ contract StakingEscrow is Issuer, IERC900History { using AdditionalMath for uint256; using AdditionalMath for uint16; using Bits for uint256; using SafeMath for uint256; using Snapshot for uint128[]; using SafeERC20 for NuCypherToken; /** * @notice Signals that tokens were deposited * @param staker Staker address * @param value Amount deposited (in NuNits) * @param periods Number of periods tokens will be locked */ event Deposited(address indexed staker, uint256 value, uint16 periods); /** * @notice Signals that tokens were stake locked * @param staker Staker address * @param value Amount locked (in NuNits) * @param firstPeriod Starting lock period * @param periods Number of periods tokens will be locked */ event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods); /** * @notice Signals that a sub-stake was divided * @param staker Staker address * @param oldValue Old sub-stake value (in NuNits) * @param lastPeriod Final locked period of old sub-stake * @param newValue New sub-stake value (in NuNits) * @param periods Number of periods to extend sub-stake */ event Divided( address indexed staker, uint256 oldValue, uint16 lastPeriod, uint256 newValue, uint16 periods ); /** * @notice Signals that two sub-stakes were merged * @param staker Staker address * @param value1 Value of first sub-stake (in NuNits) * @param value2 Value of second sub-stake (in NuNits) * @param lastPeriod Final locked period of merged sub-stake */ event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod); /** * @notice Signals that a sub-stake was prolonged * @param staker Staker address * @param value Value of sub-stake * @param lastPeriod Final locked period of old sub-stake * @param periods Number of periods sub-stake was extended */ event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods); /** * @notice Signals that tokens were withdrawn to the staker * @param staker Staker address * @param value Amount withdraws (in NuNits) */ event Withdrawn(address indexed staker, uint256 value); /** * @notice Signals that the worker associated with the staker made a commitment to next period * @param staker Staker address * @param period Period committed to * @param value Amount of tokens staked for the committed period */ event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value); /** * @notice Signals that tokens were minted for previous periods * @param staker Staker address * @param period Previous period tokens minted for * @param value Amount minted (in NuNits) */ event Minted(address indexed staker, uint16 indexed period, uint256 value); /** * @notice Signals that the staker was slashed * @param staker Staker address * @param penalty Slashing penalty * @param investigator Investigator address * @param reward Value of reward provided to investigator (in NuNits) */ event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward); /** * @notice Signals that the restake parameter was activated/deactivated * @param staker Staker address * @param reStake Updated parameter value */ event ReStakeSet(address indexed staker, bool reStake); /** * @notice Signals that a worker was bonded to the staker * @param staker Staker address * @param worker Worker address * @param startPeriod Period bonding occurred */ event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod); /** * @notice Signals that the winddown parameter was activated/deactivated * @param staker Staker address * @param windDown Updated parameter value */ event WindDownSet(address indexed staker, bool windDown); /** * @notice Signals that the snapshot parameter was activated/deactivated * @param staker Staker address * @param snapshotsEnabled Updated parameter value */ event SnapshotSet(address indexed staker, bool snapshotsEnabled); /** * @notice Signals that the staker migrated their stake to the new period length * @param staker Staker address * @param period Period when migration happened */ event Migrated(address indexed staker, uint16 indexed period); /// internal event event WorkMeasurementSet(address indexed staker, bool measureWork); struct SubStakeInfo { uint16 firstPeriod; uint16 lastPeriod; uint16 unlockingDuration; uint128 lockedValue; } struct Downtime { uint16 startPeriod; uint16 endPeriod; } struct StakerInfo { uint256 value; /* * Stores periods that are committed but not yet rewarded. * In order to optimize storage, only two values are used instead of an array. * commitToNextPeriod() method invokes mint() method so there can only be two committed * periods that are not yet rewarded: the current and the next periods. */ uint16 currentCommittedPeriod; uint16 nextCommittedPeriod; uint16 lastCommittedPeriod; uint16 stub1; // former slot for lockReStakeUntilPeriod uint256 completedWork; uint16 workerStartPeriod; // period when worker was bonded address worker; uint256 flags; // uint256 to acquire whole slot and minimize operations on it uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; Downtime[] pastDowntime; SubStakeInfo[] subStakes; uint128[] history; } // used only for upgrading uint16 internal constant RESERVED_PERIOD = 0; uint16 internal constant MAX_CHECKED_VALUES = 5; // to prevent high gas consumption in loops for slashing uint16 public constant MAX_SUB_STAKES = 30; uint16 internal constant MAX_UINT16 = 65535; // indices for flags uint8 internal constant RE_STAKE_DISABLED_INDEX = 0; uint8 internal constant WIND_DOWN_INDEX = 1; uint8 internal constant MEASURE_WORK_INDEX = 2; uint8 internal constant SNAPSHOTS_DISABLED_INDEX = 3; uint8 internal constant MIGRATED_INDEX = 4; uint16 public immutable minLockedPeriods; uint16 public immutable minWorkerPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; PolicyManagerInterface public immutable policyManager; AdjudicatorInterface public immutable adjudicator; WorkLockInterface public immutable workLock; mapping (address => StakerInfo) public stakerInfo; address[] public stakers; mapping (address => address) public stakerFromWorker; mapping (uint16 => uint256) stub4; // former slot for lockedPerPeriod uint128[] public balanceHistory; address stub1; // former slot for PolicyManager address stub2; // former slot for Adjudicator address stub3; // former slot for WorkLock mapping (uint16 => uint256) _lockedPerPeriod; // only to make verifyState from previous version work, temporary // TODO remove after upgrade #2579 function lockedPerPeriod(uint16 _period) public view returns (uint256) { return _period != RESERVED_PERIOD ? _lockedPerPeriod[_period] : 111; } /** * @notice Constructor sets address of token contract and coefficients for minting * @param _token Token contract * @param _policyManager Policy Manager contract * @param _adjudicator Adjudicator contract * @param _workLock WorkLock contract. Zero address if there is no WorkLock * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked * @param _minWorkerPeriods Min amount of periods while a worker can't be changed */ constructor( NuCypherToken _token, PolicyManagerInterface _policyManager, AdjudicatorInterface _adjudicator, WorkLockInterface _workLock, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens, uint16 _minWorkerPeriods ) Issuer( _token, _genesisHoursPerPeriod, _hoursPerPeriod, _issuanceDecayCoefficient, _lockDurationCoefficient1, _lockDurationCoefficient2, _maximumRewardedPeriods, _firstPhaseTotalSupply, _firstPhaseMaxIssuance ) { // constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; minWorkerPeriods = _minWorkerPeriods; require((_policyManager.secondsPerPeriod() == _hoursPerPeriod * (1 hours) || _policyManager.secondsPerPeriod() == _genesisHoursPerPeriod * (1 hours)) && _adjudicator.rewardCoefficient() != 0 && (address(_workLock) == address(0) || _workLock.token() == _token)); policyManager = _policyManager; adjudicator = _adjudicator; workLock = _workLock; } /** * @dev Checks the existence of a staker in the contract */ modifier onlyStaker() { StakerInfo storage info = stakerInfo[msg.sender]; require((info.value > 0 || info.nextCommittedPeriod != 0) && info.flags.bitSet(MIGRATED_INDEX)); _; } //------------------------Main getters------------------------ /** * @notice Get all tokens belonging to the staker */ function getAllTokens(address _staker) external view returns (uint256) { return stakerInfo[_staker].value; } /** * @notice Get all flags for the staker */ function getFlags(address _staker) external view returns ( bool windDown, bool reStake, bool measureWork, bool snapshots, bool migrated ) { StakerInfo storage info = stakerInfo[_staker]; windDown = info.flags.bitSet(WIND_DOWN_INDEX); reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); measureWork = info.flags.bitSet(MEASURE_WORK_INDEX); snapshots = !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX); migrated = info.flags.bitSet(MIGRATED_INDEX); } /** * @notice Get the start period. Use in the calculation of the last period of the sub stake * @param _info Staker structure * @param _currentPeriod Current period */ function getStartPeriod(StakerInfo storage _info, uint16 _currentPeriod) internal view returns (uint16) { // if the next period (after current) is committed if (_info.flags.bitSet(WIND_DOWN_INDEX) && _info.nextCommittedPeriod > _currentPeriod) { return _currentPeriod + 1; } return _currentPeriod; } /** * @notice Get the last period of the sub stake * @param _subStake Sub stake structure * @param _startPeriod Pre-calculated start period */ function getLastPeriodOfSubStake(SubStakeInfo storage _subStake, uint16 _startPeriod) internal view returns (uint16) { if (_subStake.lastPeriod != 0) { return _subStake.lastPeriod; } uint32 lastPeriod = uint32(_startPeriod) + _subStake.unlockingDuration; if (lastPeriod > uint32(MAX_UINT16)) { return MAX_UINT16; } return uint16(lastPeriod); } /** * @notice Get the last period of the sub stake * @param _staker Staker * @param _index Stake index */ function getLastPeriodOfSubStake(address _staker, uint256 _index) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; SubStakeInfo storage subStake = info.subStakes[_index]; uint16 startPeriod = getStartPeriod(info, getCurrentPeriod()); return getLastPeriodOfSubStake(subStake, startPeriod); } /** * @notice Get the value of locked tokens for a staker in a specified period * @dev Information may be incorrect for rewarded or not committed surpassed period * @param _info Staker structure * @param _currentPeriod Current period * @param _period Next period */ function getLockedTokens(StakerInfo storage _info, uint16 _currentPeriod, uint16 _period) internal view returns (uint256 lockedValue) { lockedValue = 0; uint16 startPeriod = getStartPeriod(_info, _currentPeriod); for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.firstPeriod <= _period && getLastPeriodOfSubStake(subStake, startPeriod) >= _period) { lockedValue += subStake.lockedValue; } } } /** * @notice Get the value of locked tokens for a staker in a future period * @dev This function is used by PreallocationEscrow so its signature can't be updated. * @param _staker Staker * @param _offsetPeriods Amount of periods that will be added to the current period */ function getLockedTokens(address _staker, uint16 _offsetPeriods) external view returns (uint256 lockedValue) { StakerInfo storage info = stakerInfo[_staker]; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_offsetPeriods); return getLockedTokens(info, currentPeriod, nextPeriod); } /** * @notice Get the last committed staker's period * @param _staker Staker */ function getLastCommittedPeriod(address _staker) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; return info.nextCommittedPeriod != 0 ? info.nextCommittedPeriod : info.lastCommittedPeriod; } /** * @notice Get the value of locked tokens for active stakers in (getCurrentPeriod() + _offsetPeriods) period * as well as stakers and their locked tokens * @param _offsetPeriods Amount of periods for locked tokens calculation * @param _startIndex Start index for looking in stakers array * @param _maxStakers Max stakers for looking, if set 0 then all will be used * @return allLockedTokens Sum of locked tokens for active stakers * @return activeStakers Array of stakers and their locked tokens. Stakers addresses stored as uint256 * @dev Note that activeStakers[0] in an array of uint256, but you want addresses. Careful when used directly! */ function getActiveStakers(uint16 _offsetPeriods, uint256 _startIndex, uint256 _maxStakers) external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers) { require(_offsetPeriods > 0); uint256 endIndex = stakers.length; require(_startIndex < endIndex); if (_maxStakers != 0 && _startIndex + _maxStakers < endIndex) { endIndex = _startIndex + _maxStakers; } activeStakers = new uint256[2][](endIndex - _startIndex); allLockedTokens = 0; uint256 resultIndex = 0; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_offsetPeriods); for (uint256 i = _startIndex; i < endIndex; i++) { address staker = stakers[i]; StakerInfo storage info = stakerInfo[staker]; if (info.currentCommittedPeriod != currentPeriod && info.nextCommittedPeriod != currentPeriod) { continue; } uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); if (lockedTokens != 0) { activeStakers[resultIndex][0] = uint256(staker); activeStakers[resultIndex++][1] = lockedTokens; allLockedTokens += lockedTokens; } } assembly { mstore(activeStakers, resultIndex) } } /** * @notice Get worker using staker's address */ function getWorkerFromStaker(address _staker) external view returns (address) { return stakerInfo[_staker].worker; } /** * @notice Get work that completed by the staker */ function getCompletedWork(address _staker) external view returns (uint256) { return stakerInfo[_staker].completedWork; } /** * @notice Find index of downtime structure that includes specified period * @dev If specified period is outside all downtime periods, the length of the array will be returned * @param _staker Staker * @param _period Specified period number */ function findIndexOfPastDowntime(address _staker, uint16 _period) external view returns (uint256 index) { StakerInfo storage info = stakerInfo[_staker]; for (index = 0; index < info.pastDowntime.length; index++) { if (_period <= info.pastDowntime[index].endPeriod) { return index; } } } //------------------------Main methods------------------------ /** * @notice Start or stop measuring the work of a staker * @param _staker Staker * @param _measureWork Value for `measureWork` parameter * @return Work that was previously done */ function setWorkMeasurement(address _staker, bool _measureWork) external returns (uint256) { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (info.flags.bitSet(MEASURE_WORK_INDEX) == _measureWork) { return info.completedWork; } info.flags = info.flags.toggleBit(MEASURE_WORK_INDEX); emit WorkMeasurementSet(_staker, _measureWork); return info.completedWork; } /** * @notice Bond worker * @param _worker Worker address. Must be a real address, not a contract */ function bondWorker(address _worker) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Specified worker is already bonded with this staker require(_worker != info.worker); uint16 currentPeriod = getCurrentPeriod(); if (info.worker != address(0)) { // If this staker had a worker ... // Check that enough time has passed to change it require(currentPeriod >= info.workerStartPeriod.add16(minWorkerPeriods)); // Remove the old relation "worker->staker" stakerFromWorker[info.worker] = address(0); } if (_worker != address(0)) { // Specified worker is already in use require(stakerFromWorker[_worker] == address(0)); // Specified worker is a staker require(stakerInfo[_worker].subStakes.length == 0 || _worker == msg.sender); // Set new worker->staker relation stakerFromWorker[_worker] = msg.sender; } // Bond new worker (or unbond if _worker == address(0)) info.worker = _worker; info.workerStartPeriod = currentPeriod; emit WorkerBonded(msg.sender, _worker, currentPeriod); } /** * @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake * @param _reStake Value for parameter */ function setReStake(bool _reStake) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) { return; } info.flags = info.flags.toggleBit(RE_STAKE_DISABLED_INDEX); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Deposit tokens from WorkLock contract * @param _staker Staker address * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function depositFromWorkLock( address _staker, uint256 _value, uint16 _unlockingDuration ) external { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (!info.flags.bitSet(WIND_DOWN_INDEX) && info.subStakes.length == 0) { info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(_staker, true); } // WorkLock still uses the genesis period length (24h) _unlockingDuration = recalculatePeriod(_unlockingDuration); deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Set `windDown` parameter. * If true then stake's duration will be decreasing in each period with `commitToNextPeriod()` * @param _windDown Value for parameter */ function setWindDown(bool _windDown) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) { return; } info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); emit WindDownSet(msg.sender, _windDown); // duration adjustment if next period is committed uint16 nextPeriod = getCurrentPeriod() + 1; if (info.nextCommittedPeriod != nextPeriod) { return; } // adjust sub-stakes duration for the new value of winding down parameter for (uint256 index = 0; index < info.subStakes.length; index++) { SubStakeInfo storage subStake = info.subStakes[index]; // sub-stake does not have fixed last period when winding down is disabled if (!_windDown && subStake.lastPeriod == nextPeriod) { subStake.lastPeriod = 0; subStake.unlockingDuration = 1; continue; } // this sub-stake is no longer affected by winding down parameter if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) { continue; } subStake.unlockingDuration = _windDown ? subStake.unlockingDuration - 1 : subStake.unlockingDuration + 1; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = nextPeriod; } } } /** * @notice Activate/deactivate taking snapshots of balances * @param _enableSnapshots True to activate snapshots, False to deactivate */ function setSnapshots(bool _enableSnapshots) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX) == !_enableSnapshots) { return; } uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); if(_enableSnapshots){ info.history.addSnapshot(info.value); balanceHistory.addSnapshot(lastGlobalBalance + info.value); } else { info.history.addSnapshot(0); balanceHistory.addSnapshot(lastGlobalBalance - info.value); } info.flags = info.flags.toggleBit(SNAPSHOTS_DISABLED_INDEX); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Adds a new snapshot to both the staker and global balance histories, * assuming the staker's balance was already changed * @param _info Reference to affected staker's struct * @param _addition Variance in balance. It can be positive or negative. */ function addSnapshot(StakerInfo storage _info, int256 _addition) internal { if(!_info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)){ _info.history.addSnapshot(_info.value); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance.addSigned(_addition)); } } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Deposit all tokens that were approved to transfer * @param _from Staker * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of periods during which tokens will be unlocked when wind down is enabled */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); deposit(_from, _from, MAX_SUB_STAKES, _value, uint16(payload)); } /** * @notice Deposit tokens and create new sub-stake. Use this method to become a staker * @param _staker Staker * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function deposit(address _staker, uint256 _value, uint16 _unlockingDuration) external { deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Deposit tokens and increase lock amount of an existing sub-stake * @dev This is preferable way to stake tokens because will be fewer active sub-stakes in the result * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); deposit(msg.sender, msg.sender, _index, _value, 0); } /** * @notice Deposit tokens * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _payer Owner of tokens * @param _index Index of the sub stake * @param _value Amount of tokens to deposit * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal { require(_value != 0); StakerInfo storage info = stakerInfo[_staker]; // A staker can't be a worker for another staker require(stakerFromWorker[_staker] == address(0) || stakerFromWorker[_staker] == info.worker); // initial stake of the staker if (info.subStakes.length == 0 && info.lastCommittedPeriod == 0) { stakers.push(_staker); policyManager.register(_staker, getCurrentPeriod() - 1); info.flags = info.flags.toggleBit(MIGRATED_INDEX); } require(info.flags.bitSet(MIGRATED_INDEX)); token.safeTransferFrom(_payer, address(this), _value); info.value += _value; lock(_staker, _index, _value, _unlockingDuration); addSnapshot(info, int256(_value)); if (_index >= MAX_SUB_STAKES) { emit Deposited(_staker, _value, _unlockingDuration); } else { uint16 lastPeriod = getLastPeriodOfSubStake(_staker, _index); emit Deposited(_staker, _value, lastPeriod - getCurrentPeriod()); } } /** * @notice Lock some tokens as a new sub-stake * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lockAndCreate(uint256 _value, uint16 _unlockingDuration) external onlyStaker { lock(msg.sender, MAX_SUB_STAKES, _value, _unlockingDuration); } /** * @notice Increase lock amount of an existing sub-stake * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); lock(msg.sender, _index, _value, 0); } /** * @notice Lock some tokens as a stake * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lock(address _staker, uint256 _index, uint256 _value, uint16 _unlockingDuration) internal { if (_index < MAX_SUB_STAKES) { require(_value > 0); } else { require(_value >= minAllowableLockedTokens && _unlockingDuration >= minLockedPeriods); } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[_staker]; uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); uint256 requestedLockedTokens = _value.add(lockedTokens); require(requestedLockedTokens <= info.value && requestedLockedTokens <= maxAllowableLockedTokens); // next period is committed if (info.nextCommittedPeriod == nextPeriod) { _lockedPerPeriod[nextPeriod] += _value; emit CommitmentMade(_staker, nextPeriod, _value); } // if index was provided then increase existing sub-stake if (_index < MAX_SUB_STAKES) { lockAndIncrease(info, currentPeriod, nextPeriod, _staker, _index, _value); // otherwise create new } else { lockAndCreate(info, nextPeriod, _staker, _value, _unlockingDuration); } } /** * @notice Lock some tokens as a new sub-stake * @param _info Staker structure * @param _nextPeriod Next period * @param _staker Staker * @param _value Amount of tokens which will be locked * @param _unlockingDuration Amount of periods during which tokens will be unlocked when wind down is enabled */ function lockAndCreate( StakerInfo storage _info, uint16 _nextPeriod, address _staker, uint256 _value, uint16 _unlockingDuration ) internal { uint16 duration = _unlockingDuration; // if winding down is enabled and next period is committed // then sub-stakes duration were decreased if (_info.nextCommittedPeriod == _nextPeriod && _info.flags.bitSet(WIND_DOWN_INDEX)) { duration -= 1; } saveSubStake(_info, _nextPeriod, 0, duration, _value); emit Locked(_staker, _value, _nextPeriod, _unlockingDuration); } /** * @notice Increase lock amount of an existing sub-stake * @dev Probably will be created a new sub-stake but it will be active only one period * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _staker Staker * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, address _staker, uint256 _index, uint256 _value ) internal { SubStakeInfo storage subStake = _info.subStakes[_index]; (, uint16 lastPeriod) = checkLastPeriodOfSubStake(_info, subStake, _currentPeriod); // create temporary sub-stake for current or previous committed periods // to leave locked amount in this period unchanged if (_info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod <= _currentPeriod || _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod <= _currentPeriod) { saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue); } subStake.lockedValue += uint128(_value); // all new locks should start from the next period subStake.firstPeriod = _nextPeriod; emit Locked(_staker, _value, _nextPeriod, lastPeriod - _currentPeriod); } /** * @notice Checks that last period of sub-stake is greater than the current period * @param _info Staker structure * @param _subStake Sub-stake structure * @param _currentPeriod Current period * @return startPeriod Start period. Use in the calculation of the last period of the sub stake * @return lastPeriod Last period of the sub stake */ function checkLastPeriodOfSubStake( StakerInfo storage _info, SubStakeInfo storage _subStake, uint16 _currentPeriod ) internal view returns (uint16 startPeriod, uint16 lastPeriod) { startPeriod = getStartPeriod(_info, _currentPeriod); lastPeriod = getLastPeriodOfSubStake(_subStake, startPeriod); // The sub stake must be active at least in the next period require(lastPeriod > _currentPeriod); } /** * @notice Save sub stake. First tries to override inactive sub stake * @dev Inactive sub stake means that last period of sub stake has been surpassed and already rewarded * @param _info Staker structure * @param _firstPeriod First period of the sub stake * @param _lastPeriod Last period of the sub stake * @param _unlockingDuration Duration of the sub stake in periods * @param _lockedValue Amount of locked tokens */ function saveSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint16 _lastPeriod, uint16 _unlockingDuration, uint256 _lockedValue ) internal { for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod != 0 && (_info.currentCommittedPeriod == 0 || subStake.lastPeriod < _info.currentCommittedPeriod) && (_info.nextCommittedPeriod == 0 || subStake.lastPeriod < _info.nextCommittedPeriod)) { subStake.firstPeriod = _firstPeriod; subStake.lastPeriod = _lastPeriod; subStake.unlockingDuration = _unlockingDuration; subStake.lockedValue = uint128(_lockedValue); return; } } require(_info.subStakes.length < MAX_SUB_STAKES); _info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _unlockingDuration, uint128(_lockedValue))); } /** * @notice Divide sub stake into two parts * @param _index Index of the sub stake * @param _newValue New sub stake value * @param _additionalDuration Amount of periods for extending sub stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _additionalDuration) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; require(_newValue >= minAllowableLockedTokens && _additionalDuration > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); uint256 oldValue = subStake.lockedValue; subStake.lockedValue = uint128(oldValue.sub(_newValue)); require(subStake.lockedValue >= minAllowableLockedTokens); uint16 requestedPeriods = subStake.unlockingDuration.add16(_additionalDuration); saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue); emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _additionalDuration); emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _additionalDuration Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _additionalDuration) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Incorrect parameters require(_additionalDuration > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); subStake.unlockingDuration = subStake.unlockingDuration.add16(_additionalDuration); // if the sub stake ends in the next committed period then reset the `lastPeriod` field if (lastPeriod == startPeriod) { subStake.lastPeriod = 0; } // The extended sub stake must not be less than the minimum value require(uint32(lastPeriod - currentPeriod) + _additionalDuration >= minLockedPeriods); emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _additionalDuration); emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _additionalDuration); } /** * @notice Merge two sub-stakes into one if their last periods are equal * @dev It's possible that both sub-stakes will be active after this transaction. * But only one of them will be active until next call `commitToNextPeriod` (in the next period) * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) external onlyStaker { require(_index1 != _index2); // must be different sub-stakes StakerInfo storage info = stakerInfo[msg.sender]; SubStakeInfo storage subStake1 = info.subStakes[_index1]; SubStakeInfo storage subStake2 = info.subStakes[_index2]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod1) = checkLastPeriodOfSubStake(info, subStake1, currentPeriod); (, uint16 lastPeriod2) = checkLastPeriodOfSubStake(info, subStake2, currentPeriod); // both sub-stakes must have equal last period to be mergeable require(lastPeriod1 == lastPeriod2); emit Merged(msg.sender, subStake1.lockedValue, subStake2.lockedValue, lastPeriod1); if (subStake1.firstPeriod == subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = 1; subStake2.unlockingDuration = 0; } else if (subStake1.firstPeriod > subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = subStake1.firstPeriod - 1; subStake2.unlockingDuration = 0; } else { subStake2.lockedValue += subStake1.lockedValue; subStake1.lastPeriod = subStake2.firstPeriod - 1; subStake1.unlockingDuration = 0; } } /** * @notice Remove unused sub-stake to decrease gas cost for several methods */ function removeUnusedSubStake(uint16 _index) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; uint256 lastIndex = info.subStakes.length - 1; SubStakeInfo storage subStake = info.subStakes[_index]; require(subStake.lastPeriod != 0 && (info.currentCommittedPeriod == 0 || subStake.lastPeriod < info.currentCommittedPeriod) && (info.nextCommittedPeriod == 0 || subStake.lastPeriod < info.nextCommittedPeriod)); if (_index != lastIndex) { SubStakeInfo storage lastSubStake = info.subStakes[lastIndex]; subStake.firstPeriod = lastSubStake.firstPeriod; subStake.lastPeriod = lastSubStake.lastPeriod; subStake.unlockingDuration = lastSubStake.unlockingDuration; subStake.lockedValue = lastSubStake.lockedValue; } info.subStakes.pop(); } /** * @notice Withdraw available amount of tokens to staker * @param _value Amount of tokens to withdraw */ function withdraw(uint256 _value) external onlyStaker { uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[msg.sender]; // the max locked tokens in most cases will be in the current period // but when the staker locks more then we should use the next period uint256 lockedTokens = Math.max(getLockedTokens(info, currentPeriod, nextPeriod), getLockedTokens(info, currentPeriod, currentPeriod)); require(_value <= info.value.sub(lockedTokens)); info.value -= _value; addSnapshot(info, - int256(_value)); token.safeTransfer(msg.sender, _value); emit Withdrawn(msg.sender, _value); // unbond worker if staker withdraws last portion of NU if (info.value == 0 && info.nextCommittedPeriod == 0 && info.worker != address(0)) { stakerFromWorker[info.worker] = address(0); info.worker = address(0); emit WorkerBonded(msg.sender, address(0), currentPeriod); } } /** * @notice Make a commitment to the next period and mint for the previous period */ function commitToNextPeriod() external isInitialized { address staker = stakerFromWorker[msg.sender]; StakerInfo storage info = stakerInfo[staker]; // Staker must have a stake to make a commitment require(info.value > 0); // Only worker with real address can make a commitment require(msg.sender == tx.origin); migrate(staker); uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; // the period has already been committed require(info.nextCommittedPeriod != nextPeriod); uint16 lastCommittedPeriod = getLastCommittedPeriod(staker); (uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker); uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); require(lockedTokens > 0); _lockedPerPeriod[nextPeriod] += lockedTokens; info.currentCommittedPeriod = info.nextCommittedPeriod; info.nextCommittedPeriod = nextPeriod; decreaseSubStakesDuration(info, nextPeriod); // staker was inactive for several periods if (lastCommittedPeriod < currentPeriod) { info.pastDowntime.push(Downtime(lastCommittedPeriod + 1, currentPeriod)); } policyManager.ping(staker, processedPeriod1, processedPeriod2, nextPeriod); emit CommitmentMade(staker, nextPeriod, lockedTokens); } /** * @notice Migrate from the old period length to the new one. Can be done only once * @param _staker Staker */ function migrate(address _staker) public { StakerInfo storage info = stakerInfo[_staker]; // check that provided address is/was a staker require(info.subStakes.length != 0 || info.lastCommittedPeriod != 0); if (info.flags.bitSet(MIGRATED_INDEX)) { return; } // reset state info.currentCommittedPeriod = 0; info.nextCommittedPeriod = 0; // maintain case when no more sub-stakes and need to avoid re-registering this staker during deposit info.lastCommittedPeriod = 1; info.workerStartPeriod = recalculatePeriod(info.workerStartPeriod); delete info.pastDowntime; // recalculate all sub-stakes uint16 currentPeriod = getCurrentPeriod(); for (uint256 i = 0; i < info.subStakes.length; i++) { SubStakeInfo storage subStake = info.subStakes[i]; subStake.firstPeriod = recalculatePeriod(subStake.firstPeriod); // sub-stake has fixed last period if (subStake.lastPeriod != 0) { subStake.lastPeriod = recalculatePeriod(subStake.lastPeriod); if (subStake.lastPeriod == 0) { subStake.lastPeriod = 1; } subStake.unlockingDuration = 0; // sub-stake has no fixed ending but possible that with new period length will have } else { uint16 oldCurrentPeriod = uint16(block.timestamp / genesisSecondsPerPeriod); uint16 lastPeriod = recalculatePeriod(oldCurrentPeriod + subStake.unlockingDuration); subStake.unlockingDuration = lastPeriod - currentPeriod; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = lastPeriod; } } } policyManager.migrate(_staker); info.flags = info.flags.toggleBit(MIGRATED_INDEX); emit Migrated(_staker, currentPeriod); } /** * @notice Decrease sub-stakes duration if `windDown` is enabled */ function decreaseSubStakesDuration(StakerInfo storage _info, uint16 _nextPeriod) internal { if (!_info.flags.bitSet(WIND_DOWN_INDEX)) { return; } for (uint256 index = 0; index < _info.subStakes.length; index++) { SubStakeInfo storage subStake = _info.subStakes[index]; if (subStake.lastPeriod != 0 || subStake.unlockingDuration == 0) { continue; } subStake.unlockingDuration--; if (subStake.unlockingDuration == 0) { subStake.lastPeriod = _nextPeriod; } } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment */ function mint() external onlyStaker { // save last committed period to the storage if both periods will be empty after minting // because we won't be able to calculate last committed period // see getLastCommittedPeriod(address) StakerInfo storage info = stakerInfo[msg.sender]; uint16 previousPeriod = getCurrentPeriod() - 1; if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) { info.lastCommittedPeriod = info.nextCommittedPeriod; } (uint16 processedPeriod1, uint16 processedPeriod2) = mint(msg.sender); if (processedPeriod1 != 0 || processedPeriod2 != 0) { policyManager.ping(msg.sender, processedPeriod1, processedPeriod2, 0); } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment * @param _staker Staker * @return processedPeriod1 Processed period: currentCommittedPeriod or zero * @return processedPeriod2 Processed period: nextCommittedPeriod or zero */ function mint(address _staker) internal returns (uint16 processedPeriod1, uint16 processedPeriod2) { uint16 currentPeriod = getCurrentPeriod(); uint16 previousPeriod = currentPeriod - 1; StakerInfo storage info = stakerInfo[_staker]; if (info.nextCommittedPeriod == 0 || info.currentCommittedPeriod == 0 && info.nextCommittedPeriod > previousPeriod || info.currentCommittedPeriod > previousPeriod) { return (0, 0); } uint16 startPeriod = getStartPeriod(info, currentPeriod); uint256 reward = 0; bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); if (info.currentCommittedPeriod != 0) { reward = mint(info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod1 = info.currentCommittedPeriod; info.currentCommittedPeriod = 0; if (reStake) { _lockedPerPeriod[info.nextCommittedPeriod] += reward; } } if (info.nextCommittedPeriod <= previousPeriod) { reward += mint(info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake); processedPeriod2 = info.nextCommittedPeriod; info.nextCommittedPeriod = 0; } info.value += reward; if (info.flags.bitSet(MEASURE_WORK_INDEX)) { info.completedWork += reward; } addSnapshot(info, int256(reward)); emit Minted(_staker, previousPeriod, reward); } /** * @notice Calculate reward for one period * @param _info Staker structure * @param _mintingPeriod Period for minting calculation * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period */ function mint( StakerInfo storage _info, uint16 _mintingPeriod, uint16 _currentPeriod, uint16 _startPeriod, bool _reStake ) internal returns (uint256 reward) { reward = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (subStake.firstPeriod <= _mintingPeriod && lastPeriod >= _mintingPeriod) { uint256 subStakeReward = mint( _currentPeriod, subStake.lockedValue, _lockedPerPeriod[_mintingPeriod], lastPeriod.sub16(_mintingPeriod)); reward += subStakeReward; if (_reStake) { subStake.lockedValue += uint128(subStakeReward); } } } return reward; } //-------------------------Slashing------------------------- /** * @notice Slash the staker's stake and reward the investigator * @param _staker Staker's address * @param _penalty Penalty * @param _investigator Investigator * @param _reward Reward for the investigator */ function slashStaker( address _staker, uint256 _penalty, address _investigator, uint256 _reward ) public isInitialized { require(msg.sender == address(adjudicator)); require(_penalty > 0); StakerInfo storage info = stakerInfo[_staker]; require(info.flags.bitSet(MIGRATED_INDEX)); if (info.value <= _penalty) { _penalty = info.value; } info.value -= _penalty; if (_reward > _penalty) { _reward = _penalty; } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; uint16 startPeriod = getStartPeriod(info, currentPeriod); (uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex) = getLockedTokensAndShortestSubStake(info, currentPeriod, nextPeriod, startPeriod); // Decrease the stake if amount of locked tokens in the current period more than staker has uint256 lockedTokens = currentLock + currentAndNextLock; if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, currentPeriod, startPeriod, shortestSubStakeIndex); } // Decrease the stake if amount of locked tokens in the next period more than staker has if (nextLock > 0) { lockedTokens = nextLock + currentAndNextLock - (currentAndNextLock > info.value ? currentAndNextLock - info.value : 0); if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, nextPeriod, startPeriod, MAX_SUB_STAKES); } } emit Slashed(_staker, _penalty, _investigator, _reward); if (_penalty > _reward) { unMint(_penalty - _reward); } // TODO change to withdrawal pattern (#1499) if (_reward > 0) { token.safeTransfer(_investigator, _reward); } addSnapshot(info, - int256(_penalty)); } /** * @notice Get the value of locked tokens for a staker in the current and the next period * and find the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _startPeriod Pre-calculated start period * @return currentLock Amount of tokens that locked in the current period and unlocked in the next period * @return nextLock Amount of tokens that locked in the next period and not locked in the current period * @return currentAndNextLock Amount of tokens that locked in the current period and in the next period * @return shortestSubStakeIndex Index of the shortest sub stake */ function getLockedTokensAndShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, uint16 _startPeriod ) internal view returns ( uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex ) { uint16 minDuration = MAX_UINT16; uint16 minLastPeriod = MAX_UINT16; shortestSubStakeIndex = MAX_SUB_STAKES; currentLock = 0; nextLock = 0; currentAndNextLock = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _nextPeriod) { currentAndNextLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod) { currentLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _nextPeriod && lastPeriod >= _nextPeriod) { nextLock += subStake.lockedValue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minLastPeriod || lastPeriod == minLastPeriod && duration < minDuration)) { shortestSubStakeIndex = i; minDuration = duration; minLastPeriod = lastPeriod; } } } /** * @notice Decrease short sub stakes * @param _info Staker structure * @param _penalty Penalty rate * @param _decreasePeriod The period when the decrease begins * @param _startPeriod Pre-calculated start period * @param _shortestSubStakeIndex Index of the shortest period */ function decreaseSubStakes( StakerInfo storage _info, uint256 _penalty, uint16 _decreasePeriod, uint16 _startPeriod, uint256 _shortestSubStakeIndex ) internal { SubStakeInfo storage shortestSubStake = _info.subStakes[0]; uint16 minSubStakeLastPeriod = MAX_UINT16; uint16 minSubStakeDuration = MAX_UINT16; while(_penalty > 0) { if (_shortestSubStakeIndex < MAX_SUB_STAKES) { shortestSubStake = _info.subStakes[_shortestSubStakeIndex]; minSubStakeLastPeriod = getLastPeriodOfSubStake(shortestSubStake, _startPeriod); minSubStakeDuration = minSubStakeLastPeriod - shortestSubStake.firstPeriod; _shortestSubStakeIndex = MAX_SUB_STAKES; } else { (shortestSubStake, minSubStakeDuration, minSubStakeLastPeriod) = getShortestSubStake(_info, _decreasePeriod, _startPeriod); } if (minSubStakeDuration == MAX_UINT16) { break; } uint256 appliedPenalty = _penalty; if (_penalty < shortestSubStake.lockedValue) { shortestSubStake.lockedValue -= uint128(_penalty); saveOldSubStake(_info, shortestSubStake.firstPeriod, _penalty, _decreasePeriod); _penalty = 0; } else { shortestSubStake.lastPeriod = _decreasePeriod - 1; _penalty -= shortestSubStake.lockedValue; appliedPenalty = shortestSubStake.lockedValue; } if (_info.currentCommittedPeriod >= _decreasePeriod && _info.currentCommittedPeriod <= minSubStakeLastPeriod) { _lockedPerPeriod[_info.currentCommittedPeriod] -= appliedPenalty; } if (_info.nextCommittedPeriod >= _decreasePeriod && _info.nextCommittedPeriod <= minSubStakeLastPeriod) { _lockedPerPeriod[_info.nextCommittedPeriod] -= appliedPenalty; } } } /** * @notice Get the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period * @return shortestSubStake The shortest sub stake * @return minSubStakeDuration Duration of the shortest sub stake * @return minSubStakeLastPeriod Last period of the shortest sub stake */ function getShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _startPeriod ) internal view returns ( SubStakeInfo storage shortestSubStake, uint16 minSubStakeDuration, uint16 minSubStakeLastPeriod ) { shortestSubStake = shortestSubStake; minSubStakeDuration = MAX_UINT16; minSubStakeLastPeriod = MAX_UINT16; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minSubStakeLastPeriod || lastPeriod == minSubStakeLastPeriod && duration < minSubStakeDuration)) { shortestSubStake = subStake; minSubStakeDuration = duration; minSubStakeLastPeriod = lastPeriod; } } } /** * @notice Save the old sub stake values to prevent decreasing reward for the previous period * @dev Saving happens only if the previous period is committed * @param _info Staker structure * @param _firstPeriod First period of the old sub stake * @param _lockedValue Locked value of the old sub stake * @param _currentPeriod Current period, when the old sub stake is already unlocked */ function saveOldSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint256 _lockedValue, uint16 _currentPeriod ) internal { // Check that the old sub stake should be saved bool oldCurrentCommittedPeriod = _info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod < _currentPeriod; bool oldnextCommittedPeriod = _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod < _currentPeriod; bool crosscurrentCommittedPeriod = oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= _firstPeriod; bool crossnextCommittedPeriod = oldnextCommittedPeriod && _info.nextCommittedPeriod >= _firstPeriod; if (!crosscurrentCommittedPeriod && !crossnextCommittedPeriod) { return; } // Try to find already existent proper old sub stake uint16 previousPeriod = _currentPeriod - 1; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod == previousPeriod && ((crosscurrentCommittedPeriod == (oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= subStake.firstPeriod)) && (crossnextCommittedPeriod == (oldnextCommittedPeriod && _info.nextCommittedPeriod >= subStake.firstPeriod)))) { subStake.lockedValue += uint128(_lockedValue); return; } } saveSubStake(_info, _firstPeriod, previousPeriod, 0, _lockedValue); } //-------------Additional getters for stakers info------------- /** * @notice Return the length of the array of stakers */ function getStakersLength() external view returns (uint256) { return stakers.length; } /** * @notice Return the length of the array of sub stakes */ function getSubStakesLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].subStakes.length; } /** * @notice Return the information about sub stake */ function getSubStakeInfo(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (SubStakeInfo) // TODO "virtual" only for tests, probably will be removed after #1512 external view virtual returns ( uint16 firstPeriod, uint16 lastPeriod, uint16 unlockingDuration, uint128 lockedValue ) { SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index]; firstPeriod = info.firstPeriod; lastPeriod = info.lastPeriod; unlockingDuration = info.unlockingDuration; lockedValue = info.lockedValue; } /** * @notice Return the length of the array of past downtime */ function getPastDowntimeLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].pastDowntime.length; } /** * @notice Return the information about past downtime */ function getPastDowntime(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (Downtime) external view returns (uint16 startPeriod, uint16 endPeriod) { Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index]; startPeriod = downtime.startPeriod; endPeriod = downtime.endPeriod; } //------------------ ERC900 connectors ---------------------- function totalStakedForAt(address _owner, uint256 _blockNumber) public view override returns (uint256){ return stakerInfo[_owner].history.getValueAt(_blockNumber); } function totalStakedAt(uint256 _blockNumber) public view override returns (uint256){ return balanceHistory.getValueAt(_blockNumber); } function supportsHistory() external pure override returns (bool){ return true; } //------------------------Upgradeable------------------------ /** * @dev Get StakerInfo structure by delegatecall */ function delegateGetStakerInfo(address _target, bytes32 _staker) internal returns (StakerInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.stakerInfo.selector, 1, _staker, 0); assembly { result := memoryAddress } } /** * @dev Get SubStakeInfo structure by delegatecall */ function delegateGetSubStakeInfo(address _target, bytes32 _staker, uint256 _index) internal returns (SubStakeInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getSubStakeInfo.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get Downtime structure by delegatecall */ function delegateGetPastDowntime(address _target, bytes32 _staker, uint256 _index) internal returns (Downtime memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getPastDowntime.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(delegateGet(_testTarget, this.lockedPerPeriod.selector, bytes32(bytes2(RESERVED_PERIOD))) == lockedPerPeriod(RESERVED_PERIOD)); require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(0))) == stakerFromWorker[address(0)]); require(delegateGet(_testTarget, this.getStakersLength.selector) == stakers.length); if (stakers.length == 0) { return; } address stakerAddress = stakers[0]; require(address(uint160(delegateGet(_testTarget, this.stakers.selector, 0))) == stakerAddress); StakerInfo storage info = stakerInfo[stakerAddress]; bytes32 staker = bytes32(uint256(stakerAddress)); StakerInfo memory infoToCheck = delegateGetStakerInfo(_testTarget, staker); require(infoToCheck.value == info.value && infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod && infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod && infoToCheck.flags == info.flags && infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod && infoToCheck.completedWork == info.completedWork && infoToCheck.worker == info.worker && infoToCheck.workerStartPeriod == info.workerStartPeriod); require(delegateGet(_testTarget, this.getPastDowntimeLength.selector, staker) == info.pastDowntime.length); for (uint256 i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) { Downtime storage downtime = info.pastDowntime[i]; Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, staker, i); require(downtimeToCheck.startPeriod == downtime.startPeriod && downtimeToCheck.endPeriod == downtime.endPeriod); } require(delegateGet(_testTarget, this.getSubStakesLength.selector, staker) == info.subStakes.length); for (uint256 i = 0; i < info.subStakes.length && i < MAX_CHECKED_VALUES; i++) { SubStakeInfo storage subStakeInfo = info.subStakes[i]; SubStakeInfo memory subStakeInfoToCheck = delegateGetSubStakeInfo(_testTarget, staker, i); require(subStakeInfoToCheck.firstPeriod == subStakeInfo.firstPeriod && subStakeInfoToCheck.lastPeriod == subStakeInfo.lastPeriod && subStakeInfoToCheck.unlockingDuration == subStakeInfo.unlockingDuration && subStakeInfoToCheck.lockedValue == subStakeInfo.lockedValue); } // it's not perfect because checks not only slot value but also decoding // at least without additional functions require(delegateGet(_testTarget, this.totalStakedForAt.selector, staker, bytes32(block.number)) == totalStakedForAt(stakerAddress, block.number)); require(delegateGet(_testTarget, this.totalStakedAt.selector, bytes32(block.number)) == totalStakedAt(block.number)); if (info.worker != address(0)) { require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(uint256(info.worker)))) == stakerFromWorker[info.worker]); } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // Create fake period _lockedPerPeriod[RESERVED_PERIOD] = 111; // Create fake worker stakerFromWorker[address(0)] = address(this); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; // Minimum interface to interact with Aragon's Aggregator interface IERC900History { function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256); function totalStakedAt(uint256 blockNumber) external view returns (uint256); function supportsHistory() external pure returns (bool); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./NuCypherToken.sol"; import "../zeppelin/math/Math.sol"; import "./proxy/Upgradeable.sol"; import "./lib/AdditionalMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; /** * @title Issuer * @notice Contract for calculation of issued tokens * @dev |v3.4.1| */ abstract contract Issuer is Upgradeable { using SafeERC20 for NuCypherToken; using AdditionalMath for uint32; event Donated(address indexed sender, uint256 value); /// Issuer is initialized with a reserved reward event Initialized(uint256 reservedReward); uint128 constant MAX_UINT128 = uint128(0) - 1; NuCypherToken public immutable token; uint128 public immutable totalSupply; // d * k2 uint256 public immutable mintingCoefficient; // k1 uint256 public immutable lockDurationCoefficient1; // k2 uint256 public immutable lockDurationCoefficient2; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; // kmax uint16 public immutable maximumRewardedPeriods; uint256 public immutable firstPhaseMaxIssuance; uint256 public immutable firstPhaseTotalSupply; /** * Current supply is used in the minting formula and is stored to prevent different calculation * for stakers which get reward in the same period. There are two values - * supply for previous period (used in formula) and supply for current period which accumulates value * before end of period. */ uint128 public previousPeriodSupply; uint128 public currentPeriodSupply; uint16 public currentMintingPeriod; /** * @notice Constructor sets address of token contract and coefficients for minting * @dev Minting formula for one sub-stake in one period for the first phase firstPhaseMaxIssuance * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 * @dev Minting formula for one sub-stake in one period for the second phase (totalSupply - currentSupply) / d * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 if allLockedPeriods > maximumRewardedPeriods then allLockedPeriods = maximumRewardedPeriods * @param _token Token contract * @param _genesisHoursPerPeriod Size of period in hours at genesis * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. */ constructor( NuCypherToken _token, uint32 _genesisHoursPerPeriod, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance ) { uint256 localTotalSupply = _token.totalSupply(); require(localTotalSupply > 0 && _issuanceDecayCoefficient != 0 && _hoursPerPeriod != 0 && _genesisHoursPerPeriod != 0 && _genesisHoursPerPeriod <= _hoursPerPeriod && _lockDurationCoefficient1 != 0 && _lockDurationCoefficient2 != 0 && _maximumRewardedPeriods != 0); require(localTotalSupply <= uint256(MAX_UINT128), "Token contract has supply more than supported"); uint256 maxLockDurationCoefficient = _maximumRewardedPeriods + _lockDurationCoefficient1; uint256 localMintingCoefficient = _issuanceDecayCoefficient * _lockDurationCoefficient2; require(maxLockDurationCoefficient > _maximumRewardedPeriods && localMintingCoefficient / _issuanceDecayCoefficient == _lockDurationCoefficient2 && // worst case for `totalLockedValue * d * k2`, when totalLockedValue == totalSupply localTotalSupply * localMintingCoefficient / localTotalSupply == localMintingCoefficient && // worst case for `(totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax))`, // when currentSupply == 0, lockedValue == totalSupply localTotalSupply * localTotalSupply * maxLockDurationCoefficient / localTotalSupply / localTotalSupply == maxLockDurationCoefficient, "Specified parameters cause overflow"); require(maxLockDurationCoefficient <= _lockDurationCoefficient2, "Resulting locking duration coefficient must be less than 1"); require(_firstPhaseTotalSupply <= localTotalSupply, "Too many tokens for the first phase"); require(_firstPhaseMaxIssuance <= _firstPhaseTotalSupply, "Reward for the first phase is too high"); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); genesisSecondsPerPeriod = _genesisHoursPerPeriod.mul32(1 hours); lockDurationCoefficient1 = _lockDurationCoefficient1; lockDurationCoefficient2 = _lockDurationCoefficient2; maximumRewardedPeriods = _maximumRewardedPeriods; firstPhaseTotalSupply = _firstPhaseTotalSupply; firstPhaseMaxIssuance = _firstPhaseMaxIssuance; totalSupply = uint128(localTotalSupply); mintingCoefficient = localMintingCoefficient; } /** * @dev Checks contract initialization */ modifier isInitialized() { require(currentMintingPeriod != 0); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @return Recalculate period value using new basis */ function recalculatePeriod(uint16 _period) internal view returns (uint16) { return uint16(uint256(_period) * genesisSecondsPerPeriod / secondsPerPeriod); } /** * @notice Initialize reserved tokens for reward */ function initialize(uint256 _reservedReward, address _sourceOfFunds) external onlyOwner { require(currentMintingPeriod == 0); // Reserved reward must be sufficient for at least one period of the first phase require(firstPhaseMaxIssuance <= _reservedReward); currentMintingPeriod = getCurrentPeriod(); currentPeriodSupply = totalSupply - uint128(_reservedReward); previousPeriodSupply = currentPeriodSupply; token.safeTransferFrom(_sourceOfFunds, address(this), _reservedReward); emit Initialized(_reservedReward); } /** * @notice Function to mint tokens for one period. * @param _currentPeriod Current period number. * @param _lockedValue The amount of tokens that were locked by user in specified period. * @param _totalLockedValue The amount of tokens that were locked by all users in specified period. * @param _allLockedPeriods The max amount of periods during which tokens will be locked after specified period. * @return amount Amount of minted tokens. */ function mint( uint16 _currentPeriod, uint256 _lockedValue, uint256 _totalLockedValue, uint16 _allLockedPeriods ) internal returns (uint256 amount) { if (currentPeriodSupply == totalSupply) { return 0; } if (_currentPeriod > currentMintingPeriod) { previousPeriodSupply = currentPeriodSupply; currentMintingPeriod = _currentPeriod; } uint256 currentReward; uint256 coefficient; // first phase // firstPhaseMaxIssuance * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * k2) if (previousPeriodSupply + firstPhaseMaxIssuance <= firstPhaseTotalSupply) { currentReward = firstPhaseMaxIssuance; coefficient = lockDurationCoefficient2; // second phase // (totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * d * k2) } else { currentReward = totalSupply - previousPeriodSupply; coefficient = mintingCoefficient; } uint256 allLockedPeriods = AdditionalMath.min16(_allLockedPeriods, maximumRewardedPeriods) + lockDurationCoefficient1; amount = (uint256(currentReward) * _lockedValue * allLockedPeriods) / (_totalLockedValue * coefficient); // rounding the last reward uint256 maxReward = getReservedReward(); if (amount == 0) { amount = 1; } else if (amount > maxReward) { amount = maxReward; } currentPeriodSupply += uint128(amount); } /** * @notice Return tokens for future minting * @param _amount Amount of tokens */ function unMint(uint256 _amount) internal { previousPeriodSupply -= uint128(_amount); currentPeriodSupply -= uint128(_amount); } /** * @notice Donate sender's tokens. Amount of tokens will be returned for future minting * @param _value Amount to donate */ function donate(uint256 _value) external isInitialized { token.safeTransferFrom(msg.sender, address(this), _value); unMint(_value); emit Donated(msg.sender, _value); } /** * @notice Returns the number of tokens that can be minted */ function getReservedReward() public view returns (uint256) { return totalSupply - currentPeriodSupply; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint16(delegateGet(_testTarget, this.currentMintingPeriod.selector)) == currentMintingPeriod); require(uint128(delegateGet(_testTarget, this.previousPeriodSupply.selector)) == previousPeriodSupply); require(uint128(delegateGet(_testTarget, this.currentPeriodSupply.selector)) == currentPeriodSupply); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // recalculate currentMintingPeriod if needed if (currentMintingPeriod > getCurrentPeriod()) { currentMintingPeriod = recalculatePeriod(currentMintingPeriod); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/token/ERC20/ERC20.sol"; import "../zeppelin/token/ERC20/ERC20Detailed.sol"; /** * @title NuCypherToken * @notice ERC20 token * @dev Optional approveAndCall() functionality to notify a contract if an approve() has occurred. */ contract NuCypherToken is ERC20, ERC20Detailed('NuCypher', 'NU', 18) { /** * @notice Set amount of tokens * @param _totalSupplyOfTokens Total number of tokens */ constructor (uint256 _totalSupplyOfTokens) { _mint(msg.sender, _totalSupplyOfTokens); } /** * @notice Approves and then calls the receiving contract * * @dev call the receiveApproval function on the contract you want to be notified. * receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) */ function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success) { approve(_spender, _value); TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } /** * @dev Interface to use the receiveApproval method */ interface TokenRecipient { /** * @notice Receives a notification of approval of the transfer * @param _from Sender of approval * @param _value The amount of tokens to be spent * @param _tokenContract Address of the token contract * @param _extraData Extra data */ function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view override returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(value == 0 || _allowed[msg.sender][spender] == 0); _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public override returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title Math * @dev Assorted math operations */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; /** * @notice Base contract for upgradeable contract * @dev Inherited contract should implement verifyState(address) method by checking storage variables * (see verifyState(address) in Dispatcher). Also contract should implement finishUpgrade(address) * if it is using constructor parameters by coping this parameters to the dispatcher storage */ abstract contract Upgradeable is Ownable { event StateVerified(address indexed testTarget, address sender); event UpgradeFinished(address indexed target, address sender); /** * @dev Contracts at the target must reserve the same location in storage for this address as in Dispatcher * Stored data actually lives in the Dispatcher * However the storage layout is specified here in the implementing contracts */ address public target; /** * @dev Previous contract address (if available). Used for rollback */ address public previousTarget; /** * @dev Upgrade status. Explicit `uint8` type is used instead of `bool` to save gas by excluding 0 value */ uint8 public isUpgrade; /** * @dev Guarantees that next slot will be separated from the previous */ uint256 stubSlot; /** * @dev Constants for `isUpgrade` field */ uint8 constant UPGRADE_FALSE = 1; uint8 constant UPGRADE_TRUE = 2; /** * @dev Checks that function executed while upgrading * Recommended to add to `verifyState` and `finishUpgrade` methods */ modifier onlyWhileUpgrading() { require(isUpgrade == UPGRADE_TRUE); _; } /** * @dev Method for verifying storage state. * Should check that new target contract returns right storage value */ function verifyState(address _testTarget) public virtual onlyWhileUpgrading { emit StateVerified(_testTarget, msg.sender); } /** * @dev Copy values from the new target to the current storage * @param _target New target contract address */ function finishUpgrade(address _target) public virtual onlyWhileUpgrading { emit UpgradeFinished(_target, msg.sender); } /** * @dev Base method to get data * @param _target Target to call * @param _selector Method selector * @param _numberOfArguments Number of used arguments * @param _argument1 First method argument * @param _argument2 Second method argument * @return memoryAddress Address in memory where the data is located */ function delegateGetData( address _target, bytes4 _selector, uint8 _numberOfArguments, bytes32 _argument1, bytes32 _argument2 ) internal returns (bytes32 memoryAddress) { assembly { memoryAddress := mload(0x40) mstore(memoryAddress, _selector) if gt(_numberOfArguments, 0) { mstore(add(memoryAddress, 0x04), _argument1) } if gt(_numberOfArguments, 1) { mstore(add(memoryAddress, 0x24), _argument2) } switch delegatecall(gas(), _target, memoryAddress, add(0x04, mul(0x20, _numberOfArguments)), 0, 0) case 0 { revert(memoryAddress, 0) } default { returndatacopy(memoryAddress, 0x0, returndatasize()) } } } /** * @dev Call "getter" without parameters. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 0, 0, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with one parameter. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector, bytes32 _argument) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 1, _argument, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with two parameters. * Result should not exceed 32 bytes */ function delegateGet( address _target, bytes4 _selector, bytes32 _argument1, bytes32 _argument2 ) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2); assembly { result := mload(memoryAddress) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public virtual onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/math/SafeMath.sol"; /** * @notice Additional math operations */ library AdditionalMath { using SafeMath for uint256; function max16(uint16 a, uint16 b) internal pure returns (uint16) { return a >= b ? a : b; } function min16(uint16 a, uint16 b) internal pure returns (uint16) { return a < b ? a : b; } /** * @notice Division and ceil */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return (a.add(b) - 1) / b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.add(uint256(b)); } else { return a.sub(uint256(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.sub(uint256(b)); } else { return a.add(uint256(-b)); } } /** * @dev Multiplies two numbers, throws on overflow. */ function mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; assert(c / a == b); return c; } /** * @dev Adds two numbers, throws on overflow. */ function add16(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub16(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return add16(a, uint16(b)); } else { return sub16(a, uint16(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return sub16(a, uint16(b)); } else { return add16(a, uint16(-b)); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @dev Taken from https://github.com/ethereum/solidity-examples/blob/master/src/bits/Bits.sol */ library Bits { uint256 internal constant ONE = uint256(1); /** * @notice Sets the bit at the given 'index' in 'self' to: * '1' - if the bit is '0' * '0' - if the bit is '1' * @return The modified value */ function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) { return self ^ ONE << index; } /** * @notice Get the value of the bit at the given 'index' in 'self'. */ function bit(uint256 self, uint8 index) internal pure returns (uint8) { return uint8(self >> index & 1); } /** * @notice Check if the bit at the given 'index' in 'self' is set. * @return 'true' - if the value of the bit is '1', * 'false' - if the value of the bit is '0' */ function bitSet(uint256 self, uint8 index) internal pure returns (bool) { return self >> index & 1 == 1; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; /** * @title Snapshot * @notice Manages snapshots of size 128 bits (32 bits for timestamp, 96 bits for value) * 96 bits is enough for storing NU token values, and 32 bits should be OK for block numbers * @dev Since each storage slot can hold two snapshots, new slots are allocated every other TX. Thus, gas cost of adding snapshots is 51400 and 36400 gas, alternately. * Based on Aragon's Checkpointing (https://https://github.com/aragonone/voting-connectors/blob/master/shared/contract-utils/contracts/Checkpointing.sol) * On average, adding snapshots spends ~6500 less gas than the 256-bit checkpoints of Aragon's Checkpointing */ library Snapshot { function encodeSnapshot(uint32 _time, uint96 _value) internal pure returns(uint128) { return uint128(uint256(_time) << 96 | uint256(_value)); } function decodeSnapshot(uint128 _snapshot) internal pure returns(uint32 time, uint96 value){ time = uint32(bytes4(bytes16(_snapshot))); value = uint96(_snapshot); } function addSnapshot(uint128[] storage _self, uint256 _value) internal { addSnapshot(_self, block.number, _value); } function addSnapshot(uint128[] storage _self, uint256 _time, uint256 _value) internal { uint256 length = _self.length; if (length != 0) { (uint32 currentTime, ) = decodeSnapshot(_self[length - 1]); if (uint32(_time) == currentTime) { _self[length - 1] = encodeSnapshot(uint32(_time), uint96(_value)); return; } else if (uint32(_time) < currentTime){ revert(); } } _self.push(encodeSnapshot(uint32(_time), uint96(_value))); } function lastSnapshot(uint128[] storage _self) internal view returns (uint32, uint96) { uint256 length = _self.length; if (length > 0) { return decodeSnapshot(_self[length - 1]); } return (0, 0); } function lastValue(uint128[] storage _self) internal view returns (uint96) { (, uint96 value) = lastSnapshot(_self); return value; } function getValueAt(uint128[] storage _self, uint256 _time256) internal view returns (uint96) { uint32 _time = uint32(_time256); uint256 length = _self.length; // Short circuit if there's no checkpoints yet // Note that this also lets us avoid using SafeMath later on, as we've established that // there must be at least one checkpoint if (length == 0) { return 0; } // Check last checkpoint uint256 lastIndex = length - 1; (uint32 snapshotTime, uint96 snapshotValue) = decodeSnapshot(_self[length - 1]); if (_time >= snapshotTime) { return snapshotValue; } // Check first checkpoint (if not already checked with the above check on last) (snapshotTime, snapshotValue) = decodeSnapshot(_self[0]); if (length == 1 || _time < snapshotTime) { return 0; } // Do binary search // As we've already checked both ends, we don't need to check the last checkpoint again uint256 low = 0; uint256 high = lastIndex - 1; uint32 midTime; uint96 midValue; while (high > low) { uint256 mid = (high + low + 1) / 2; // average, ceil round (midTime, midValue) = decodeSnapshot(_self[mid]); if (_time > midTime) { low = mid; } else if (_time < midTime) { // Note that we don't need SafeMath here because mid must always be greater than 0 // from the while condition high = mid - 1; } else { // _time == midTime return midValue; } } (, snapshotValue) = decodeSnapshot(_self[low]); return snapshotValue; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; interface IForwarder { function isForwarder() external pure returns (bool); function canForward(address sender, bytes calldata evmCallScript) external view returns (bool); function forward(bytes calldata evmCallScript) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; interface TokenManager { function mint(address _receiver, uint256 _amount) external; function issue(uint256 _amount) external; function assign(address _receiver, uint256 _amount) external; function burn(address _holder, uint256 _amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.7.0; import "./IForwarder.sol"; // Interface for Voting contract, as found in https://github.com/aragon/aragon-apps/blob/master/apps/voting/contracts/Voting.sol interface Voting is IForwarder{ enum VoterState { Absent, Yea, Nay } // Public getters function token() external returns (address); function supportRequiredPct() external returns (uint64); function minAcceptQuorumPct() external returns (uint64); function voteTime() external returns (uint64); function votesLength() external returns (uint256); // Setters function changeSupportRequiredPct(uint64 _supportRequiredPct) external; function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external; // Creating new votes function newVote(bytes calldata _executionScript, string memory _metadata) external returns (uint256 voteId); function newVote(bytes calldata _executionScript, string memory _metadata, bool _castVote, bool _executesIfDecided) external returns (uint256 voteId); // Voting function canVote(uint256 _voteId, address _voter) external view returns (bool); function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external; // Executing a passed vote function canExecute(uint256 _voteId) external view returns (bool); function executeVote(uint256 _voteId) external; // Additional info function getVote(uint256 _voteId) external view returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes memory script ); function getVoterState(uint256 _voteId, address _voter) external view returns (VoterState); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/math/SafeMath.sol"; /** * @notice Multi-signature contract with off-chain signing */ contract MultiSig { using SafeMath for uint256; event Executed(address indexed sender, uint256 indexed nonce, address indexed destination, uint256 value); event OwnerAdded(address indexed owner); event OwnerRemoved(address indexed owner); event RequirementChanged(uint16 required); uint256 constant public MAX_OWNER_COUNT = 50; uint256 public nonce; uint8 public required; mapping (address => bool) public isOwner; address[] public owners; /** * @notice Only this contract can call method */ modifier onlyThisContract() { require(msg.sender == address(this)); _; } receive() external payable {} /** * @param _required Number of required signings * @param _owners List of initial owners. */ constructor (uint8 _required, address[] memory _owners) { require(_owners.length <= MAX_OWNER_COUNT && _required <= _owners.length && _required > 0); for (uint256 i = 0; i < _owners.length; i++) { address owner = _owners[i]; require(!isOwner[owner] && owner != address(0)); isOwner[owner] = true; } owners = _owners; required = _required; } /** * @notice Get unsigned hash for transaction parameters * @dev Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191 * @param _sender Trustee who will execute the transaction * @param _destination Destination address * @param _value Amount of ETH to transfer * @param _data Call data * @param _nonce Nonce */ function getUnsignedTransactionHash( address _sender, address _destination, uint256 _value, bytes memory _data, uint256 _nonce ) public view returns (bytes32) { return keccak256( abi.encodePacked(byte(0x19), byte(0), address(this), _sender, _destination, _value, _data, _nonce)); } /** * @dev Note that address recovered from signatures must be strictly increasing * @param _sigV Array of signatures values V * @param _sigR Array of signatures values R * @param _sigS Array of signatures values S * @param _destination Destination address * @param _value Amount of ETH to transfer * @param _data Call data */ function execute( uint8[] calldata _sigV, bytes32[] calldata _sigR, bytes32[] calldata _sigS, address _destination, uint256 _value, bytes calldata _data ) external { require(_sigR.length >= required && _sigR.length == _sigS.length && _sigR.length == _sigV.length); bytes32 txHash = getUnsignedTransactionHash(msg.sender, _destination, _value, _data, nonce); address lastAdd = address(0); for (uint256 i = 0; i < _sigR.length; i++) { address recovered = ecrecover(txHash, _sigV[i], _sigR[i], _sigS[i]); require(recovered > lastAdd && isOwner[recovered]); lastAdd = recovered; } emit Executed(msg.sender, nonce, _destination, _value); nonce = nonce.add(1); (bool callSuccess,) = _destination.call{value: _value}(_data); require(callSuccess); } /** * @notice Allows to add a new owner * @dev Transaction has to be sent by `execute` method. * @param _owner Address of new owner */ function addOwner(address _owner) external onlyThisContract { require(owners.length < MAX_OWNER_COUNT && _owner != address(0) && !isOwner[_owner]); isOwner[_owner] = true; owners.push(_owner); emit OwnerAdded(_owner); } /** * @notice Allows to remove an owner * @dev Transaction has to be sent by `execute` method. * @param _owner Address of owner */ function removeOwner(address _owner) external onlyThisContract { require(owners.length > required && isOwner[_owner]); isOwner[_owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) { if (owners[i] == _owner) { owners[i] = owners[owners.length - 1]; break; } } owners.pop(); emit OwnerRemoved(_owner); } /** * @notice Returns the number of owners of this MultiSig */ function getNumberOfOwners() external view returns (uint256) { return owners.length; } /** * @notice Allows to change the number of required signatures * @dev Transaction has to be sent by `execute` method * @param _required Number of required signatures */ function changeRequirement(uint8 _required) external onlyThisContract { require(_required <= owners.length && _required > 0); required = _required; emit RequirementChanged(_required); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/token/ERC20/SafeERC20.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/math/Math.sol"; import "../zeppelin/utils/Address.sol"; import "./lib/AdditionalMath.sol"; import "./lib/SignatureVerifier.sol"; import "./StakingEscrow.sol"; import "./NuCypherToken.sol"; import "./proxy/Upgradeable.sol"; /** * @title PolicyManager * @notice Contract holds policy data and locks accrued policy fees * @dev |v6.3.1| */ contract PolicyManager is Upgradeable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using AdditionalMath for int256; using AdditionalMath for uint16; using Address for address payable; event PolicyCreated( bytes16 indexed policyId, address indexed sponsor, address indexed owner, uint256 feeRate, uint64 startTimestamp, uint64 endTimestamp, uint256 numberOfNodes ); event ArrangementRevoked( bytes16 indexed policyId, address indexed sender, address indexed node, uint256 value ); event RefundForArrangement( bytes16 indexed policyId, address indexed sender, address indexed node, uint256 value ); event PolicyRevoked(bytes16 indexed policyId, address indexed sender, uint256 value); event RefundForPolicy(bytes16 indexed policyId, address indexed sender, uint256 value); event MinFeeRateSet(address indexed node, uint256 value); // TODO #1501 // Range range event FeeRateRangeSet(address indexed sender, uint256 min, uint256 defaultValue, uint256 max); event Withdrawn(address indexed node, address indexed recipient, uint256 value); struct ArrangementInfo { address node; uint256 indexOfDowntimePeriods; uint16 lastRefundedPeriod; } struct Policy { bool disabled; address payable sponsor; address owner; uint128 feeRate; uint64 startTimestamp; uint64 endTimestamp; uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; ArrangementInfo[] arrangements; } struct NodeInfo { uint128 fee; uint16 previousFeePeriod; uint256 feeRate; uint256 minFeeRate; mapping (uint16 => int256) stub; // former slot for feeDelta mapping (uint16 => int256) feeDelta; } // TODO used only for `delegateGetNodeInfo`, probably will be removed after #1512 struct MemoryNodeInfo { uint128 fee; uint16 previousFeePeriod; uint256 feeRate; uint256 minFeeRate; } struct Range { uint128 min; uint128 defaultValue; uint128 max; } bytes16 internal constant RESERVED_POLICY_ID = bytes16(0); address internal constant RESERVED_NODE = address(0); uint256 internal constant MAX_BALANCE = uint256(uint128(0) - 1); // controlled overflow to get max int256 int256 public constant DEFAULT_FEE_DELTA = int256((uint256(0) - 1) >> 1); StakingEscrow public immutable escrow; uint32 public immutable genesisSecondsPerPeriod; uint32 public immutable secondsPerPeriod; mapping (bytes16 => Policy) public policies; mapping (address => NodeInfo) public nodes; Range public feeRateRange; uint64 public resetTimestamp; /** * @notice Constructor sets address of the escrow contract * @dev Put same address in both inputs variables except when migration is happening * @param _escrowDispatcher Address of escrow dispatcher * @param _escrowImplementation Address of escrow implementation */ constructor(StakingEscrow _escrowDispatcher, StakingEscrow _escrowImplementation) { escrow = _escrowDispatcher; // if the input address is not the StakingEscrow then calling `secondsPerPeriod` will throw error uint32 localSecondsPerPeriod = _escrowImplementation.secondsPerPeriod(); require(localSecondsPerPeriod > 0); secondsPerPeriod = localSecondsPerPeriod; uint32 localgenesisSecondsPerPeriod = _escrowImplementation.genesisSecondsPerPeriod(); require(localgenesisSecondsPerPeriod > 0); genesisSecondsPerPeriod = localgenesisSecondsPerPeriod; // handle case when we deployed new StakingEscrow but not yet upgraded if (_escrowDispatcher != _escrowImplementation) { require(_escrowDispatcher.secondsPerPeriod() == localSecondsPerPeriod || _escrowDispatcher.secondsPerPeriod() == localgenesisSecondsPerPeriod); } } /** * @dev Checks that sender is the StakingEscrow contract */ modifier onlyEscrowContract() { require(msg.sender == address(escrow)); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @return Recalculate period value using new basis */ function recalculatePeriod(uint16 _period) internal view returns (uint16) { return uint16(uint256(_period) * genesisSecondsPerPeriod / 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.previousFeePeriod == 0 && _period < getCurrentPeriod()); nodeInfo.previousFeePeriod = _period; } /** * @notice Migrate from the old period length to the new one * @param _node Node address */ function migrate(address _node) external onlyEscrowContract { NodeInfo storage nodeInfo = nodes[_node]; // with previous period length any previousFeePeriod will be greater than current period // this is a sign of not migrated node require(nodeInfo.previousFeePeriod >= getCurrentPeriod()); nodeInfo.previousFeePeriod = recalculatePeriod(nodeInfo.previousFeePeriod); nodeInfo.feeRate = 0; } /** * @notice Set minimum, default & maximum fee rate for all stakers and all policies ('global fee range') */ // TODO # 1501 // function setFeeRateRange(Range calldata _range) external onlyOwner { function setFeeRateRange(uint128 _min, uint128 _default, uint128 _max) external onlyOwner { require(_min <= _default && _default <= _max); feeRateRange = Range(_min, _default, _max); emit FeeRateRangeSet(msg.sender, _min, _default, _max); } /** * @notice Set the minimum acceptable fee rate (set by staker for their associated worker) * @dev Input value must fall within `feeRateRange` (global fee range) */ function setMinFeeRate(uint256 _minFeeRate) external { require(_minFeeRate >= feeRateRange.min && _minFeeRate <= feeRateRange.max, "The staker's min fee rate must fall within the global fee range"); NodeInfo storage nodeInfo = nodes[msg.sender]; if (nodeInfo.minFeeRate == _minFeeRate) { return; } nodeInfo.minFeeRate = _minFeeRate; emit MinFeeRateSet(msg.sender, _minFeeRate); } /** * @notice Get the minimum acceptable fee rate (set by staker for their associated worker) */ function getMinFeeRate(NodeInfo storage _nodeInfo) internal view returns (uint256) { // if minFeeRate has not been set or chosen value falls outside the global fee range // a default value is returned instead if (_nodeInfo.minFeeRate == 0 || _nodeInfo.minFeeRate < feeRateRange.min || _nodeInfo.minFeeRate > feeRateRange.max) { return feeRateRange.defaultValue; } else { return _nodeInfo.minFeeRate; } } /** * @notice Get the minimum acceptable fee rate (set by staker for their associated worker) */ function getMinFeeRate(address _node) public view returns (uint256) { NodeInfo storage nodeInfo = nodes[_node]; return getMinFeeRate(nodeInfo); } /** * @notice Create policy * @dev Generate policy id before creation * @param _policyId Policy id * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of the policy in seconds * @param _nodes Nodes that will handle policy */ function createPolicy( bytes16 _policyId, address _policyOwner, uint64 _endTimestamp, address[] calldata _nodes ) external payable { require( _endTimestamp > block.timestamp && msg.value > 0 ); require(address(this).balance <= MAX_BALANCE); uint16 currentPeriod = getCurrentPeriod(); uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1; uint256 numberOfPeriods = endPeriod - currentPeriod; uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods); require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length == msg.value); Policy storage policy = createPolicy(_policyId, _policyOwner, _endTimestamp, feeRate, _nodes.length); for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; addFeeToNode(currentPeriod, endPeriod, node, feeRate, int256(feeRate)); policy.arrangements.push(ArrangementInfo(node, 0, 0)); } } /** * @notice Create multiple policies with the same owner, nodes and length * @dev Generate policy ids before creation * @param _policyIds Policy ids * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of all policies in seconds * @param _nodes Nodes that will handle all policies */ function createPolicies( bytes16[] calldata _policyIds, address _policyOwner, uint64 _endTimestamp, address[] calldata _nodes ) external payable { require( _endTimestamp > block.timestamp && msg.value > 0 && _policyIds.length > 1 ); require(address(this).balance <= MAX_BALANCE); uint16 currentPeriod = getCurrentPeriod(); uint16 endPeriod = uint16(_endTimestamp / secondsPerPeriod) + 1; uint256 numberOfPeriods = endPeriod - currentPeriod; uint128 feeRate = uint128(msg.value.div(_nodes.length) / numberOfPeriods / _policyIds.length); require(feeRate > 0 && feeRate * numberOfPeriods * _nodes.length * _policyIds.length == msg.value); for (uint256 i = 0; i < _policyIds.length; i++) { Policy storage policy = createPolicy(_policyIds[i], _policyOwner, _endTimestamp, feeRate, _nodes.length); for (uint256 j = 0; j < _nodes.length; j++) { policy.arrangements.push(ArrangementInfo(_nodes[j], 0, 0)); } } int256 fee = int256(_policyIds.length * feeRate); for (uint256 i = 0; i < _nodes.length; i++) { address node = _nodes[i]; addFeeToNode(currentPeriod, endPeriod, node, feeRate, fee); } } /** * @notice Create policy * @param _policyId Policy id * @param _policyOwner Policy owner. Zero address means sender is owner * @param _endTimestamp End timestamp of the policy in seconds * @param _feeRate Fee rate for policy * @param _nodesLength Number of nodes that will handle policy */ function createPolicy( bytes16 _policyId, address _policyOwner, uint64 _endTimestamp, uint128 _feeRate, uint256 _nodesLength ) internal returns (Policy storage policy) { policy = policies[_policyId]; require( _policyId != RESERVED_POLICY_ID && policy.feeRate == 0 && !policy.disabled ); policy.sponsor = msg.sender; policy.startTimestamp = uint64(block.timestamp); policy.endTimestamp = _endTimestamp; policy.feeRate = _feeRate; if (_policyOwner != msg.sender && _policyOwner != address(0)) { policy.owner = _policyOwner; } emit PolicyCreated( _policyId, msg.sender, _policyOwner == address(0) ? msg.sender : _policyOwner, _feeRate, policy.startTimestamp, policy.endTimestamp, _nodesLength ); } /** * @notice Increase fee rate for specified node * @param _currentPeriod Current period * @param _endPeriod End period of policy * @param _node Node that will handle policy * @param _feeRate Fee rate for one policy * @param _overallFeeRate Fee rate for all policies */ function addFeeToNode( uint16 _currentPeriod, uint16 _endPeriod, address _node, uint128 _feeRate, int256 _overallFeeRate ) internal { require(_node != RESERVED_NODE); NodeInfo storage nodeInfo = nodes[_node]; require(nodeInfo.previousFeePeriod != 0 && nodeInfo.previousFeePeriod < _currentPeriod && _feeRate >= getMinFeeRate(nodeInfo)); // Check default value for feeDelta if (nodeInfo.feeDelta[_currentPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[_currentPeriod] = _overallFeeRate; } else { // Overflow protection removed, because ETH total supply less than uint255/int256 nodeInfo.feeDelta[_currentPeriod] += _overallFeeRate; } if (nodeInfo.feeDelta[_endPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[_endPeriod] = -_overallFeeRate; } else { nodeInfo.feeDelta[_endPeriod] -= _overallFeeRate; } // Reset to default value if needed if (nodeInfo.feeDelta[_currentPeriod] == 0) { nodeInfo.feeDelta[_currentPeriod] = DEFAULT_FEE_DELTA; } if (nodeInfo.feeDelta[_endPeriod] == 0) { nodeInfo.feeDelta[_endPeriod] = DEFAULT_FEE_DELTA; } } /** * @notice Get policy owner */ function getPolicyOwner(bytes16 _policyId) public view returns (address) { Policy storage policy = policies[_policyId]; return policy.owner == address(0) ? policy.sponsor : policy.owner; } /** * @notice Call from StakingEscrow to update node info once per period. * Set default `feeDelta` value for specified period and update node fee * @param _node Node address * @param _processedPeriod1 Processed period * @param _processedPeriod2 Processed period * @param _periodToSetDefault Period to set */ function ping( address _node, uint16 _processedPeriod1, uint16 _processedPeriod2, uint16 _periodToSetDefault ) external onlyEscrowContract { NodeInfo storage node = nodes[_node]; // protection from calling not migrated node, see migrate() require(node.previousFeePeriod <= getCurrentPeriod()); if (_processedPeriod1 != 0) { updateFee(node, _processedPeriod1); } if (_processedPeriod2 != 0) { updateFee(node, _processedPeriod2); } // This code increases gas cost for node in trade of decreasing cost for policy sponsor if (_periodToSetDefault != 0 && node.feeDelta[_periodToSetDefault] == 0) { node.feeDelta[_periodToSetDefault] = DEFAULT_FEE_DELTA; } } /** * @notice Update node fee * @param _info Node info structure * @param _period Processed period */ function updateFee(NodeInfo storage _info, uint16 _period) internal { if (_info.previousFeePeriod == 0 || _period <= _info.previousFeePeriod) { return; } for (uint16 i = _info.previousFeePeriod + 1; i <= _period; i++) { int256 delta = _info.feeDelta[i]; if (delta == DEFAULT_FEE_DELTA) { // gas refund _info.feeDelta[i] = 0; continue; } _info.feeRate = _info.feeRate.addSigned(delta); // gas refund _info.feeDelta[i] = 0; } _info.previousFeePeriod = _period; _info.fee += uint128(_info.feeRate); } /** * @notice Withdraw fee by node */ function withdraw() external returns (uint256) { return withdraw(msg.sender); } /** * @notice Withdraw fee by node * @param _recipient Recipient of the fee */ function withdraw(address payable _recipient) public returns (uint256) { NodeInfo storage node = nodes[msg.sender]; uint256 fee = node.fee; require(fee != 0); node.fee = 0; _recipient.sendValue(fee); emit Withdrawn(msg.sender, _recipient, fee); return fee; } /** * @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 policyStartPeriod = uint16(_policy.startTimestamp / secondsPerPeriod); uint16 maxPeriod = AdditionalMath.min16(getCurrentPeriod(), uint16(_policy.endTimestamp / secondsPerPeriod)); uint16 minPeriod = AdditionalMath.max16(policyStartPeriod, _arrangement.lastRefundedPeriod); uint16 downtimePeriods = 0; uint256 length = escrow.getPastDowntimeLength(_arrangement.node); uint256 initialIndexOfDowntimePeriods; if (_arrangement.lastRefundedPeriod == 0) { initialIndexOfDowntimePeriods = escrow.findIndexOfPastDowntime(_arrangement.node, policyStartPeriod); } else { initialIndexOfDowntimePeriods = _arrangement.indexOfDowntimePeriods; } for (indexOfDowntimePeriods = initialIndexOfDowntimePeriods; indexOfDowntimePeriods < length; indexOfDowntimePeriods++) { (uint16 startPeriod, uint16 endPeriod) = escrow.getPastDowntime(_arrangement.node, indexOfDowntimePeriods); if (startPeriod > maxPeriod) { break; } else if (endPeriod < minPeriod) { continue; } downtimePeriods += AdditionalMath.min16(maxPeriod, endPeriod) .sub16(AdditionalMath.max16(minPeriod, startPeriod)) + 1; if (maxPeriod <= endPeriod) { break; } } uint16 lastCommittedPeriod = escrow.getLastCommittedPeriod(_arrangement.node); if (indexOfDowntimePeriods == length && lastCommittedPeriod < maxPeriod) { // Overflow protection removed: // lastCommittedPeriod < maxPeriod and minPeriod <= maxPeriod + 1 downtimePeriods += maxPeriod - AdditionalMath.max16(minPeriod - 1, lastCommittedPeriod); } refundValue = _policy.feeRate * downtimePeriods; lastRefundedPeriod = maxPeriod + 1; } /** * @notice Revoke/refund arrangement/policy by the sponsor * @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) { refundValue = 0; Policy storage policy = policies[_policyId]; require(!policy.disabled && policy.startTimestamp >= resetTimestamp); uint16 endPeriod = uint16(policy.endTimestamp / secondsPerPeriod) + 1; uint256 numberOfActive = policy.arrangements.length; uint256 i = 0; for (; 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]; // Check default value for feeDelta uint16 lastRefundedPeriod = arrangement.lastRefundedPeriod; if (nodeInfo.feeDelta[lastRefundedPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[lastRefundedPeriod] = -int256(policy.feeRate); } else { nodeInfo.feeDelta[lastRefundedPeriod] -= int256(policy.feeRate); } if (nodeInfo.feeDelta[endPeriod] == DEFAULT_FEE_DELTA) { nodeInfo.feeDelta[endPeriod] = int256(policy.feeRate); } else { nodeInfo.feeDelta[endPeriod] += int256(policy.feeRate); } // Reset to default value if needed if (nodeInfo.feeDelta[lastRefundedPeriod] == 0) { nodeInfo.feeDelta[lastRefundedPeriod] = DEFAULT_FEE_DELTA; } if (nodeInfo.feeDelta[endPeriod] == 0) { nodeInfo.feeDelta[endPeriod] = DEFAULT_FEE_DELTA; } nodeRefundValue += uint256(endPeriod - lastRefundedPeriod) * policy.feeRate; } if (_forceRevoke || arrangement.lastRefundedPeriod >= endPeriod) { arrangement.node = RESERVED_NODE; arrangement.indexOfDowntimePeriods = 0; arrangement.lastRefundedPeriod = 0; numberOfActive--; emit ArrangementRevoked(_policyId, msg.sender, node, nodeRefundValue); } else { emit RefundForArrangement(_policyId, msg.sender, node, nodeRefundValue); } refundValue += nodeRefundValue; if (_node != RESERVED_NODE) { break; } } address payable policySponsor = policy.sponsor; if (_node == RESERVED_NODE) { if (numberOfActive == 0) { policy.disabled = true; // gas refund policy.sponsor = address(0); policy.owner = address(0); policy.feeRate = 0; policy.startTimestamp = 0; policy.endTimestamp = 0; emit PolicyRevoked(_policyId, msg.sender, refundValue); } else { emit RefundForPolicy(_policyId, msg.sender, refundValue); } } else { // arrangement not found require(i < policy.arrangements.length); } if (refundValue > 0) { policySponsor.sendValue(refundValue); } } /** * @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) { refundValue = 0; Policy storage policy = policies[_policyId]; require((policy.owner == msg.sender || policy.sponsor == msg.sender) && !policy.disabled); uint256 i = 0; for (; 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 += nodeRefundValue; if (_node != RESERVED_NODE) { break; } } if (_node != RESERVED_NODE) { // arrangement not found require(i < policy.arrangements.length); } } /** * @notice Revoke policy by the sponsor * @param _policyId Policy id */ function revokePolicy(bytes16 _policyId) external returns (uint256 refundValue) { require(getPolicyOwner(_policyId) == msg.sender); return refundInternal(_policyId, RESERVED_NODE, true); } /** * @notice Revoke arrangement by the sponsor * @param _policyId Policy id * @param _node Node that will be excluded */ function revokeArrangement(bytes16 _policyId, address _node) external returns (uint256 refundValue) { require(_node != RESERVED_NODE); require(getPolicyOwner(_policyId) == msg.sender); return refundInternal(_policyId, _node, true); } /** * @notice Get unsigned hash for revocation * @param _policyId Policy id * @param _node Node that will be excluded * @return Revocation hash, EIP191 version 0x45 ('E') */ function getRevocationHash(bytes16 _policyId, address _node) public view returns (bytes32) { return SignatureVerifier.hashEIP191(abi.encodePacked(_policyId, _node), byte(0x45)); } /** * @notice Check correctness of signature * @param _policyId Policy id * @param _node Node that will be excluded, zero address if whole policy will be revoked * @param _signature Signature of owner */ function checkOwnerSignature(bytes16 _policyId, address _node, bytes memory _signature) internal view { bytes32 hash = getRevocationHash(_policyId, _node); address recovered = SignatureVerifier.recover(hash, _signature); require(getPolicyOwner(_policyId) == recovered); } /** * @notice Revoke policy or arrangement using owner's signature * @param _policyId Policy id * @param _node Node that will be excluded, zero address if whole policy will be revoked * @param _signature Signature of owner, EIP191 version 0x45 ('E') */ function revoke(bytes16 _policyId, address _node, bytes calldata _signature) external returns (uint256 refundValue) { checkOwnerSignature(_policyId, _node, _signature); return refundInternal(_policyId, _node, true); } /** * @notice Refund part of fee by the sponsor * @param _policyId Policy id */ function refund(bytes16 _policyId) external { Policy storage policy = policies[_policyId]; require(policy.owner == msg.sender || policy.sponsor == msg.sender); refundInternal(_policyId, RESERVED_NODE, false); } /** * @notice Refund part of one node's fee by the sponsor * @param _policyId Policy id * @param _node Node address */ function refund(bytes16 _policyId, address _node) external returns (uint256 refundValue) { require(_node != RESERVED_NODE); Policy storage policy = policies[_policyId]; require(policy.owner == msg.sender || policy.sponsor == msg.sender); 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) external view returns (uint256) { return policies[_policyId].arrangements.length; } /** * @notice Get information about staker's fee rate * @param _node Address of staker * @param _period Period to get fee delta */ function getNodeFeeDelta(address _node, uint16 _period) // TODO "virtual" only for tests, probably will be removed after #1512 public view virtual returns (int256) { // TODO remove after upgrade #2579 if (_node == RESERVED_NODE && _period == 11) { return 55; } return nodes[_node].feeDelta[_period]; } /** * @notice Return the information about arrangement */ function getArrangementInfo(bytes16 _policyId, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (ArrangementInfo) external 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, this.policies.selector, 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, this.getArrangementInfo.selector, 2, bytes32(_policyId), bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get NodeInfo structure by delegatecall */ function delegateGetNodeInfo(address _target, address _node) internal returns (MemoryNodeInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.nodes.selector, 1, bytes32(uint256(_node)), 0); assembly { result := memoryAddress } } /** * @dev Get feeRateRange structure by delegatecall */ function delegateGetFeeRateRange(address _target) internal returns (Range memory result) { bytes32 memoryAddress = delegateGetData(_target, this.feeRateRange.selector, 0, 0, 0); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint64(delegateGet(_testTarget, this.resetTimestamp.selector)) == resetTimestamp); Range memory rangeToCheck = delegateGetFeeRateRange(_testTarget); require(feeRateRange.min == rangeToCheck.min && feeRateRange.defaultValue == rangeToCheck.defaultValue && feeRateRange.max == rangeToCheck.max); Policy storage policy = policies[RESERVED_POLICY_ID]; Policy memory policyToCheck = delegateGetPolicy(_testTarget, RESERVED_POLICY_ID); require(policyToCheck.sponsor == policy.sponsor && policyToCheck.owner == policy.owner && policyToCheck.feeRate == policy.feeRate && policyToCheck.startTimestamp == policy.startTimestamp && policyToCheck.endTimestamp == policy.endTimestamp && policyToCheck.disabled == policy.disabled); require(delegateGet(_testTarget, this.getArrangementsLength.selector, RESERVED_POLICY_ID) == policy.arrangements.length); if (policy.arrangements.length > 0) { 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]; MemoryNodeInfo memory nodeInfoToCheck = delegateGetNodeInfo(_testTarget, RESERVED_NODE); require(nodeInfoToCheck.fee == nodeInfo.fee && nodeInfoToCheck.feeRate == nodeInfo.feeRate && nodeInfoToCheck.previousFeePeriod == nodeInfo.previousFeePeriod && nodeInfoToCheck.minFeeRate == nodeInfo.minFeeRate); require(int256(delegateGet(_testTarget, this.getNodeFeeDelta.selector, bytes32(bytes20(RESERVED_NODE)), bytes32(uint256(11)))) == getNodeFeeDelta(RESERVED_NODE, 11)); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); if (resetTimestamp == 0) { resetTimestamp = uint64(block.timestamp); } // Create fake Policy and NodeInfo to use them in verifyState(address) Policy storage policy = policies[RESERVED_POLICY_ID]; policy.sponsor = msg.sender; policy.owner = address(this); policy.startTimestamp = 1; policy.endTimestamp = 2; policy.feeRate = 3; policy.disabled = true; policy.arrangements.push(ArrangementInfo(RESERVED_NODE, 11, 22)); NodeInfo storage nodeInfo = nodes[RESERVED_NODE]; nodeInfo.fee = 100; nodeInfo.feeRate = 33; nodeInfo.previousFeePeriod = 44; nodeInfo.feeDelta[11] = 55; nodeInfo.minFeeRate = 777; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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]. * * _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"); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./Upgradeable.sol"; import "../../zeppelin/utils/Address.sol"; /** * @notice ERC897 - ERC DelegateProxy */ interface ERCProxy { function proxyType() external pure returns (uint256); function implementation() external view returns (address); } /** * @notice Proxying requests to other contracts. * Client should use ABI of real contract and address of this contract */ contract Dispatcher is Upgradeable, ERCProxy { using Address for address; event Upgraded(address indexed from, address indexed to, address owner); event RolledBack(address indexed from, address indexed to, address owner); /** * @dev Set upgrading status before and after operations */ modifier upgrading() { isUpgrade = UPGRADE_TRUE; _; isUpgrade = UPGRADE_FALSE; } /** * @param _target Target contract address */ constructor(address _target) upgrading { require(_target.isContract()); // Checks that target contract inherits Dispatcher state verifyState(_target); // `verifyState` must work with its contract verifyUpgradeableState(_target, _target); target = _target; finishUpgrade(); emit Upgraded(address(0), _target, msg.sender); } //------------------------ERC897------------------------ /** * @notice ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() external pure override returns (uint256) { return 2; } /** * @notice ERC897, gets the address of the implementation where every call will be delegated */ function implementation() external view override returns (address) { return target; } //------------------------------------------------------------ /** * @notice Verify new contract storage and upgrade target * @param _target New target contract address */ function upgrade(address _target) public onlyOwner upgrading { require(_target.isContract()); // Checks that target contract has "correct" (as much as possible) state layout verifyState(_target); //`verifyState` must work with its contract verifyUpgradeableState(_target, _target); if (target.isContract()) { verifyUpgradeableState(target, _target); } previousTarget = target; target = _target; finishUpgrade(); emit Upgraded(previousTarget, _target, msg.sender); } /** * @notice Rollback to previous target * @dev Test storage carefully before upgrade again after rollback */ function rollback() public onlyOwner upgrading { require(previousTarget.isContract()); emit RolledBack(target, previousTarget, msg.sender); // should be always true because layout previousTarget -> target was already checked // but `verifyState` is not 100% accurate so check again verifyState(previousTarget); if (target.isContract()) { verifyUpgradeableState(previousTarget, target); } target = previousTarget; previousTarget = address(0); finishUpgrade(); } /** * @dev Call verifyState method for Upgradeable contract */ function verifyUpgradeableState(address _from, address _to) private { (bool callSuccess,) = _from.delegatecall(abi.encodeWithSelector(this.verifyState.selector, _to)); require(callSuccess); } /** * @dev Call finishUpgrade method from the Upgradeable contract */ function finishUpgrade() private { (bool callSuccess,) = target.delegatecall(abi.encodeWithSelector(this.finishUpgrade.selector, target)); require(callSuccess); } function verifyState(address _testTarget) public override onlyWhileUpgrading { //checks equivalence accessing state through new contract and current storage require(address(uint160(delegateGet(_testTarget, this.owner.selector))) == owner()); require(address(uint160(delegateGet(_testTarget, this.target.selector))) == target); require(address(uint160(delegateGet(_testTarget, this.previousTarget.selector))) == previousTarget); require(uint8(delegateGet(_testTarget, this.isUpgrade.selector)) == isUpgrade); } /** * @dev Override function using empty code because no reason to call this function in Dispatcher */ function finishUpgrade(address) public override {} /** * @dev Receive function sends empty request to the target contract */ receive() external payable { assert(target.isContract()); // execute receive function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(""); if (!callSuccess) { revert(); } } /** * @dev Fallback function sends all requests to the target contract */ fallback() external payable { assert(target.isContract()); // execute requested function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/utils/Address.sol"; import "../../zeppelin/token/ERC20/SafeERC20.sol"; import "./StakingInterface.sol"; import "../../zeppelin/proxy/Initializable.sol"; /** * @notice Router for accessing interface contract */ contract StakingInterfaceRouter is Ownable { BaseStakingInterface public target; /** * @param _target Address of the interface contract */ constructor(BaseStakingInterface _target) { require(address(_target.token()) != address(0)); target = _target; } /** * @notice Upgrade interface * @param _target New contract address */ function upgrade(BaseStakingInterface _target) external onlyOwner { require(address(_target.token()) != address(0)); target = _target; } } /** * @notice Internal base class for AbstractStakingContract and InitializableStakingContract */ abstract contract RawStakingContract { using Address for address; /** * @dev Returns address of StakingInterfaceRouter */ function router() public view virtual returns (StakingInterfaceRouter); /** * @dev Checks permission for calling fallback function */ function isFallbackAllowed() public virtual returns (bool); /** * @dev Withdraw tokens from staking contract */ function withdrawTokens(uint256 _value) public virtual; /** * @dev Withdraw ETH from staking contract */ function withdrawETH() public virtual; receive() external payable {} /** * @dev Function sends all requests to the target contract */ fallback() external payable { require(isFallbackAllowed()); address target = address(router().target()); require(target.isContract()); // execute requested function from target contract (bool callSuccess, ) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } /** * @notice Base class for any staking contract (not usable with openzeppelin proxy) * @dev Implement `isFallbackAllowed()` or override fallback function * Implement `withdrawTokens(uint256)` and `withdrawETH()` functions */ abstract contract AbstractStakingContract is RawStakingContract { StakingInterfaceRouter immutable router_; NuCypherToken public immutable token; /** * @param _router Interface router contract address */ constructor(StakingInterfaceRouter _router) { router_ = _router; NuCypherToken localToken = _router.target().token(); require(address(localToken) != address(0)); token = localToken; } /** * @dev Returns address of StakingInterfaceRouter */ function router() public view override returns (StakingInterfaceRouter) { return router_; } } /** * @notice Base class for any staking contract usable with openzeppelin proxy * @dev Implement `isFallbackAllowed()` or override fallback function * Implement `withdrawTokens(uint256)` and `withdrawETH()` functions */ abstract contract InitializableStakingContract is Initializable, RawStakingContract { StakingInterfaceRouter router_; NuCypherToken public token; /** * @param _router Interface router contract address */ function initialize(StakingInterfaceRouter _router) public initializer { router_ = _router; NuCypherToken localToken = _router.target().token(); require(address(localToken) != address(0)); token = localToken; } /** * @dev Returns address of StakingInterfaceRouter */ function router() public view override returns (StakingInterfaceRouter) { return router_; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "./AbstractStakingContract.sol"; import "../NuCypherToken.sol"; import "../StakingEscrow.sol"; import "../PolicyManager.sol"; import "../WorkLock.sol"; /** * @notice Base StakingInterface */ contract BaseStakingInterface { address public immutable stakingInterfaceAddress; NuCypherToken public immutable token; StakingEscrow public immutable escrow; PolicyManager public immutable policyManager; WorkLock public immutable workLock; /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract * @param _workLock WorkLock contract */ constructor( NuCypherToken _token, StakingEscrow _escrow, PolicyManager _policyManager, WorkLock _workLock ) { require(_token.totalSupply() > 0 && _escrow.secondsPerPeriod() > 0 && _policyManager.secondsPerPeriod() > 0 && // in case there is no worklock contract (address(_workLock) == address(0) || _workLock.boostingRefund() > 0)); token = _token; escrow = _escrow; policyManager = _policyManager; workLock = _workLock; stakingInterfaceAddress = address(this); } /** * @dev Checks executing through delegate call */ modifier onlyDelegateCall() { require(stakingInterfaceAddress != address(this)); _; } /** * @dev Checks the existence of the worklock contract */ modifier workLockSet() { require(address(workLock) != address(0)); _; } } /** * @notice Interface for accessing main contracts from a staking contract * @dev All methods must be stateless because this code will be executed by delegatecall call, use immutable fields. * @dev |v1.7.1| */ contract StakingInterface is BaseStakingInterface { event DepositedAsStaker(address indexed sender, uint256 value, uint16 periods); event WithdrawnAsStaker(address indexed sender, uint256 value); event DepositedAndIncreased(address indexed sender, uint256 index, uint256 value); event LockedAndCreated(address indexed sender, uint256 value, uint16 periods); event LockedAndIncreased(address indexed sender, uint256 index, uint256 value); event Divided(address indexed sender, uint256 index, uint256 newValue, uint16 periods); event Merged(address indexed sender, uint256 index1, uint256 index2); event Minted(address indexed sender); event PolicyFeeWithdrawn(address indexed sender, uint256 value); event MinFeeRateSet(address indexed sender, uint256 value); event ReStakeSet(address indexed sender, bool reStake); event WorkerBonded(address indexed sender, address worker); event Prolonged(address indexed sender, uint256 index, uint16 periods); event WindDownSet(address indexed sender, bool windDown); event SnapshotSet(address indexed sender, bool snapshotsEnabled); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH); event BidCanceled(address indexed sender); event CompensationWithdrawn(address indexed sender); /** * @notice Constructor sets addresses of the contracts * @param _token Token contract * @param _escrow Escrow contract * @param _policyManager PolicyManager contract * @param _workLock WorkLock contract */ constructor( NuCypherToken _token, StakingEscrow _escrow, PolicyManager _policyManager, WorkLock _workLock ) BaseStakingInterface(_token, _escrow, _policyManager, _workLock) { } /** * @notice Bond worker in the staking escrow * @param _worker Worker address */ function bondWorker(address _worker) public onlyDelegateCall { escrow.bondWorker(_worker); emit WorkerBonded(msg.sender, _worker); } /** * @notice Set `reStake` parameter in the staking escrow * @param _reStake Value for parameter */ function setReStake(bool _reStake) public onlyDelegateCall { escrow.setReStake(_reStake); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Deposit tokens to the staking escrow * @param _value Amount of token to deposit * @param _periods Amount of periods during which tokens will be locked */ function depositAsStaker(uint256 _value, uint16 _periods) public onlyDelegateCall { require(token.balanceOf(address(this)) >= _value); token.approve(address(escrow), _value); escrow.deposit(address(this), _value, _periods); emit DepositedAsStaker(msg.sender, _value, _periods); } /** * @notice Deposit tokens to the staking escrow * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall { require(token.balanceOf(address(this)) >= _value); token.approve(address(escrow), _value); escrow.depositAndIncrease(_index, _value); emit DepositedAndIncreased(msg.sender, _index, _value); } /** * @notice Withdraw available amount of tokens from the staking escrow to the staking contract * @param _value Amount of token to withdraw */ function withdrawAsStaker(uint256 _value) public onlyDelegateCall { escrow.withdraw(_value); emit WithdrawnAsStaker(msg.sender, _value); } /** * @notice Lock some tokens in the staking escrow * @param _value Amount of tokens which should lock * @param _periods Amount of periods during which tokens will be locked */ function lockAndCreate(uint256 _value, uint16 _periods) public onlyDelegateCall { escrow.lockAndCreate(_value, _periods); emit LockedAndCreated(msg.sender, _value, _periods); } /** * @notice Lock some tokens in the staking escrow * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) public onlyDelegateCall { escrow.lockAndIncrease(_index, _value); emit LockedAndIncreased(msg.sender, _index, _value); } /** * @notice Divide stake into two parts * @param _index Index of stake * @param _newValue New stake value * @param _periods Amount of periods for extending stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) public onlyDelegateCall { escrow.divideStake(_index, _newValue, _periods); emit Divided(msg.sender, _index, _newValue, _periods); } /** * @notice Merge two sub-stakes into one * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) public onlyDelegateCall { escrow.mergeStake(_index1, _index2); emit Merged(msg.sender, _index1, _index2); } /** * @notice Mint tokens in the staking escrow */ function mint() public onlyDelegateCall { escrow.mint(); emit Minted(msg.sender); } /** * @notice Withdraw available policy fees from the policy manager to the staking contract */ function withdrawPolicyFee() public onlyDelegateCall { uint256 value = policyManager.withdraw(); emit PolicyFeeWithdrawn(msg.sender, value); } /** * @notice Set the minimum fee that the staker will accept in the policy manager contract */ function setMinFeeRate(uint256 _minFeeRate) public onlyDelegateCall { policyManager.setMinFeeRate(_minFeeRate); emit MinFeeRateSet(msg.sender, _minFeeRate); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _periods Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _periods) public onlyDelegateCall { escrow.prolongStake(_index, _periods); emit Prolonged(msg.sender, _index, _periods); } /** * @notice Set `windDown` parameter in the staking escrow * @param _windDown Value for parameter */ function setWindDown(bool _windDown) public onlyDelegateCall { escrow.setWindDown(_windDown); emit WindDownSet(msg.sender, _windDown); } /** * @notice Set `snapshots` parameter in the staking escrow * @param _enableSnapshots Value for parameter */ function setSnapshots(bool _enableSnapshots) public onlyDelegateCall { escrow.setSnapshots(_enableSnapshots); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Bid for tokens by transferring ETH */ function bid(uint256 _value) public payable onlyDelegateCall workLockSet { workLock.bid{value: _value}(); emit Bid(msg.sender, _value); } /** * @notice Cancel bid and refund deposited ETH */ function cancelBid() public onlyDelegateCall workLockSet { workLock.cancelBid(); emit BidCanceled(msg.sender); } /** * @notice Withdraw compensation after force refund */ function withdrawCompensation() public onlyDelegateCall workLockSet { workLock.withdrawCompensation(); emit CompensationWithdrawn(msg.sender); } /** * @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract */ function claim() public onlyDelegateCall workLockSet { uint256 claimedTokens = workLock.claim(); emit Claimed(msg.sender, claimedTokens); } /** * @notice Refund ETH for the completed work */ function refund() public onlyDelegateCall workLockSet { uint256 refundETH = workLock.refund(); emit Refund(msg.sender, refundETH); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/token/ERC20/SafeERC20.sol"; import "../zeppelin/utils/Address.sol"; import "../zeppelin/ownership/Ownable.sol"; import "./NuCypherToken.sol"; import "./StakingEscrow.sol"; import "./lib/AdditionalMath.sol"; /** * @notice The WorkLock distribution contract */ contract WorkLock is Ownable { using SafeERC20 for NuCypherToken; using SafeMath for uint256; using AdditionalMath for uint256; using Address for address payable; using Address for address; event Deposited(address indexed sender, uint256 value); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH, uint256 completedWork); event Canceled(address indexed sender, uint256 value); event BiddersChecked(address indexed sender, uint256 startIndex, uint256 endIndex); event ForceRefund(address indexed sender, address indexed bidder, uint256 refundETH); event CompensationWithdrawn(address indexed sender, uint256 value); event Shutdown(address indexed sender); struct WorkInfo { uint256 depositedETH; uint256 completedWork; bool claimed; uint128 index; } uint16 public constant SLOWING_REFUND = 100; uint256 private constant MAX_ETH_SUPPLY = 2e10 ether; NuCypherToken public immutable token; StakingEscrow public immutable escrow; /* * @dev WorkLock calculations: * bid = minBid + bonusETHPart * bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens * bonusDepositRate = bonusTokenSupply / bonusETHSupply * claimedTokens = minAllowableLockedTokens + bonusETHPart * bonusDepositRate * bonusRefundRate = bonusDepositRate * SLOWING_REFUND / boostingRefund * refundETH = completedWork / refundRate */ uint256 public immutable boostingRefund; uint256 public immutable minAllowedBid; uint16 public immutable stakingPeriods; // copy from the escrow contract uint256 public immutable maxAllowableLockedTokens; uint256 public immutable minAllowableLockedTokens; uint256 public tokenSupply; uint256 public startBidDate; uint256 public endBidDate; uint256 public endCancellationDate; uint256 public bonusETHSupply; mapping(address => WorkInfo) public workInfo; mapping(address => uint256) public compensation; address[] public bidders; // if value == bidders.length then WorkLock is fully checked uint256 public nextBidderToCheck; /** * @dev Checks timestamp regarding cancellation window */ modifier afterCancellationWindow() { require(block.timestamp >= endCancellationDate, "Operation is allowed when cancellation phase is over"); _; } /** * @param _token Token contract * @param _escrow Escrow contract * @param _startBidDate Timestamp when bidding starts * @param _endBidDate Timestamp when bidding will end * @param _endCancellationDate Timestamp when cancellation will ends * @param _boostingRefund Coefficient to boost refund ETH * @param _stakingPeriods Amount of periods during which tokens will be locked after claiming * @param _minAllowedBid Minimum allowed ETH amount for bidding */ constructor( NuCypherToken _token, StakingEscrow _escrow, uint256 _startBidDate, uint256 _endBidDate, uint256 _endCancellationDate, uint256 _boostingRefund, uint16 _stakingPeriods, uint256 _minAllowedBid ) { uint256 totalSupply = _token.totalSupply(); require(totalSupply > 0 && // token contract is deployed and accessible _escrow.secondsPerPeriod() > 0 && // escrow contract is deployed and accessible _escrow.token() == _token && // same token address for worklock and escrow _endBidDate > _startBidDate && // bidding period lasts some time _endBidDate > block.timestamp && // there is time to make a bid _endCancellationDate >= _endBidDate && // cancellation window includes bidding _minAllowedBid > 0 && // min allowed bid was set _boostingRefund > 0 && // boosting coefficient was set _stakingPeriods >= _escrow.minLockedPeriods()); // staking duration is consistent with escrow contract // worst case for `ethToWork()` and `workToETH()`, // when ethSupply == MAX_ETH_SUPPLY and tokenSupply == totalSupply require(MAX_ETH_SUPPLY * totalSupply * SLOWING_REFUND / MAX_ETH_SUPPLY / totalSupply == SLOWING_REFUND && MAX_ETH_SUPPLY * totalSupply * _boostingRefund / MAX_ETH_SUPPLY / totalSupply == _boostingRefund); token = _token; escrow = _escrow; startBidDate = _startBidDate; endBidDate = _endBidDate; endCancellationDate = _endCancellationDate; boostingRefund = _boostingRefund; stakingPeriods = _stakingPeriods; minAllowedBid = _minAllowedBid; maxAllowableLockedTokens = _escrow.maxAllowableLockedTokens(); minAllowableLockedTokens = _escrow.minAllowableLockedTokens(); } /** * @notice Deposit tokens to contract * @param _value Amount of tokens to transfer */ function tokenDeposit(uint256 _value) external { require(block.timestamp < endBidDate, "Can't deposit more tokens after end of bidding"); token.safeTransferFrom(msg.sender, address(this), _value); tokenSupply += _value; emit Deposited(msg.sender, _value); } /** * @notice Calculate amount of tokens that will be get for specified amount of ETH * @dev This value will be fixed only after end of bidding */ function ethToTokens(uint256 _ethAmount) public view returns (uint256) { if (_ethAmount < minAllowedBid) { return 0; } // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return tokenSupply / bidders.length; } uint256 bonusETH = _ethAmount - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; return minAllowableLockedTokens + bonusETH.mul(bonusTokenSupply).div(bonusETHSupply); } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH */ function ethToWork(uint256 _ethAmount, uint256 _tokenSupply, uint256 _ethSupply) internal view returns (uint256) { return _ethAmount.mul(_tokenSupply).mul(SLOWING_REFUND).divCeil(_ethSupply.mul(boostingRefund)); } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH * @dev This value will be fixed only after end of bidding * @param _ethToReclaim Specified sum of ETH staker wishes to reclaim following completion of work * @param _restOfDepositedETH Remaining ETH in staker's deposit once ethToReclaim sum has been subtracted * @dev _ethToReclaim + _restOfDepositedETH = depositedETH */ function ethToWork(uint256 _ethToReclaim, uint256 _restOfDepositedETH) internal view returns (uint256) { uint256 baseETHSupply = bidders.length * minAllowedBid; // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return ethToWork(_ethToReclaim, tokenSupply, baseETHSupply); } uint256 baseETH = 0; uint256 bonusETH = 0; // If the staker's total remaining deposit (including the specified sum of ETH to reclaim) // is lower than the minimum bid size, // then only the base part is used to calculate the work required to reclaim ETH if (_ethToReclaim + _restOfDepositedETH <= minAllowedBid) { baseETH = _ethToReclaim; // If the staker's remaining deposit (not including the specified sum of ETH to reclaim) // is still greater than the minimum bid size, // then only the bonus part is used to calculate the work required to reclaim ETH } else if (_restOfDepositedETH >= minAllowedBid) { bonusETH = _ethToReclaim; // If the staker's remaining deposit (not including the specified sum of ETH to reclaim) // is lower than the minimum bid size, // then both the base and bonus parts must be used to calculate the work required to reclaim ETH } else { bonusETH = _ethToReclaim + _restOfDepositedETH - minAllowedBid; baseETH = _ethToReclaim - bonusETH; } uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens; uint256 work = 0; if (baseETH > 0) { work = ethToWork(baseETH, baseTokenSupply, baseETHSupply); } if (bonusETH > 0) { uint256 bonusTokenSupply = tokenSupply - baseTokenSupply; work += ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply); } return work; } /** * @notice Calculate amount of work that need to be done to refund specified amount of ETH * @dev This value will be fixed only after end of bidding */ function ethToWork(uint256 _ethAmount) public view returns (uint256) { return ethToWork(_ethAmount, 0); } /** * @notice Calculate amount of ETH that will be refund for completing specified amount of work */ function workToETH(uint256 _completedWork, uint256 _ethSupply, uint256 _tokenSupply) internal view returns (uint256) { return _completedWork.mul(_ethSupply).mul(boostingRefund).div(_tokenSupply.mul(SLOWING_REFUND)); } /** * @notice Calculate amount of ETH that will be refund for completing specified amount of work * @dev This value will be fixed only after end of bidding */ function workToETH(uint256 _completedWork, uint256 _depositedETH) public view returns (uint256) { uint256 baseETHSupply = bidders.length * minAllowedBid; // when all participants bid with the same minimum amount of eth if (bonusETHSupply == 0) { return workToETH(_completedWork, baseETHSupply, tokenSupply); } uint256 bonusWork = 0; uint256 bonusETH = 0; uint256 baseTokenSupply = bidders.length * minAllowableLockedTokens; if (_depositedETH > minAllowedBid) { bonusETH = _depositedETH - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - baseTokenSupply; bonusWork = ethToWork(bonusETH, bonusTokenSupply, bonusETHSupply); if (_completedWork <= bonusWork) { return workToETH(_completedWork, bonusETHSupply, bonusTokenSupply); } } _completedWork -= bonusWork; return bonusETH + workToETH(_completedWork, baseETHSupply, baseTokenSupply); } /** * @notice Get remaining work to full refund */ function getRemainingWork(address _bidder) external view returns (uint256) { WorkInfo storage info = workInfo[_bidder]; uint256 completedWork = escrow.getCompletedWork(_bidder).sub(info.completedWork); uint256 remainingWork = ethToWork(info.depositedETH); if (remainingWork <= completedWork) { return 0; } return remainingWork - completedWork; } /** * @notice Get length of bidders array */ function getBiddersLength() external view returns (uint256) { return bidders.length; } /** * @notice Bid for tokens by transferring ETH */ function bid() external payable { require(block.timestamp >= startBidDate, "Bidding is not open yet"); require(block.timestamp < endBidDate, "Bidding is already finished"); WorkInfo storage info = workInfo[msg.sender]; // first bid if (info.depositedETH == 0) { require(msg.value >= minAllowedBid, "Bid must be at least minimum"); require(bidders.length < tokenSupply / minAllowableLockedTokens, "Not enough tokens for more bidders"); info.index = uint128(bidders.length); bidders.push(msg.sender); bonusETHSupply = bonusETHSupply.add(msg.value - minAllowedBid); } else { bonusETHSupply = bonusETHSupply.add(msg.value); } info.depositedETH = info.depositedETH.add(msg.value); emit Bid(msg.sender, msg.value); } /** * @notice Cancel bid and refund deposited ETH */ function cancelBid() external { require(block.timestamp < endCancellationDate, "Cancellation allowed only during cancellation window"); WorkInfo storage info = workInfo[msg.sender]; require(info.depositedETH > 0, "No bid to cancel"); require(!info.claimed, "Tokens are already claimed"); uint256 refundETH = info.depositedETH; info.depositedETH = 0; // remove from bidders array, move last bidder to the empty place uint256 lastIndex = bidders.length - 1; if (info.index != lastIndex) { address lastBidder = bidders[lastIndex]; bidders[info.index] = lastBidder; workInfo[lastBidder].index = info.index; } bidders.pop(); if (refundETH > minAllowedBid) { bonusETHSupply = bonusETHSupply.sub(refundETH - minAllowedBid); } msg.sender.sendValue(refundETH); emit Canceled(msg.sender, refundETH); } /** * @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens */ function shutdown() external onlyOwner { require(!isClaimingAvailable(), "Claiming has already been enabled"); internalShutdown(); } /** * @notice Cancels distribution, makes possible to retrieve all bids and owner gets all tokens */ function internalShutdown() internal { startBidDate = 0; endBidDate = 0; endCancellationDate = uint256(0) - 1; // "infinite" cancellation window token.safeTransfer(owner(), tokenSupply); emit Shutdown(msg.sender); } /** * @notice Make force refund to bidders who can get tokens more than maximum allowed * @param _biddersForRefund Sorted list of unique bidders. Only bidders who must receive a refund */ function forceRefund(address payable[] calldata _biddersForRefund) external afterCancellationWindow { require(nextBidderToCheck != bidders.length, "Bidders have already been checked"); uint256 length = _biddersForRefund.length; require(length > 0, "Must be at least one bidder for a refund"); uint256 minNumberOfBidders = tokenSupply.divCeil(maxAllowableLockedTokens); if (bidders.length < minNumberOfBidders) { internalShutdown(); return; } address previousBidder = _biddersForRefund[0]; uint256 minBid = workInfo[previousBidder].depositedETH; uint256 maxBid = minBid; // get minimum and maximum bids for (uint256 i = 1; i < length; i++) { address bidder = _biddersForRefund[i]; uint256 depositedETH = workInfo[bidder].depositedETH; require(bidder > previousBidder && depositedETH > 0, "Addresses must be an array of unique bidders"); if (minBid > depositedETH) { minBid = depositedETH; } else if (maxBid < depositedETH) { maxBid = depositedETH; } previousBidder = bidder; } uint256[] memory refunds = new uint256[](length); // first step - align at a minimum bid if (minBid != maxBid) { for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; WorkInfo storage info = workInfo[bidder]; if (info.depositedETH > minBid) { refunds[i] = info.depositedETH - minBid; info.depositedETH = minBid; bonusETHSupply -= refunds[i]; } } } require(ethToTokens(minBid) > maxAllowableLockedTokens, "At least one of bidders has allowable bid"); // final bids adjustment (only for bonus part) // (min_whale_bid * token_supply - max_stake * eth_supply) / (token_supply - max_stake * n_whales) uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens; uint256 minBonusETH = minBid - minAllowedBid; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; uint256 refundETH = minBonusETH.mul(bonusTokenSupply) .sub(maxBonusTokens.mul(bonusETHSupply)) .divCeil(bonusTokenSupply - maxBonusTokens.mul(length)); uint256 resultBid = minBid.sub(refundETH); bonusETHSupply -= length * refundETH; for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; WorkInfo storage info = workInfo[bidder]; refunds[i] += refundETH; info.depositedETH = resultBid; } // reset verification nextBidderToCheck = 0; // save a refund for (uint256 i = 0; i < length; i++) { address bidder = _biddersForRefund[i]; compensation[bidder] += refunds[i]; emit ForceRefund(msg.sender, bidder, refunds[i]); } } /** * @notice Withdraw compensation after force refund */ function withdrawCompensation() external { uint256 refund = compensation[msg.sender]; require(refund > 0, "There is no compensation"); compensation[msg.sender] = 0; msg.sender.sendValue(refund); emit CompensationWithdrawn(msg.sender, refund); } /** * @notice Check that the claimed tokens are within `maxAllowableLockedTokens` for all participants, * starting from the last point `nextBidderToCheck` * @dev Method stops working when the remaining gas is less than `_gasToSaveState` * and saves the state in `nextBidderToCheck`. * If all bidders have been checked then `nextBidderToCheck` will be equal to the length of the bidders array */ function verifyBiddingCorrectness(uint256 _gasToSaveState) external afterCancellationWindow returns (uint256) { require(nextBidderToCheck != bidders.length, "Bidders have already been checked"); // all participants bid with the same minimum amount of eth uint256 index = nextBidderToCheck; if (bonusETHSupply == 0) { require(tokenSupply / bidders.length <= maxAllowableLockedTokens, "Not enough bidders"); index = bidders.length; } uint256 maxBonusTokens = maxAllowableLockedTokens - minAllowableLockedTokens; uint256 bonusTokenSupply = tokenSupply - bidders.length * minAllowableLockedTokens; uint256 maxBidFromMaxStake = minAllowedBid + maxBonusTokens.mul(bonusETHSupply).div(bonusTokenSupply); while (index < bidders.length && gasleft() > _gasToSaveState) { address bidder = bidders[index]; require(workInfo[bidder].depositedETH <= maxBidFromMaxStake, "Bid is greater than max allowable bid"); index++; } if (index != nextBidderToCheck) { emit BiddersChecked(msg.sender, nextBidderToCheck, index); nextBidderToCheck = index; } return nextBidderToCheck; } /** * @notice Checks if claiming available */ function isClaimingAvailable() public view returns (bool) { return block.timestamp >= endCancellationDate && nextBidderToCheck == bidders.length; } /** * @notice Claimed tokens will be deposited and locked as stake in the StakingEscrow contract. */ function claim() external returns (uint256 claimedTokens) { require(isClaimingAvailable(), "Claiming has not been enabled yet"); WorkInfo storage info = workInfo[msg.sender]; require(!info.claimed, "Tokens are already claimed"); claimedTokens = ethToTokens(info.depositedETH); require(claimedTokens > 0, "Nothing to claim"); info.claimed = true; token.approve(address(escrow), claimedTokens); escrow.depositFromWorkLock(msg.sender, claimedTokens, stakingPeriods); info.completedWork = escrow.setWorkMeasurement(msg.sender, true); emit Claimed(msg.sender, claimedTokens); } /** * @notice Get available refund for bidder */ function getAvailableRefund(address _bidder) public view returns (uint256) { WorkInfo storage info = workInfo[_bidder]; // nothing to refund if (info.depositedETH == 0) { return 0; } uint256 currentWork = escrow.getCompletedWork(_bidder); uint256 completedWork = currentWork.sub(info.completedWork); // no work that has been completed since last refund if (completedWork == 0) { return 0; } uint256 refundETH = workToETH(completedWork, info.depositedETH); if (refundETH > info.depositedETH) { refundETH = info.depositedETH; } return refundETH; } /** * @notice Refund ETH for the completed work */ function refund() external returns (uint256 refundETH) { WorkInfo storage info = workInfo[msg.sender]; require(info.claimed, "Tokens must be claimed before refund"); refundETH = getAvailableRefund(msg.sender); require(refundETH > 0, "Nothing to refund: there is no ETH to refund or no completed work"); if (refundETH == info.depositedETH) { escrow.setWorkMeasurement(msg.sender, false); } info.depositedETH = info.depositedETH.sub(refundETH); // convert refund back to work to eliminate potential rounding errors uint256 completedWork = ethToWork(refundETH, info.depositedETH); info.completedWork = info.completedWork.add(completedWork); emit Refund(msg.sender, refundETH, completedWork); msg.sender.sendValue(refundETH); } } // SPDX-License-Identifier: AGPL-3.0-or-later 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; } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers and owner **/ contract PoolingStakingContract is AbstractStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited(address indexed sender, uint256 value, uint256 depositedTokens); event TokensWithdrawn(address indexed sender, uint256 value, uint256 depositedTokens); event ETHWithdrawn(address indexed sender, uint256 value); event DepositSet(address indexed sender, bool value); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; } StakingEscrow public immutable escrow; uint256 public totalDepositedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 public ownerFraction; uint256 public ownerWithdrawnReward; uint256 public ownerWithdrawnETH; mapping (address => Delegator) public delegators; bool depositIsEnabled = true; /** * @param _router Address of the StakingInterfaceRouter contract * @param _ownerFraction Base owner's portion of reward */ constructor( StakingInterfaceRouter _router, uint256 _ownerFraction ) AbstractStakingContract(_router) { escrow = _router.target().escrow(); ownerFraction = _ownerFraction; } /** * @notice Enabled deposit */ function enableDeposit() external onlyOwner { depositIsEnabled = true; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Disable deposit */ function disableDeposit() external onlyOwner { depositIsEnabled = false; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(depositIsEnabled, "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens += _value; token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { uint256 stakedTokens = escrow.getAllTokens(address(this)); uint256 freeTokens = token.balanceOf(address(this)); uint256 reward = stakedTokens + freeTokens - totalDepositedTokens; if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for pool owner */ function getAvailableOwnerReward() public view returns (uint256) { uint256 reward = getCumulativeReward(); uint256 maxAllowableReward; if (totalDepositedTokens != 0) { maxAllowableReward = reward.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction)); } else { maxAllowableReward = reward; } return maxAllowableReward.sub(ownerWithdrawnReward); } /** * @notice Get available reward in tokens for delegator */ function getAvailableReward(address _delegator) public view returns (uint256) { if (totalDepositedTokens == 0) { return 0; } uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 maxAllowableReward = reward.mul(delegator.depositedTokens) .div(totalDepositedTokens.add(ownerFraction)); return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0; } /** * @notice Withdraw reward in tokens to owner */ function withdrawOwnerReward() public onlyOwner { uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableOwnerReward(); if (availableReward > balance) { availableReward = balance; } require(availableReward > 0, "There is no available reward to withdraw"); ownerWithdrawnReward = ownerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw amount of tokens to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); uint256 availableReward = getAvailableReward(msg.sender); Delegator storage delegator = delegators[msg.sender]; require(_value <= availableReward + delegator.depositedTokens, "Requested amount of tokens exceeded allowed portion"); if (_value <= availableReward) { delegator.withdrawnReward += _value; totalWithdrawnReward += _value; } else { delegator.withdrawnReward = delegator.withdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); uint256 depositToWithdraw = _value - availableReward; uint256 newDepositedTokens = delegator.depositedTokens - depositToWithdraw; uint256 newWithdrawnReward = delegator.withdrawnReward.mul(newDepositedTokens).div(delegator.depositedTokens); uint256 newWithdrawnETH = delegator.withdrawnETH.mul(newDepositedTokens).div(delegator.depositedTokens); totalDepositedTokens -= depositToWithdraw; totalWithdrawnReward -= (delegator.withdrawnReward - newWithdrawnReward); totalWithdrawnETH -= (delegator.withdrawnETH - newWithdrawnETH); delegator.depositedTokens = newDepositedTokens; delegator.withdrawnReward = newWithdrawnReward; delegator.withdrawnETH = newWithdrawnETH; } token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available ether for owner */ function getAvailableOwnerETH() public view returns (uint256) { // TODO boilerplate code uint256 balance = address(this).balance; balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(ownerFraction).div(totalDepositedTokens.add(ownerFraction)); uint256 availableETH = maxAllowableETH.sub(ownerWithdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Get available ether for delegator */ function getAvailableETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; // TODO boilerplate code uint256 balance = address(this).balance; balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens) .div(totalDepositedTokens.add(ownerFraction)); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to pool owner */ function withdrawOwnerETH() public onlyOwner { uint256 availableETH = getAvailableOwnerETH(); require(availableETH > 0, "There is no available ETH to withdraw"); ownerWithdrawnETH = ownerWithdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { uint256 availableETH = getAvailableETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Calling fallback function is allowed only for the owner **/ function isFallbackAllowed() public view override returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers **/ contract PoolingStakingContractV2 is InitializableStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited( address indexed sender, uint256 value, uint256 depositedTokens ); event TokensWithdrawn( address indexed sender, uint256 value, uint256 depositedTokens ); event ETHWithdrawn(address indexed sender, uint256 value); event WorkerOwnerSet(address indexed sender, address indexed workerOwner); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; } /** * Defines base fraction and precision of worker fraction. * E.g., for a value of 10000, a worker fraction of 100 represents 1% of reward (100/10000) */ uint256 public constant BASIS_FRACTION = 10000; StakingEscrow public escrow; address public workerOwner; uint256 public totalDepositedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 workerFraction; uint256 public workerWithdrawnReward; mapping(address => Delegator) public delegators; /** * @notice Initialize function for using with OpenZeppelin proxy * @param _workerFraction Share of token reward that worker node owner will get. * Use value up to BASIS_FRACTION (10000), if _workerFraction = BASIS_FRACTION -> means 100% reward as commission. * For example, 100 worker fraction is 1% of reward * @param _router StakingInterfaceRouter address * @param _workerOwner Owner of worker node, only this address can withdraw worker commission */ function initialize( uint256 _workerFraction, StakingInterfaceRouter _router, address _workerOwner ) external initializer { require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION); InitializableStakingContract.initialize(_router); _transferOwnership(msg.sender); escrow = _router.target().escrow(); workerFraction = _workerFraction; workerOwner = _workerOwner; emit WorkerOwnerSet(msg.sender, _workerOwner); } /** * @notice withdrawAll() is allowed */ function isWithdrawAllAllowed() public view returns (bool) { // no tokens in StakingEscrow contract which belong to pool return escrow.getAllTokens(address(this)) == 0; } /** * @notice deposit() is allowed */ function isDepositAllowed() public view returns (bool) { // tokens which directly belong to pool uint256 freeTokens = token.balanceOf(address(this)); // no sub-stakes and no earned reward return isWithdrawAllAllowed() && freeTokens == totalDepositedTokens; } /** * @notice Set worker owner address */ function setWorkerOwner(address _workerOwner) external onlyOwner { workerOwner = _workerOwner; emit WorkerOwnerSet(msg.sender, _workerOwner); } /** * @notice Calculate worker's fraction depending on deposited tokens * Override to implement dynamic worker fraction. */ function getWorkerFraction() public view virtual returns (uint256) { return workerFraction; } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(isDepositAllowed(), "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens = delegator.depositedTokens.add(_value); token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { // locked + unlocked tokens in StakingEscrow contract which belong to pool uint256 stakedTokens = escrow.getAllTokens(address(this)); // tokens which directly belong to pool uint256 freeTokens = token.balanceOf(address(this)); // tokens in excess of the initially deposited uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens); // check how many of reward tokens belong directly to pool if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward. * Available and withdrawn reward together to use in delegator/owner reward calculations */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for worker node owner */ function getAvailableWorkerReward() public view returns (uint256) { // total current and historical reward uint256 reward = getCumulativeReward(); // calculate total reward for worker including historical reward uint256 maxAllowableReward; // usual case if (totalDepositedTokens != 0) { uint256 fraction = getWorkerFraction(); maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION); // special case when there are no delegators } else { maxAllowableReward = reward; } // check that worker has any new reward if (maxAllowableReward > workerWithdrawnReward) { return maxAllowableReward - workerWithdrawnReward; } return 0; } /** * @notice Get available reward in tokens for delegator */ function getAvailableDelegatorReward(address _delegator) public view returns (uint256) { // special case when there are no delegators if (totalDepositedTokens == 0) { return 0; } // total current and historical reward uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 fraction = getWorkerFraction(); // calculate total reward for delegator including historical reward // excluding worker share uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div( totalDepositedTokens.mul(BASIS_FRACTION) ); // check that worker has any new reward if (maxAllowableReward > delegator.withdrawnReward) { return maxAllowableReward - delegator.withdrawnReward; } return 0; } /** * @notice Withdraw reward in tokens to worker node owner */ function withdrawWorkerReward() external { require(msg.sender == workerOwner); uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableWorkerReward(); if (availableReward > balance) { availableReward = balance; } require( availableReward > 0, "There is no available reward to withdraw" ); workerWithdrawnReward = workerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw reward to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); Delegator storage delegator = delegators[msg.sender]; uint256 availableReward = getAvailableDelegatorReward(msg.sender); require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion"); delegator.withdrawnReward = delegator.withdrawnReward.add(_value); totalWithdrawnReward = totalWithdrawnReward.add(_value); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Withdraw reward, deposit and fee to delegator */ function withdrawAll() public { require(isWithdrawAllAllowed(), "Withdraw deposit and reward must be enabled"); uint256 balance = token.balanceOf(address(this)); Delegator storage delegator = delegators[msg.sender]; uint256 availableReward = getAvailableDelegatorReward(msg.sender); uint256 value = availableReward.add(delegator.depositedTokens); require(value <= balance, "Not enough tokens in the contract"); // TODO remove double reading: availableReward and availableWorkerReward use same calls to external contracts uint256 availableWorkerReward = getAvailableWorkerReward(); // potentially could be less then due reward uint256 availableETH = getAvailableDelegatorETH(msg.sender); // prevent losing reward for worker after calculations uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens); if (workerReward > 0) { require(value.add(workerReward) <= balance, "Not enough tokens in the contract"); token.safeTransfer(workerOwner, workerReward); emit TokensWithdrawn(workerOwner, workerReward, 0); } uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens); workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease); totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward); totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens); delegator.withdrawnReward = 0; delegator.depositedTokens = 0; token.safeTransfer(msg.sender, value); emit TokensWithdrawn(msg.sender, value, 0); totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH); delegator.withdrawnETH = 0; if (availableETH > 0) { emit ETHWithdrawn(msg.sender, availableETH); msg.sender.sendValue(availableETH); } } /** * @notice Get available ether for delegator */ function getAvailableDelegatorETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 balance = address(this).balance; // ETH balance + already withdrawn balance = balance.add(totalWithdrawnETH); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { Delegator storage delegator = delegators[msg.sender]; uint256 availableETH = getAvailableDelegatorETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); emit ETHWithdrawn(msg.sender, availableETH); msg.sender.sendValue(availableETH); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public override view returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract holds tokens for vesting. * Also tokens can be used as a stake in the staking escrow contract */ contract PreallocationEscrow is AbstractStakingContract, Ownable { using SafeMath for uint256; using SafeERC20 for NuCypherToken; using Address for address payable; event TokensDeposited(address indexed sender, uint256 value, uint256 duration); event TokensWithdrawn(address indexed owner, uint256 value); event ETHWithdrawn(address indexed owner, uint256 value); StakingEscrow public immutable stakingEscrow; uint256 public lockedValue; uint256 public endLockTimestamp; /** * @param _router Address of the StakingInterfaceRouter contract */ constructor(StakingInterfaceRouter _router) AbstractStakingContract(_router) { stakingEscrow = _router.target().escrow(); } /** * @notice Initial tokens deposit * @param _sender Token sender * @param _value Amount of token to deposit * @param _duration Duration of tokens locking */ function initialDeposit(address _sender, uint256 _value, uint256 _duration) internal { require(lockedValue == 0 && _value > 0); endLockTimestamp = block.timestamp.add(_duration); lockedValue = _value; token.safeTransferFrom(_sender, address(this), _value); emit TokensDeposited(_sender, _value, _duration); } /** * @notice Initial tokens deposit * @param _value Amount of token to deposit * @param _duration Duration of tokens locking */ function initialDeposit(uint256 _value, uint256 _duration) external { initialDeposit(msg.sender, _value, _duration); } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Initial tokens deposit * @param _from Sender * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of seconds during which tokens will be locked */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); initialDeposit(_from, _value, payload); } /** * @notice Get locked tokens value */ function getLockedTokens() public view returns (uint256) { if (endLockTimestamp <= block.timestamp) { return 0; } return lockedValue; } /** * @notice Withdraw available amount of tokens to owner * @param _value Amount of token to withdraw */ function withdrawTokens(uint256 _value) public override onlyOwner { uint256 balance = token.balanceOf(address(this)); require(balance >= _value); // Withdrawal invariant for PreallocationEscrow: // After withdrawing, the sum of all escrowed tokens (either here or in StakingEscrow) must exceed the locked amount require(balance - _value + stakingEscrow.getAllTokens(address(this)) >= getLockedTokens()); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value); } /** * @notice Withdraw available ETH to the owner */ function withdrawETH() public override onlyOwner { uint256 balance = address(this).balance; require(balance != 0); msg.sender.sendValue(balance); emit ETHWithdrawn(msg.sender, balance); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public view override returns (bool) { return msg.sender == owner(); } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.7.0; import "../../zeppelin/ownership/Ownable.sol"; import "../../zeppelin/math/SafeMath.sol"; import "./AbstractStakingContract.sol"; /** * @notice Contract acts as delegate for sub-stakers and owner * @author @vzotova and @roma_k **/ contract WorkLockPoolingContract is InitializableStakingContract, Ownable { using SafeMath for uint256; using Address for address payable; using SafeERC20 for NuCypherToken; event TokensDeposited( address indexed sender, uint256 value, uint256 depositedTokens ); event TokensWithdrawn( address indexed sender, uint256 value, uint256 depositedTokens ); event ETHWithdrawn(address indexed sender, uint256 value); event DepositSet(address indexed sender, bool value); event Bid(address indexed sender, uint256 depositedETH); event Claimed(address indexed sender, uint256 claimedTokens); event Refund(address indexed sender, uint256 refundETH); struct Delegator { uint256 depositedTokens; uint256 withdrawnReward; uint256 withdrawnETH; uint256 depositedETHWorkLock; uint256 refundedETHWorkLock; bool claimedWorkLockTokens; } uint256 public constant BASIS_FRACTION = 100; StakingEscrow public escrow; WorkLock public workLock; address public workerOwner; uint256 public totalDepositedTokens; uint256 public workLockClaimedTokens; uint256 public totalWithdrawnReward; uint256 public totalWithdrawnETH; uint256 public totalWorkLockETHReceived; uint256 public totalWorkLockETHRefunded; uint256 public totalWorkLockETHWithdrawn; uint256 workerFraction; uint256 public workerWithdrawnReward; mapping(address => Delegator) public delegators; bool depositIsEnabled = true; /** * @notice Initialize function for using with OpenZeppelin proxy * @param _workerFraction Share of token reward that worker node owner will get. * Use value up to BASIS_FRACTION, if _workerFraction = BASIS_FRACTION -> means 100% reward as commission * @param _router StakingInterfaceRouter address * @param _workerOwner Owner of worker node, only this address can withdraw worker commission */ function initialize( uint256 _workerFraction, StakingInterfaceRouter _router, address _workerOwner ) public initializer { require(_workerOwner != address(0) && _workerFraction <= BASIS_FRACTION); InitializableStakingContract.initialize(_router); _transferOwnership(msg.sender); escrow = _router.target().escrow(); workLock = _router.target().workLock(); workerFraction = _workerFraction; workerOwner = _workerOwner; } /** * @notice Enabled deposit */ function enableDeposit() external onlyOwner { depositIsEnabled = true; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Disable deposit */ function disableDeposit() external onlyOwner { depositIsEnabled = false; emit DepositSet(msg.sender, depositIsEnabled); } /** * @notice Calculate worker's fraction depending on deposited tokens */ function getWorkerFraction() public view returns (uint256) { return workerFraction; } /** * @notice Transfer tokens as delegator * @param _value Amount of tokens to transfer */ function depositTokens(uint256 _value) external { require(depositIsEnabled, "Deposit must be enabled"); require(_value > 0, "Value must be not empty"); totalDepositedTokens = totalDepositedTokens.add(_value); Delegator storage delegator = delegators[msg.sender]; delegator.depositedTokens = delegator.depositedTokens.add(_value); token.safeTransferFrom(msg.sender, address(this), _value); emit TokensDeposited(msg.sender, _value, delegator.depositedTokens); } /** * @notice Delegator can transfer ETH directly to workLock */ function escrowETH() external payable { Delegator storage delegator = delegators[msg.sender]; delegator.depositedETHWorkLock = delegator.depositedETHWorkLock.add(msg.value); totalWorkLockETHReceived = totalWorkLockETHReceived.add(msg.value); workLock.bid{value: msg.value}(); emit Bid(msg.sender, msg.value); } /** * @dev Hide method from StakingInterface */ function bid(uint256) public payable { revert(); } /** * @dev Hide method from StakingInterface */ function withdrawCompensation() public pure { revert(); } /** * @dev Hide method from StakingInterface */ function cancelBid() public pure { revert(); } /** * @dev Hide method from StakingInterface */ function claim() public pure { revert(); } /** * @notice Claim tokens in WorkLock and save number of claimed tokens */ function claimTokensFromWorkLock() public { workLockClaimedTokens = workLock.claim(); totalDepositedTokens = totalDepositedTokens.add(workLockClaimedTokens); emit Claimed(address(this), workLockClaimedTokens); } /** * @notice Calculate and save number of claimed tokens for specified delegator */ function calculateAndSaveTokensAmount() external { Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); } /** * @notice Calculate and save number of claimed tokens for specified delegator */ function calculateAndSaveTokensAmount(Delegator storage _delegator) internal { if (workLockClaimedTokens == 0 || _delegator.depositedETHWorkLock == 0 || _delegator.claimedWorkLockTokens) { return; } uint256 delegatorTokensShare = _delegator.depositedETHWorkLock.mul(workLockClaimedTokens) .div(totalWorkLockETHReceived); _delegator.depositedTokens = _delegator.depositedTokens.add(delegatorTokensShare); _delegator.claimedWorkLockTokens = true; emit Claimed(msg.sender, delegatorTokensShare); } /** * @notice Get available reward for all delegators and owner */ function getAvailableReward() public view returns (uint256) { uint256 stakedTokens = escrow.getAllTokens(address(this)); uint256 freeTokens = token.balanceOf(address(this)); uint256 reward = stakedTokens.add(freeTokens).sub(totalDepositedTokens); if (reward > freeTokens) { return freeTokens; } return reward; } /** * @notice Get cumulative reward */ function getCumulativeReward() public view returns (uint256) { return getAvailableReward().add(totalWithdrawnReward); } /** * @notice Get available reward in tokens for worker node owner */ function getAvailableWorkerReward() public view returns (uint256) { uint256 reward = getCumulativeReward(); uint256 maxAllowableReward; if (totalDepositedTokens != 0) { uint256 fraction = getWorkerFraction(); maxAllowableReward = reward.mul(fraction).div(BASIS_FRACTION); } else { maxAllowableReward = reward; } if (maxAllowableReward > workerWithdrawnReward) { return maxAllowableReward - workerWithdrawnReward; } return 0; } /** * @notice Get available reward in tokens for delegator */ function getAvailableReward(address _delegator) public view returns (uint256) { if (totalDepositedTokens == 0) { return 0; } uint256 reward = getCumulativeReward(); Delegator storage delegator = delegators[_delegator]; uint256 fraction = getWorkerFraction(); uint256 maxAllowableReward = reward.mul(delegator.depositedTokens).mul(BASIS_FRACTION - fraction).div( totalDepositedTokens.mul(BASIS_FRACTION) ); return maxAllowableReward > delegator.withdrawnReward ? maxAllowableReward - delegator.withdrawnReward : 0; } /** * @notice Withdraw reward in tokens to worker node owner */ function withdrawWorkerReward() external { require(msg.sender == workerOwner); uint256 balance = token.balanceOf(address(this)); uint256 availableReward = getAvailableWorkerReward(); if (availableReward > balance) { availableReward = balance; } require( availableReward > 0, "There is no available reward to withdraw" ); workerWithdrawnReward = workerWithdrawnReward.add(availableReward); totalWithdrawnReward = totalWithdrawnReward.add(availableReward); token.safeTransfer(msg.sender, availableReward); emit TokensWithdrawn(msg.sender, availableReward, 0); } /** * @notice Withdraw reward to delegator * @param _value Amount of tokens to withdraw */ function withdrawTokens(uint256 _value) public override { uint256 balance = token.balanceOf(address(this)); require(_value <= balance, "Not enough tokens in the contract"); Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableReward = getAvailableReward(msg.sender); require( _value <= availableReward, "Requested amount of tokens exceeded allowed portion"); delegator.withdrawnReward = delegator.withdrawnReward.add(_value); totalWithdrawnReward = totalWithdrawnReward.add(_value); token.safeTransfer(msg.sender, _value); emit TokensWithdrawn(msg.sender, _value, delegator.depositedTokens); } /** * @notice Withdraw reward, deposit and fee to delegator */ function withdrawAll() public { uint256 balance = token.balanceOf(address(this)); Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableReward = getAvailableReward(msg.sender); uint256 value = availableReward.add(delegator.depositedTokens); require(value <= balance, "Not enough tokens in the contract"); // TODO remove double reading uint256 availableWorkerReward = getAvailableWorkerReward(); // potentially could be less then due reward uint256 availableETH = getAvailableETH(msg.sender); // prevent losing reward for worker after calculations uint256 workerReward = availableWorkerReward.mul(delegator.depositedTokens).div(totalDepositedTokens); if (workerReward > 0) { require(value.add(workerReward) <= balance, "Not enough tokens in the contract"); token.safeTransfer(workerOwner, workerReward); emit TokensWithdrawn(workerOwner, workerReward, 0); } uint256 withdrawnToDecrease = workerWithdrawnReward.mul(delegator.depositedTokens).div(totalDepositedTokens); workerWithdrawnReward = workerWithdrawnReward.sub(withdrawnToDecrease); totalWithdrawnReward = totalWithdrawnReward.sub(withdrawnToDecrease).sub(delegator.withdrawnReward); totalDepositedTokens = totalDepositedTokens.sub(delegator.depositedTokens); delegator.withdrawnReward = 0; delegator.depositedTokens = 0; token.safeTransfer(msg.sender, value); emit TokensWithdrawn(msg.sender, value, 0); totalWithdrawnETH = totalWithdrawnETH.sub(delegator.withdrawnETH); delegator.withdrawnETH = 0; if (availableETH > 0) { msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } } /** * @notice Get available ether for delegator */ function getAvailableETH(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 balance = address(this).balance; // ETH balance + already withdrawn - (refunded - refundWithdrawn) balance = balance.add(totalWithdrawnETH).add(totalWorkLockETHWithdrawn).sub(totalWorkLockETHRefunded); uint256 maxAllowableETH = balance.mul(delegator.depositedTokens).div(totalDepositedTokens); uint256 availableETH = maxAllowableETH.sub(delegator.withdrawnETH); if (availableETH > balance) { availableETH = balance; } return availableETH; } /** * @notice Withdraw available amount of ETH to delegator */ function withdrawETH() public override { Delegator storage delegator = delegators[msg.sender]; calculateAndSaveTokensAmount(delegator); uint256 availableETH = getAvailableETH(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); delegator.withdrawnETH = delegator.withdrawnETH.add(availableETH); totalWithdrawnETH = totalWithdrawnETH.add(availableETH); msg.sender.sendValue(availableETH); emit ETHWithdrawn(msg.sender, availableETH); } /** * @notice Withdraw compensation and refund from WorkLock and save these numbers */ function refund() public { uint256 balance = address(this).balance; if (workLock.compensation(address(this)) > 0) { workLock.withdrawCompensation(); } workLock.refund(); uint256 refundETH = address(this).balance - balance; totalWorkLockETHRefunded = totalWorkLockETHRefunded.add(refundETH); emit Refund(address(this), refundETH); } /** * @notice Get available refund for delegator */ function getAvailableRefund(address _delegator) public view returns (uint256) { Delegator storage delegator = delegators[_delegator]; uint256 maxAllowableETH = totalWorkLockETHRefunded.mul(delegator.depositedETHWorkLock) .div(totalWorkLockETHReceived); uint256 availableETH = maxAllowableETH.sub(delegator.refundedETHWorkLock); uint256 balance = totalWorkLockETHRefunded.sub(totalWorkLockETHWithdrawn); if (availableETH > balance) { availableETH = balance; } return availableETH; } /* * @notice Withdraw available amount of ETH to delegator */ function withdrawRefund() external { uint256 availableETH = getAvailableRefund(msg.sender); require(availableETH > 0, "There is no available ETH to withdraw"); Delegator storage delegator = delegators[msg.sender]; delegator.refundedETHWorkLock = delegator.refundedETHWorkLock.add(availableETH); totalWorkLockETHWithdrawn = totalWorkLockETHWithdrawn.add(availableETH); msg.sender.sendValue(availableETH); emit Refund(msg.sender, availableETH); } /** * @notice Calling fallback function is allowed only for the owner */ function isFallbackAllowed() public override view returns (bool) { return msg.sender == owner(); } }
* @notice Deserialize to CapsuleFrag/
function toCapsuleFrag(bytes memory _cFragBytes) internal pure returns (CapsuleFrag memory cFrag) { uint256 cFragBytesLength = _cFragBytes.length; require(cFragBytesLength >= FULL_CAPSULE_FRAG_SIZE); uint256 pointer = getPointer(_cFragBytes); pointer = copyPoint(pointer, cFrag.pointE1); pointer = copyPoint(pointer, cFrag.pointV1); cFrag.kFragId = getBytes32(pointer); pointer += BIGNUM_SIZE; pointer = copyPoint(pointer, cFrag.pointPrecursor); cFrag.proof = toCorrectnessProof(pointer, cFragBytesLength - CAPSULE_FRAG_SIZE); }
1,393,027
[ 1, 20423, 358, 385, 6679, 725, 19509, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 358, 24193, 725, 19509, 12, 3890, 3778, 389, 71, 19509, 2160, 13, 203, 3639, 2713, 16618, 1135, 261, 24193, 725, 19509, 3778, 276, 19509, 13, 203, 565, 288, 203, 3639, 2254, 5034, 276, 19509, 2160, 1782, 273, 389, 71, 19509, 2160, 18, 2469, 31, 203, 3639, 2583, 12, 71, 19509, 2160, 1782, 1545, 18153, 67, 17296, 55, 5595, 67, 9981, 1781, 67, 4574, 1769, 203, 203, 3639, 2254, 5034, 4407, 273, 1689, 2480, 24899, 71, 19509, 2160, 1769, 203, 3639, 4407, 273, 1610, 2148, 12, 10437, 16, 276, 19509, 18, 1153, 41, 21, 1769, 203, 3639, 4407, 273, 1610, 2148, 12, 10437, 16, 276, 19509, 18, 1153, 58, 21, 1769, 203, 3639, 276, 19509, 18, 79, 19509, 548, 273, 8425, 1578, 12, 10437, 1769, 203, 3639, 4407, 1011, 18855, 6069, 67, 4574, 31, 203, 3639, 4407, 273, 1610, 2148, 12, 10437, 16, 276, 19509, 18, 1153, 1386, 9216, 1769, 203, 203, 3639, 276, 19509, 18, 24207, 273, 358, 16147, 4496, 20439, 12, 10437, 16, 276, 19509, 2160, 1782, 300, 29720, 55, 5595, 67, 9981, 1781, 67, 4574, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9bC228711706db212ED2BC12d9dC1643cf304EEA/sources/lib/openzeppelin-contracts-upgradeable/contracts/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol
* @dev The storage `slot` is unsupported as a UUID./
error ERC1967UnsupportedProxiableUUID(bytes32 slot);
8,424,111
[ 1, 1986, 2502, 1375, 14194, 68, 353, 13248, 487, 279, 5866, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 555, 4232, 39, 3657, 9599, 8544, 16155, 2214, 5562, 12, 3890, 1578, 4694, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/421613/0x620e20d91C9b0e11ecAE439E7b85138DA2a1003F/sources/contracts/impls/WitnetUpgradableBase.sol
Converts bytes32 into string.
function _toString(bytes32 _bytes32) internal pure returns (string memory) { bytes memory _bytes = new bytes(_toStringLength(_bytes32)); for (uint _i = 0; _i < _bytes.length;) { _bytes[_i] = _bytes32[_i]; unchecked { _i ++; } } return string(_bytes); }
16,825,509
[ 1, 5692, 1731, 1578, 1368, 533, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 10492, 12, 3890, 1578, 389, 3890, 1578, 13, 203, 3639, 2713, 16618, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 1731, 3778, 389, 3890, 273, 394, 1731, 24899, 10492, 1782, 24899, 3890, 1578, 10019, 203, 3639, 364, 261, 11890, 389, 77, 273, 374, 31, 389, 77, 411, 389, 3890, 18, 2469, 30943, 288, 203, 5411, 389, 3890, 63, 67, 77, 65, 273, 389, 3890, 1578, 63, 67, 77, 15533, 203, 5411, 22893, 288, 203, 7734, 389, 77, 965, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 533, 24899, 3890, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x642Aa4faB8A40260E61eAbb169447B39287A0ccE/sources/BlockBot.sol
set as marketing wallet
marketingWallet = address(0xc3a9Fd7dBb4fE87b2e49F8eC21B00C0e362F07fE);
16,179,139
[ 1, 542, 487, 13667, 310, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 13667, 310, 16936, 273, 1758, 12, 20, 6511, 23, 69, 29, 27263, 27, 72, 38, 70, 24, 74, 41, 11035, 70, 22, 73, 7616, 42, 28, 73, 39, 5340, 38, 713, 39, 20, 73, 5718, 22, 42, 8642, 74, 41, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; // Copyright 2018 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import "../lib/SafeMath.sol"; import "../lib/MetaBlock.sol"; import "./BlockStoreInterface.sol"; import "./PollingPlaceInterface.sol"; /** * @title A polling place is where validators cast their votes. * * @notice PollingPlace accepts Casper FFG votes from validators. * PollingPlace also tracks the validator deposits of the Mosaic * validators. The set of validators will change with new meta-blocks * opening on auxiliary. This contract should always know the active * validators and their respective weight. */ contract PollingPlace is PollingPlaceInterface { using SafeMath for uint256; /* Structs */ /** * A validator deposited weight on origin to enter the set of validators. */ struct Validator { /** The address of the validator on auxiliary. */ address auxiliaryAddress; /** * The weight that a validator's vote has. Depends on the stake on * origin and whethere the validator has logged out or been slashed. */ uint256 weight; /** When set to `true`, check `endHeight` to know the last meta-block. */ bool ended; /** * The meta-block height where this validator will enter the set of * validators. Usually, when a validator deposits at meta-block height * h, then meta-block h+1 announces that the validator will join in * meta-block h+2. * The validator will participate starting from the meta-block with * exactly this height. */ uint256 startHeight; /** * The meta-block height where this validator will exit the set of * validators. Usually, when a validator withdraws at meta-block height * h, then meta-block h+1 announces that the validator will leave in * meta-block h+2. * The meta-block with this height will be the first block where the * validator does not participate anymore. */ uint256 endHeight; } /** Vote message */ struct VoteMessage { /** * A unique identifier that identifies what chain this vote is about. * To generate the vote hash coreIdentifier is needed. As the votes are * for both origin and auxiliary chain, the core identifier information * is stored in this struct. */ bytes20 coreIdentifier; /** * The hash of the transition object of the meta-block that would * result from the source block being finalised and proposed to origin. */ bytes32 transitionHash; /** The hash of the source block. */ bytes32 source; /** The hash of the target block. */ bytes32 target; /** The height of the source block. */ uint256 sourceHeight; /** The height of the target block. */ uint256 targetHeight; } /** Vote object */ struct Vote { /** Vote message. */ VoteMessage voteMessage; /** v component of signature */ uint8 v; /** r component of signature */ bytes32 r; /** s component of signature */ bytes32 s; } /* Public Variables */ /** The core identifier of the core that tracks origin. */ bytes20 public originCoreIdentifier; /** The core identifier of the core that tracks this auxiliary chain. */ bytes20 public auxiliaryCoreIdentifier; /** Maps core identifiers to their respective block stores. */ mapping (bytes20 => BlockStoreInterface) public blockStores; /** * Maps core identifiers to their respective chain heights at the currently * open meta-block. Targets of votes must have a height >= the core height. * This way, we only allow votes that target the current "epoch" (open meta- * block). */ mapping (bytes20 => uint256) public coreHeights; /** * Maps a vote hash to the combined weight of all validators that voted * this vote. */ mapping (bytes32 => uint256) public votesWeights; /** * Maps validator addresses to the highest target vote they have voted. All * future votes must target a height greater than the last voted target * height. */ mapping (address => uint256) public validatorTargetHeights; /** * Tracks the current height of the meta-block within this contract. We * track this here to make certain assertions about newly reported * meta-blocks and to know what current height we are voting on. */ uint256 public currentMetaBlockHeight; /** * Maps auxiliary addresses of validators to their details. * * The initial set will be given at construction. Later, validators can * enter and leave the set of validators through the reporting of new * meta-blocks to auxiliary. Validators that left the set of validators are * still kept in the mapping, with `ended` set to `true`. * * One address can never stake more than once. */ mapping (address => Validator) public validators; /** * Maps the meta-block height to the total weight at that height. The total * weight is the sum of all deposits that took place at least two * meta-blocks before and that have not withdrawn at least two meta-blocks * before. */ mapping (uint256 => uint256) public totalWeights; /* Modifiers */ /** * @notice Functions with this modifier can only be called from the address * that is registered as the auxilixary block store. */ modifier onlyAuxiliaryBlockStore() { address auxiliaryBlockStore = address(blockStores[auxiliaryCoreIdentifier]); require( msg.sender == auxiliaryBlockStore, "This method must be called from the registered auxiliary block store." ); _; } /* Constructor */ /** * @notice Initialize the contract with an initial set of validators. * Provide two arrays with the validators' addresses on auxiliary * and their respective weights at the same index. If an auxiliary * address and a weight have the same index in the provided arrays, * they are regarded as belonging to the same validator. * * @param _originBlockStore The block store that stores the origin chain. * @param _auxiliaryBlockStore The block store that stores the auxiliary * chain. * @param _auxiliaryAddresses An array of validators' addresses on * auxiliary. * @param _weights The weights of the validators on origin. Indexed the same * way as the _auxiliaryAddresses. */ constructor ( address _originBlockStore, address _auxiliaryBlockStore, address[] memory _auxiliaryAddresses, uint256[] memory _weights ) public { require( _originBlockStore != address(0), "The address of the origin block store must not be zero." ); require( _auxiliaryBlockStore != address(0), "The address of the auxiliary block store must not be zero." ); require( _auxiliaryAddresses.length > 0, "The count of initial validators must be at least one." ); BlockStoreInterface originBlockStore = BlockStoreInterface(_originBlockStore); BlockStoreInterface auxiliaryBlockStore = BlockStoreInterface(_auxiliaryBlockStore); originCoreIdentifier = originBlockStore.getCoreIdentifier(); auxiliaryCoreIdentifier = auxiliaryBlockStore.getCoreIdentifier(); blockStores[originCoreIdentifier] = originBlockStore; blockStores[auxiliaryCoreIdentifier] = auxiliaryBlockStore; addValidators(_auxiliaryAddresses, _weights); } /* External Functions */ /** * @notice Updates the meta-block height by one and adds the new validators * that should join at this height. * Provide two arrays with the validators' addresses on auxiliary * and their respective weights at the same index. If an auxiliary * address and a weight have the same index in the provided arrays, * they are regarded as belonging to the same validator. * * @param _validators The addresses of the new validators on the auxiliary * chain. * @param _weights The weights of the validators. * @param _originHeight The height of the origin chain where the new * meta-block opens. * @param _auxiliaryHeight The height of the auxiliary checkpoint that is * the last finalised checkpoint within the * previous, closed meta-block. * * @return `true` if the update was successful. */ function updateMetaBlock( address[] calldata _validators, uint256[] calldata _weights, uint256 _originHeight, uint256 _auxiliaryHeight ) external onlyAuxiliaryBlockStore returns (bool success_) { currentMetaBlockHeight = currentMetaBlockHeight.add(1); /* * Before adding the new validators, copy the total weights from the * previous height. The new validators' weights for this height will be * added on top in `addValidators()`. */ totalWeights[currentMetaBlockHeight] = totalWeights[currentMetaBlockHeight.sub(1)]; addValidators(_validators, _weights); updateCoreHeights(_originHeight, _auxiliaryHeight); success_ = true; } /** * @notice Cast a vote from a source to a target. * * @param _coreIdentifier A unique identifier that identifies what chain * this vote is about. * @param _transitionHash The hash of the transition object of the * meta-block that would result from the source * block being finalised and proposed to origin. * @param _source The hash of the source block. * @param _target The hash of the target block. * @param _sourceHeight The height of the source block. * @param _targetHeight The height of the target block. * @param _v V of the signature. * @param _r R of the signature. * @param _s S of the signature. * * @return `true` if the vote was recorded successfully. */ function vote( bytes20 _coreIdentifier, bytes32 _transitionHash, bytes32 _source, bytes32 _target, uint256 _sourceHeight, uint256 _targetHeight, uint8 _v, bytes32 _r, bytes32 _s ) external returns (bool success_) { require( _sourceHeight < _targetHeight, "The source height must be less than the target height." ); require( _targetHeight > coreHeights[_coreIdentifier], "The target height must be within the currently open meta-block." ); BlockStoreInterface blockStore = blockStores[_coreIdentifier]; require( address(blockStore) != address(0), "The provided core identifier must be known to the PollingPlace." ); require( blockStore.isVoteValid(_transitionHash, _source, _target), "The provided vote is not valid according to the block store." ); Vote memory voteObject = getVoteObject( _coreIdentifier, _transitionHash, _source, _target, _sourceHeight, _targetHeight, _v, _r, _s ); bytes32 voteHash = hashVote(voteObject.voteMessage); Validator storage validator = getValidatorFromVote( voteObject, voteHash ); require( validator.auxiliaryAddress != address(0), "A vote by an unknown validator cannot be recorded." ); require( _targetHeight > validatorTargetHeights[validator.auxiliaryAddress], "A validator must vote for increasing target heights." ); storeVote( voteObject, voteHash, validator, blockStore ); success_ = true; } /* Private Functions */ /** * @notice Add validators to the set of validators. Starting from the * current meta-block height. * * @param _auxiliaryAddresses The addresses of the new validators on the * auxiliary chain. * @param _weights The weights of the validators on origin. */ function addValidators( address[] memory _auxiliaryAddresses, uint256[] memory _weights ) private { require( _auxiliaryAddresses.length == _weights.length, "The lengths of the addresses and weights arrays must be identical." ); for (uint256 i; i < _auxiliaryAddresses.length; i++) { address auxiliaryAddress = _auxiliaryAddresses[i]; uint256 weight = _weights[i]; require( weight > 0, "The weight must be greater zero for all validators." ); require( auxiliaryAddress != address(0), "The auxiliary address of a validator must not be zero." ); require( !validatorExists(auxiliaryAddress), "There must not be duplicate addresses in the set of validators." ); validators[auxiliaryAddress] = Validator( auxiliaryAddress, weight, false, currentMetaBlockHeight, 0 ); totalWeights[currentMetaBlockHeight] = totalWeights[currentMetaBlockHeight].add( weight ); } } /** * @notice Verify that the new heights are legal and then store them. * * @param _originHeight The height of the origin chain where the new meta- * block opens. * @param _auxiliaryHeight The height of the auxiliary chain where the new * meta-block opens. */ function updateCoreHeights( uint256 _originHeight, uint256 _auxiliaryHeight ) private { require( _originHeight > coreHeights[originCoreIdentifier], "The height of origin must increase with a meta-block opening." ); require( _auxiliaryHeight > coreHeights[auxiliaryCoreIdentifier], "The height of auxiliary must increase with a meta-block opening." ); coreHeights[originCoreIdentifier] = _originHeight; coreHeights[auxiliaryCoreIdentifier] = _auxiliaryHeight; } /** * @notice Stores a vote and checks subsuquently if the target checkpoint * is now justified. If so, it calls justify on the given block * store. * * @dev All requirement checks must have been made before calling this * method. As this function is private, we can trust that vote hash * will be correct. In case if this function changes to external or * public then we should calculate the vote hash from the vote object in this * function. * * * @param _voteObject Vote object. * @param _voteHash Hash of the VoteMessage. * @param _validator The validator that signed the vote. * @param _blockStore The block store that this vote is about. */ function storeVote( Vote memory _voteObject, bytes32 _voteHash, Validator storage _validator, BlockStoreInterface _blockStore ) private { VoteMessage memory voteMessage = _voteObject.voteMessage; validatorTargetHeights[_validator.auxiliaryAddress] = voteMessage.targetHeight; votesWeights[_voteHash] = votesWeights[_voteHash].add( validatorWeight(_validator, currentMetaBlockHeight) ); /* * Because the target must be within the currently open meta-block, the * required weight must also be from the currently open meta-block. */ uint256 required = requiredWeight(currentMetaBlockHeight); if (votesWeights[_voteHash] >= required) { _blockStore.justify(voteMessage.source, voteMessage.target); } } /** * @notice Returns true if the validator is already stored. * * @param _auxiliaryAddress The address of the validator on the auxiliary * system. * * @return `true` if the address has already been registered. */ function validatorExists( address _auxiliaryAddress ) private view returns (bool) { return validators[_auxiliaryAddress].auxiliaryAddress != address(0); } /** * @notice Uses the signature of a vote to recover the public address of * the signer. * * @dev As this function is private, we can trust that vote hash will be * correct. In case if this function changes to external or public * then we should calculate the vote hash from the vote object in this * function. * * @param _voteObject Vote object. * @param _voteHash Hash of vote message. * * @return The `Validator` that signed the given message with the given * signature. */ function getValidatorFromVote(Vote memory _voteObject, bytes32 _voteHash) private view returns (Validator storage validator_) { address signer = ecrecover( _voteHash, _voteObject.v, _voteObject.r, _voteObject.s ); validator_ = validators[signer]; } /** * @notice The weight that a validator has at a given height. * * @dev The weight can not change except to zero due to logging out or * slashing. * * @param _validator The validator that the weight is requested for. * @param _height The height at which the validator weight is requested. * * @return The weight of the given validator at the given height. */ function validatorWeight( Validator storage _validator, uint256 _height ) private view returns (uint256 weight_) { if (_validator.startHeight > _height) { weight_ = 0; } else if (_validator.ended && _validator.endHeight <= _height) { weight_ = 0; } else { weight_ = _validator.weight; } } /** * @notice The minimum weight that is required for a vote to achieve a * >=2/3 majority. * * @param _metaBlockHeight The height of the meta-block for which the * required weight must be known. * * @return requiredWeight_ The minimum weight of votes that achieve * a >=2/3 majority. */ function requiredWeight( uint256 _metaBlockHeight ) private view returns (uint256 requiredWeight_) { requiredWeight_ = MetaBlock.requiredWeightForSuperMajority( totalWeights[_metaBlockHeight] ); } /** * @notice Creates the hash of o vote object. This is the same hash that * the validator has signed. * * @param _voteMessage Vote message object. * * @return The hash of the given vote. */ function hashVote(VoteMessage memory _voteMessage) private pure returns (bytes32 hashed_) { hashed_ = MetaBlock.hashVote( _voteMessage.coreIdentifier, _voteMessage.transitionHash, _voteMessage.source, _voteMessage.target, _voteMessage.sourceHeight, _voteMessage.targetHeight ); // As per https://github.com/ethereum/go-ethereum/pull/2940 bytes memory prefix = "\x19Ethereum Signed Message:\n32"; hashed_ = keccak256( abi.encodePacked( prefix, hashed_ ) ); } /** * @notice Creates a vote object * * @param _coreIdentifier A unique identifier that identifies what chain * this vote is about. * @param _transitionHash The hash of the transition object of the * meta-block that would result from the source * block being finalised and proposed to origin. * @param _source The hash of the source block. * @param _target The hash of the target block. * @param _sourceHeight The height of the source block. * @param _targetHeight The height of the target block. * @param _v V of the signature. * @param _r R of the signature. * @param _s S of the signature. * * @return vote object */ function getVoteObject( bytes20 _coreIdentifier, bytes32 _transitionHash, bytes32 _source, bytes32 _target, uint256 _sourceHeight, uint256 _targetHeight, uint8 _v, bytes32 _r, bytes32 _s ) private pure returns (Vote memory voteObject_) { VoteMessage memory voteMessage = VoteMessage( _coreIdentifier, _transitionHash, _source, _target, _sourceHeight, _targetHeight ); voteObject_ = Vote( voteMessage, _v, _r, _s ); } }
* Maps validator addresses to the highest target vote they have voted. All future votes must target a height greater than the last voted target height./
mapping (address => uint256) public validatorTargetHeights;
5,394,781
[ 1, 8903, 4213, 6138, 358, 326, 9742, 1018, 12501, 2898, 1240, 331, 16474, 18, 4826, 3563, 19588, 1297, 1018, 279, 2072, 6802, 2353, 326, 1142, 331, 16474, 1018, 2072, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 4213, 2326, 2686, 87, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Snapshot.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/Uniswap.sol"; import "../interfaces/IPinkAntiBot.sol"; contract YachtMasterToken is ERC20, ERC20Snapshot, Ownable { //Integration with PinkSaleAntibot interface IPinkAntiBot public pinkAntiBot; bool public antiBotEnabled; // Mapping to exclude some contracts from fees. Transfers are excluded from fees if address in this mapping is recipient or sender. mapping (address => bool) public excludedFromFees; // Yacht funds wallet address that will be used for DAO treasury and buy Yachts. address payable public yachtMasterWalletAddress; // Marketing wallet address used for funding marketing. address payable public marketingWalletAddress; // Developer wallet address used for funding the team. address payable public developerWalletAddress; // Liquidity wallet address used to hold the 35% of YMT tokens for the liquidity pool. // After these coins are moved to the DEX, this address will no longer be used. address public liquidityWalletAddress; // Address of the wallet that will keep YMT tokens for burn. address payable public tobeburntWalletAddress; // Address of the contract responsible for the air dropping. address public airDropWalletAddress; // The PancakeSwap router address for swapping YMT tokens for WBNB. address public uniswapRouterAddress; // The initial block timestamp of the token contract. uint256 public initialTimeStamp; // Yacht transaction fee - deployed at 3%. uint256 public yachtTransactionFeePercent = 3; // Developer team transaction fee - deployed at 1%. uint256 public developerFeePercent = 1; // Marketing transaction fee - deployed at 1%. uint256 public marketingFeePercent = 1; // Marketing transaction fee - deployed at 1%. uint256 public burnFeePercent = 1; // PancakeSwap router interface. IUniswapV2Router02 private uniswapRouter; // Address of the WBNB to YMT token pair on PancakeSwap. address public uniswapPair; // Initial token distribution: // 20% - Air drop contract (will be locked and vested periodically outside of contract) // 35% - Liquidity pool (1 year lockup period after vesting presale - outside of contract) // 30% - Burn // 10% - Developer coins (6 month lockup period) // 5% - Marketing constructor( uint256 initialSupply, address payable _yachtMasterWalletAddress, address payable _marketingWalletAddress, address payable _developerWalletAddress, address _liquidityWalletAddress, address payable _tobeburntWalletAddress, address _airDropWalletAddress, address _uniswapRouterAddress, address pinkAntiBot_) ERC20("YachtMasterToken", "YMT") { initialTimeStamp = block.timestamp; yachtMasterWalletAddress = _yachtMasterWalletAddress; marketingWalletAddress = _marketingWalletAddress; developerWalletAddress = _developerWalletAddress; liquidityWalletAddress = _liquidityWalletAddress; tobeburntWalletAddress = _tobeburntWalletAddress; airDropWalletAddress = _airDropWalletAddress; uniswapRouterAddress = _uniswapRouterAddress; // Create an instance of the PinkAntiBot variable from the provided address pinkAntiBot = IPinkAntiBot(pinkAntiBot_); // Register the deployer to be the token owner with PinkAntiBot. You can // later change the token owner in the PinkAntiBot contract pinkAntiBot.setTokenOwner(msg.sender); antiBotEnabled = true; excludedFromFees[yachtMasterWalletAddress] = true; excludedFromFees[marketingWalletAddress] = true; excludedFromFees[developerWalletAddress] = true; excludedFromFees[liquidityWalletAddress] = true; excludedFromFees[tobeburntWalletAddress] = true; excludedFromFees[airDropWalletAddress] = true; _mint(marketingWalletAddress, (initialSupply) * 5 / 100); _mint(developerWalletAddress, (initialSupply) * 10 / 100); _mint(liquidityWalletAddress, (initialSupply) * 35 / 100); _mint(tobeburntWalletAddress, (initialSupply) * 30 / 100); _mint(airDropWalletAddress, (initialSupply) * 20 / 100); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(uniswapRouterAddress); uniswapRouter = _uniswapV2Router; _approve(address(this), address(uniswapRouter), initialSupply); uniswapPair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); IERC20(uniswapPair).approve(address(uniswapRouter), type(uint256).max); } /** * Returns the contract address * Return contract address */ function getContractAddress() public view returns (address){ return address(this); } /** * @dev Adds a user to be excluded from fees. * @param user address of the user to be excluded from fees. */ function excludeUserFromFees(address user) public onlyOwner { excludedFromFees[user] = true; } /** * @dev Gets the current timestamp, used for testing + verification * @return the the timestamp of the current block */ function getCurrentTimestamp() public view returns (uint256) { return block.timestamp; } /** * @dev Removes a user from the fee exclusion. * @param user address of the user than will now have to pay transaction fees. */ function includeUsersInFees(address user) public onlyOwner { excludedFromFees[user] = false; } //Function to burn tokens function burn(uint256 amount) public onlyOwner { _burn(msg.sender, amount); } // Use this function to control whether to use PinkAntiBot or not instead // of managing this in the PinkAntiBot contract function setEnableAntiBot(bool _enable) external onlyOwner { antiBotEnabled = _enable; } // Internal Transfer function override to collect taxes only on Swap. function _transfer(address sender, address recipient, uint256 amount) internal virtual override { // Check in exchanges between wallets for 2% of total supply if (sender != uniswapPair && recipient != uniswapPair && !excludedFromFees[sender] && !excludedFromFees[recipient]) { require((balanceOf(recipient) + amount) < (totalSupply() / 76), "You can't have more than 2% of the total supply."); } //when to collect taxes if((sender == uniswapPair || recipient == uniswapPair) && !excludedFromFees[sender] && !excludedFromFees[recipient]) { //Investor cannot have more than 2% of total supply if(sender == uniswapPair && !excludedFromFees[sender] && !excludedFromFees[recipient]) { require((balanceOf(recipient) + amount) < (totalSupply() / 76), "You can't have more than 2% of the total supply."); } // Yacht transaction fee. uint256 yachtFee = (amount * yachtTransactionFeePercent) / 100; // Marketing team transaction fee. uint256 marketingFee = (amount * marketingFeePercent) / 100; // Developer team transaction fee. uint256 developerFee = (amount * developerFeePercent) / 100; // Burn fee uint256 burnFee = (amount * burnFeePercent) / 100; // The total fee to send to the contract address. uint256 totalFee = yachtFee + marketingFee + developerFee + burnFee; // Sends the transaction fees to the contract address super._transfer(sender, address(this), totalFee); // Prepares amount afterfees amount -= totalFee; } super._transfer(sender, recipient, amount); } /** * @dev Swaps YMT tokens from transaction fees to BNB. * @param amount the amount of YMT tokens to swap */ function swapYMTForBNB(uint256 amount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapRouter.WETH(); _approve(address(this), address(uniswapRouter), amount); uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), block.timestamp ); } /** * @dev Sends BNB to transaction fee wallets after YMT swaps. * @param amount the amount to be transfered */ function sendFeesToWallets(uint256 amount) private { uint256 totalFee = yachtTransactionFeePercent + marketingFeePercent + developerFeePercent + burnFeePercent; yachtMasterWalletAddress.transfer((amount * yachtTransactionFeePercent) / totalFee); marketingWalletAddress.transfer((amount * marketingFeePercent) / totalFee); developerWalletAddress.transfer((amount * developerFeePercent) / totalFee); tobeburntWalletAddress.transfer((amount * burnFeePercent) / totalFee); } /** * @dev Swaps YMT to BNB. */ function swapFeesManually() public onlyOwner { uint256 contractYMTBalance = balanceOf(address(this)); if (contractYMTBalance > 0) { swapYMTForBNB(contractYMTBalance); } } /** * @dev Sends BNB to transaction */ function disperseFeesManually() public onlyOwner { uint256 contractBNBBalance = address(this).balance; sendFeesToWallets(contractBNBBalance); } receive() external payable {} function snapshot() public onlyOwner { _snapshot(); } // The following functions are overrides required by Solidity. // Enabling antibot from Pinksale function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Snapshot) { // Only use PinkAntiBot if this state is true if (antiBotEnabled) { pinkAntiBot.onPreTransferCheck(from, to, amount); } super._beforeTokenTransfer(from, to, amount); } }
* Returns the contract address Return contract address/
function getContractAddress() public view returns (address){ return address(this); }
12,722,684
[ 1, 1356, 326, 6835, 1758, 2000, 6835, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 8924, 1887, 1435, 1071, 1476, 1135, 261, 2867, 15329, 203, 3639, 327, 1758, 12, 2211, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-12-23 */ // Sources flattened with hardhat v2.6.8 https://hardhat.org // SPDX-License-Identifier: MIT // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/proxy/[email protected] // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract 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; } // File @openzeppelin/contracts-upgradeable/access/[email protected] pragma solidity ^0.7.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 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 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; } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts-upgradeable/math/[email protected] pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] pragma solidity ^0.7.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.7.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); } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File contracts/interfaces/IDistributor.sol pragma solidity ^0.7.6; interface IDistributor { /// @dev distribute ALD reward to Aladdin Staking contract. function distribute() external; } // File contracts/interfaces/IStaking.sol pragma solidity ^0.7.6; interface IStaking { function stake(uint256 _amount) external; function stakeFor(address _recipient, uint256 _amount) external; function unstake(address _recipient, uint256 _amount) external; function unstakeAll(address _recipient) external; function bondFor(address _recipient, uint256 _amount) external; function rewardBond(address _vault, uint256 _amount) external; function rebase() external; function redeem(address _recipient, bool _withdraw) external; } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/interfaces/IXALD.sol pragma solidity ^0.7.6; interface IXALD is IERC20 { function stake(address _recipient, uint256 _aldAmount) external; function unstake(address _account, uint256 _xALDAmount) external; function rebase(uint256 epoch, uint256 profit) external; function getSharesByALD(uint256 _aldAmount) external view returns (uint256); function getALDByShares(uint256 _sharesAmount) external view returns (uint256); } // File contracts/interfaces/IWXALD.sol pragma solidity ^0.7.6; interface IWXALD { function wrap(uint256 _xALDAmount) external returns (uint256); function unwrap(uint256 _wxALDAmount) external returns (uint256); function wrappedXALDToXALD(uint256 _wxALDAmount) external view returns (uint256); } // File contracts/interfaces/IRewardBondDepositor.sol pragma solidity ^0.7.6; interface IRewardBondDepositor { function currentEpoch() external view returns ( uint64 epochNumber, uint64 startBlock, uint64 nextBlock, uint64 epochLength ); function rewardShares(uint256 _epoch, address _vault) external view returns (uint256); function getVaultsFromAccount(address _user) external view returns (address[] memory); function getAccountRewardShareSince( uint256 _epoch, address _user, address _vault ) external view returns (uint256[] memory); function bond(address _vault) external; function rebase() external; function notifyRewards(address _user, uint256[] memory _amounts) external; } // File contracts/stake/Staking.sol pragma solidity ^0.7.6; contract Staking is OwnableUpgradeable, IStaking { using SafeMath for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; event Bond(address indexed recipient, uint256 aldAmount, uint256 wxALDAmount); event RewardBond(address indexed vault, uint256 aldAmount, uint256 wxALDAmount); event Stake(address indexed caller, address indexed recipient, uint256 amount); event Unstake(address indexed caller, address indexed recipient, uint256 amount); event Redeem(address indexed caller, address indexed recipient, uint256 amount); struct UserLockedBalance { // The amount of wxALD locked. uint192 amount; // The block number when the lock starts. uint32 lockedBlock; // The block number when the lock ends. uint32 unlockBlock; } struct RewardBondBalance { // The block number when the lock starts. uint32 lockedBlock; // The block number when the lock ends. uint32 unlockBlock; // Mapping from vault address to the amount of wxALD locked. mapping(address => uint256) amounts; } struct Checkpoint { uint128 epochNumber; uint128 blockNumber; } // The address of governor. address public governor; // The address of ALD token. address public ALD; // The address of xALD token. address public xALD; // The address of wxALD token. address public wxALD; // The address of direct bond contract. address public directBondDepositor; // The address of vault reward bond contract. address public rewardBondDepositor; // The address of distributor. address public distributor; // Whether staking is paused. bool public paused; // Whether to enable whitelist mode. bool public enableWhitelist; mapping(address => bool) public isWhitelist; // Whether an address is in black list mapping(address => bool) public blacklist; // The default locking period in epoch. uint256 public defaultLockingPeriod; // The bond locking period in epoch. uint256 public bondLockingPeriod; // Mapping from user address to locking period in epoch. mapping(address => uint256) public lockingPeriod; // Mapping from user address to staked ald balances. mapping(address => UserLockedBalance[]) private userStakedLocks; // Mapping from user address to asset bond ald balances. mapping(address => UserLockedBalance[]) private userDirectBondLocks; // Mapping from user address to reward bond ald balances. mapping(address => UserLockedBalance[]) private userRewardBondLocks; // The list of reward bond ald locks. // 65536 epoch is about 170 year, assuming 1 epoch = 1 day. RewardBondBalance[65536] public rewardBondLocks; // Mapping from user address to lastest interacted epoch/block number. mapping(address => Checkpoint) private checkpoint; modifier notPaused() { require(!paused, "Staking: paused"); _; } modifier onlyGovernor() { require(msg.sender == governor || msg.sender == owner(), "Treasury: only governor"); _; } /// @param _ALD The address of ALD token. /// @param _xALD The address of xALD token. /// @param _wxALD The address of wxALD token. /// @param _rewardBondDepositor The address of reward bond contract. function initialize( address _ALD, address _xALD, address _wxALD, address _rewardBondDepositor ) external initializer { OwnableUpgradeable.__Ownable_init(); require(_ALD != address(0), "Treasury: zero address"); require(_xALD != address(0), "Treasury: zero address"); require(_wxALD != address(0), "Treasury: zero address"); require(_rewardBondDepositor != address(0), "Treasury: zero address"); ALD = _ALD; xALD = _xALD; wxALD = _wxALD; IERC20Upgradeable(_xALD).safeApprove(_wxALD, uint256(-1)); paused = true; enableWhitelist = true; defaultLockingPeriod = 90; bondLockingPeriod = 5; rewardBondDepositor = _rewardBondDepositor; } /********************************** View Functions **********************************/ /// @dev return the full vested block (staking and bond) for given user /// @param _user The address of user; function fullyVestedBlock(address _user) external view returns (uint256, uint256) { uint256 stakeVestedBlock; { UserLockedBalance[] storage _locks = userStakedLocks[_user]; for (uint256 i = 0; i < _locks.length; i++) { UserLockedBalance storage _lock = _locks[i]; if (_lock.amount > 0) { stakeVestedBlock = Math.max(stakeVestedBlock, _lock.unlockBlock); } } } uint256 bondVestedBlock; { UserLockedBalance[] storage _locks = userDirectBondLocks[_user]; for (uint256 i = 0; i < _locks.length; i++) { UserLockedBalance storage _lock = _locks[i]; if (_lock.amount > 0) { bondVestedBlock = Math.max(bondVestedBlock, _lock.unlockBlock); } } } return (stakeVestedBlock, bondVestedBlock); } /// @dev return the pending xALD amount including locked and unlocked. /// @param _user The address of user. function pendingXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 _lastEpoch = checkpoint[_user].epochNumber; uint256 pendingAmount = _getPendingWithList(userStakedLocks[_user], _lastBlock); pendingAmount = pendingAmount.add(_getPendingWithList(userDirectBondLocks[_user], _lastBlock)); pendingAmount = pendingAmount.add(_getPendingWithList(userRewardBondLocks[_user], _lastBlock)); pendingAmount = pendingAmount.add(_getPendingRewardBond(_user, _lastEpoch, _lastBlock)); return IWXALD(wxALD).wrappedXALDToXALD(pendingAmount); } /// @dev return the pending xALD amount from user staking, including locked and unlocked. /// @param _user The address of user. function pendingStakedXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 pendingAmount = _getPendingWithList(userStakedLocks[_user], _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(pendingAmount); } /// @dev return the pending xALD amount from user bond, including locked and unlocked. /// @param _user The address of user. function pendingBondXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 pendingAmount = _getPendingWithList(userDirectBondLocks[_user], _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(pendingAmount); } /// @dev return the pending xALD amount from user vault reward, including locked and unlocked. /// @param _user The address of user. /// @param _vault The address of vault. function pendingXALDByVault(address _user, address _vault) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 _startEpoch = _findPossibleStartEpoch(_user, _lastBlock); uint256 pendingAmount = _getPendingRewardBondByVault(_user, _vault, _startEpoch, _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(pendingAmount); } /// @dev return the unlocked xALD amount. /// @param _user The address of user. function unlockedXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 _lastEpoch = checkpoint[_user].epochNumber; uint256 unlockedAmount = _getRedeemableWithList(userStakedLocks[_user], _lastBlock); unlockedAmount = unlockedAmount.add(_getRedeemableWithList(userDirectBondLocks[_user], _lastBlock)); unlockedAmount = unlockedAmount.add(_getRedeemableWithList(userRewardBondLocks[_user], _lastBlock)); unlockedAmount = unlockedAmount.add(_getRedeemableRewardBond(_user, _lastEpoch, _lastBlock)); return IWXALD(wxALD).wrappedXALDToXALD(unlockedAmount); } /// @dev return the unlocked xALD amount from user staking. /// @param _user The address of user. function unlockedStakedXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 unlockedAmount = _getRedeemableWithList(userStakedLocks[_user], _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(unlockedAmount); } /// @dev return the unlocked xALD amount from user bond. /// @param _user The address of user. function unlockedBondXALD(address _user) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 unlockedAmount = _getRedeemableWithList(userDirectBondLocks[_user], _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(unlockedAmount); } /// @dev return the unlocked xALD amount from user vault reward. /// @param _user The address of user. /// @param _vault The address of vault. function unlockedXALDByVault(address _user, address _vault) external view returns (uint256) { // be carefull when no checkpoint for _user uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 _startEpoch = _findPossibleStartEpoch(_user, _lastBlock); uint256 pendingAmount = _getRedeemableRewardBondByVault(_user, _vault, _startEpoch, _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(pendingAmount); } /********************************** Mutated Functions **********************************/ /// @dev stake all ALD for xALD. function stakeAll() external notPaused { if (enableWhitelist) { require(isWhitelist[msg.sender], "Staking: not whitelist"); } uint256 _amount = IERC20Upgradeable(ALD).balanceOf(msg.sender); _amount = _transferAndWrap(msg.sender, _amount); _stakeFor(msg.sender, _amount); } /// @dev stake ALD for xALD. /// @param _amount The amount of ALD to stake. function stake(uint256 _amount) external override notPaused { if (enableWhitelist) { require(isWhitelist[msg.sender], "Staking: not whitelist"); } _amount = _transferAndWrap(msg.sender, _amount); _stakeFor(msg.sender, _amount); } /// @dev stake ALD for others. /// @param _recipient The address to receipt xALD. /// @param _amount The amount of ALD to stake. function stakeFor(address _recipient, uint256 _amount) external override notPaused { if (enableWhitelist) { require(isWhitelist[msg.sender], "Staking: not whitelist"); } _amount = _transferAndWrap(msg.sender, _amount); _stakeFor(_recipient, _amount); } /// @dev unstake xALD to ALD. /// @param _recipient The address to receipt ALD. /// @param _amount The amount of xALD to unstake. function unstake(address _recipient, uint256 _amount) external override notPaused { _unstake(_recipient, _amount); } /// @dev unstake all xALD to ALD. /// @param _recipient The address to receipt ALD. function unstakeAll(address _recipient) external override notPaused { uint256 _amount = IXALD(xALD).balanceOf(msg.sender); _unstake(_recipient, _amount); } /// @dev bond ALD from direct asset. only called by DirectBondDepositor contract. /// @notice all bond on the same epoch are grouped at the expected start block of next epoch. /// @param _recipient The address to receipt xALD. /// @param _amount The amount of ALD to stake. function bondFor(address _recipient, uint256 _amount) external override notPaused { require(directBondDepositor == msg.sender, "Staking: not approved"); uint256 _wxALDAmount = _transferAndWrap(msg.sender, _amount); // bond lock logic (, , uint256 nextBlock, uint256 epochLength) = IRewardBondDepositor(rewardBondDepositor).currentEpoch(); UserLockedBalance[] storage _locks = userDirectBondLocks[_recipient]; uint256 length = _locks.length; if (length == 0 || _locks[length - 1].lockedBlock != nextBlock) { _locks.push( UserLockedBalance({ amount: uint192(_wxALDAmount), lockedBlock: uint32(nextBlock), unlockBlock: uint32(nextBlock + epochLength * bondLockingPeriod) }) ); } else { _locks[length - 1].amount = uint192(uint256(_locks[length - 1].amount).add(_wxALDAmount)); } emit Bond(_recipient, _amount, _wxALDAmount); } /// @dev bond ALD from vault reward. only called by RewardBondDepositor contract. /// @notice all bond on the same epoch are grouped at the expected start block of next epoch. /// @param _vault The address of vault. /// @param _amount The amount of ALD to stake. function rewardBond(address _vault, uint256 _amount) external override notPaused { require(rewardBondDepositor == msg.sender, "Staking: not approved"); uint256 _wxALDAmount = _transferAndWrap(msg.sender, _amount); (uint256 epochNumber, , uint256 nextBlock, uint256 epochLength) = IRewardBondDepositor(rewardBondDepositor) .currentEpoch(); RewardBondBalance storage _lock = rewardBondLocks[epochNumber]; if (_lock.lockedBlock == 0) { // first bond in current epoch _lock.lockedBlock = uint32(nextBlock); _lock.unlockBlock = uint32(nextBlock + epochLength * bondLockingPeriod); } _lock.amounts[_vault] = _lock.amounts[_vault].add(_wxALDAmount); emit RewardBond(_vault, _amount, _wxALDAmount); } /// @dev mint ALD reward for stakers. /// @notice assume it is called in `rebase()` from contract `rewardBondDepositor`. function rebase() external override notPaused { require(rewardBondDepositor == msg.sender, "Staking: not approved"); if (distributor != address(0)) { uint256 _pool = IERC20Upgradeable(ALD).balanceOf(address(this)); IDistributor(distributor).distribute(); uint256 _distributed = IERC20Upgradeable(ALD).balanceOf(address(this)).sub(_pool); (uint256 epochNumber, , , ) = IRewardBondDepositor(rewardBondDepositor).currentEpoch(); IXALD(xALD).rebase(epochNumber, _distributed); } } /// @dev redeem unlocked xALD from contract. /// @param _recipient The address to receive xALD/ALD. /// @param __unstake Whether to unstake xALD to ALD. function redeem(address _recipient, bool __unstake) external override notPaused { require(!blacklist[msg.sender], "Staking: blacklist"); // be carefull when no checkpoint for msg.sender uint256 _lastBlock = checkpoint[msg.sender].blockNumber; uint256 _lastEpoch = checkpoint[msg.sender].epochNumber; if (_lastBlock == block.number) { return; } uint256 unlockedAmount = _redeemWithList(userStakedLocks[msg.sender], _lastBlock); unlockedAmount = unlockedAmount.add(_redeemWithList(userDirectBondLocks[msg.sender], _lastBlock)); unlockedAmount = unlockedAmount.add(_redeemWithList(userRewardBondLocks[msg.sender], _lastBlock)); unlockedAmount = unlockedAmount.add(_redeemRewardBondLocks(msg.sender, _lastEpoch, _lastBlock)); // find the unlocked xALD amount unlockedAmount = IWXALD(wxALD).unwrap(unlockedAmount); emit Redeem(msg.sender, _recipient, unlockedAmount); if (__unstake) { IXALD(xALD).unstake(address(this), unlockedAmount); IERC20Upgradeable(ALD).safeTransfer(_recipient, unlockedAmount); emit Unstake(msg.sender, _recipient, unlockedAmount); } else { IERC20Upgradeable(xALD).safeTransfer(_recipient, unlockedAmount); } (uint256 epochNumber, , , ) = IRewardBondDepositor(rewardBondDepositor).currentEpoch(); checkpoint[msg.sender] = Checkpoint({ blockNumber: uint128(block.number), epochNumber: uint128(epochNumber) }); } /********************************** Restricted Functions **********************************/ function updateGovernor(address _governor) external onlyOwner { governor = _governor; } function updateDistributor(address _distributor) external onlyOwner { distributor = _distributor; } function updatePaused(bool _paused) external onlyGovernor { paused = _paused; } function updateEnableWhitelist(bool _enableWhitelist) external onlyOwner { enableWhitelist = _enableWhitelist; } function updateWhitelist(address[] memory _users, bool status) external onlyOwner { for (uint256 i = 0; i < _users.length; i++) { isWhitelist[_users[i]] = status; } } function updateBlacklist(address[] memory _users, bool status) external onlyOwner { for (uint256 i = 0; i < _users.length; i++) { blacklist[_users[i]] = status; } } function updateBongLockingPeriod(uint256 _bondLockingPeriod) external onlyOwner { bondLockingPeriod = _bondLockingPeriod; } function updateDefaultLockingPeriod(uint256 _defaultLockingPeriod) external onlyOwner { defaultLockingPeriod = _defaultLockingPeriod; } function updateLockingPeriod(address[] memory _users, uint256[] memory _periods) external onlyOwner { require(_users.length == _periods.length, "Staking: length mismatch"); for (uint256 i = 0; i < _users.length; i++) { lockingPeriod[_users[i]] = _periods[i]; } } function updateDirectBondDepositor(address _directBondDepositor) external onlyOwner { require(_directBondDepositor != address(0), "Treasury: zero address"); directBondDepositor = _directBondDepositor; } /********************************** Internal Functions **********************************/ /// @dev all stakes on the same epoch are grouped at the expected start block of next epoch. /// @param _recipient The address of recipient who receives xALD. /// @param _amount The amount of wxALD for the recipient. function _stakeFor(address _recipient, uint256 _amount) internal { (, , uint256 nextBlock, uint256 epochLength) = IRewardBondDepositor(rewardBondDepositor).currentEpoch(); UserLockedBalance[] storage _locks = userStakedLocks[_recipient]; uint256 length = _locks.length; // stake lock logic if (length == 0 || _locks[length - 1].lockedBlock != nextBlock) { uint256 _period = _lockingPeriod(_recipient); _locks.push( UserLockedBalance({ amount: uint192(_amount), lockedBlock: uint32(nextBlock), unlockBlock: uint32(nextBlock + epochLength * _period) }) ); } else { _locks[length - 1].amount = uint192(uint256(_locks[length - 1].amount).add(_amount)); } emit Stake(msg.sender, _recipient, _amount); } function _unstake(address _recipient, uint256 _amount) internal { IXALD(xALD).unstake(msg.sender, _amount); IERC20Upgradeable(ALD).safeTransfer(_recipient, _amount); emit Unstake(msg.sender, _recipient, _amount); } function _lockingPeriod(address _user) internal view returns (uint256) { uint256 _period = lockingPeriod[_user]; if (_period == 0) return defaultLockingPeriod; else return _period; } function _transferAndWrap(address _sender, uint256 _amount) internal returns (uint256) { IERC20Upgradeable(ALD).safeTransferFrom(_sender, address(this), _amount); IXALD(xALD).stake(address(this), _amount); return IWXALD(wxALD).wrap(_amount); } function _redeemRewardBondLocks( address _user, uint256 _lastEpoch, uint256 _lastBlock ) internal returns (uint256) { uint256 unlockedAmount; address[] memory _vaults = IRewardBondDepositor(rewardBondDepositor).getVaultsFromAccount(_user); for (uint256 i = 0; i < _vaults.length; i++) { unlockedAmount = unlockedAmount.add(_redeemRewardBondLocksByVault(_user, _vaults[i], _lastEpoch, _lastBlock)); } return unlockedAmount; } function _redeemRewardBondLocksByVault( address _user, address _vault, uint256 _startEpoch, uint256 _lastBlock ) internal returns (uint256) { IRewardBondDepositor _depositor = IRewardBondDepositor(rewardBondDepositor); // gas saving UserLockedBalance[] storage _locks = userRewardBondLocks[_user]; uint256 unlockedAmount; uint256[] memory _shares = _depositor.getAccountRewardShareSince(_startEpoch, _user, _vault); for (uint256 i = 0; i < _shares.length; i++) { if (_shares[i] == 0) continue; uint256 _epoch = _startEpoch + i; uint256 _amount = rewardBondLocks[_epoch].amounts[_vault]; { uint256 _totalShare = _depositor.rewardShares(_epoch, _vault); _amount = _amount.mul(_shares[i]).div(_totalShare); } uint256 _lockedBlock = rewardBondLocks[_epoch].lockedBlock; uint256 _unlockBlock = rewardBondLocks[_epoch].unlockBlock; // [_lockedBlock, _unlockBlock), [_lastBlock + 1, block.number + 1) uint256 _left = Math.max(_lockedBlock, _lastBlock + 1); uint256 _right = Math.min(_unlockBlock, block.number + 1); if (_left < _right) { unlockedAmount = unlockedAmount.add(_amount.mul(_right - _left).div(_unlockBlock - _lockedBlock)); } // some reward unlocked if (_unlockBlock > block.number + 1) { _locks.push( UserLockedBalance({ amount: uint192(_amount), lockedBlock: uint32(_lockedBlock), unlockBlock: uint32(_unlockBlock) }) ); } } return unlockedAmount; } function _redeemWithList(UserLockedBalance[] storage _locks, uint256 _lastBlock) internal returns (uint256) { uint256 length = _locks.length; uint256 unlockedAmount = 0; for (uint256 i = 0; i < length; ) { uint256 _amount = _locks[i].amount; uint256 _startBlock = _locks[i].lockedBlock; uint256 _endBlock = _locks[i].unlockBlock; if (_amount > 0 && _startBlock <= block.number) { // in this case: _endBlock must greater than _lastBlock uint256 _left = Math.max(_lastBlock + 1, _startBlock); uint256 _right = Math.min(block.number + 1, _endBlock); unlockedAmount = unlockedAmount.add(_amount.mul(_right - _left).div(_endBlock - _startBlock)); if (_endBlock <= block.number) { // since the order is not important // use swap and delete to reduce the length of array length -= 1; _locks[i] = _locks[length]; delete _locks[length]; _locks.pop(); } else { i++; } } } return unlockedAmount; } function _getRedeemableWithList(UserLockedBalance[] storage _locks, uint256 _lastBlock) internal view returns (uint256) { uint256 length = _locks.length; uint256 unlockedAmount = 0; for (uint256 i = 0; i < length; i++) { uint256 _amount = _locks[i].amount; uint256 _startBlock = _locks[i].lockedBlock; uint256 _endBlock = _locks[i].unlockBlock; if (_amount > 0 && _startBlock <= block.number) { // in this case: _endBlock must greater than _lastBlock uint256 _left = Math.max(_lastBlock + 1, _startBlock); uint256 _right = Math.min(block.number + 1, _endBlock); unlockedAmount = unlockedAmount.add(_amount.mul(_right - _left).div(_endBlock - _startBlock)); } } return unlockedAmount; } function _getPendingWithList(UserLockedBalance[] storage _locks, uint256 _lastBlock) internal view returns (uint256) { uint256 length = _locks.length; uint256 pendingAmount = 0; for (uint256 i = 0; i < length; i++) { uint256 _amount = _locks[i].amount; uint256 _startBlock = _locks[i].lockedBlock; uint256 _endBlock = _locks[i].unlockBlock; // [_startBlock, _endBlock), [_lastBlock + 1, oo) if (_amount > 0 && _endBlock > _lastBlock + 1) { // in this case: _endBlock must greater than _lastBlock uint256 _left = Math.max(_lastBlock + 1, _startBlock); pendingAmount = pendingAmount.add(_amount.mul(_endBlock - _left).div(_endBlock - _startBlock)); } } return pendingAmount; } function _getRedeemableRewardBond( address _user, uint256 _lastEpoch, uint256 _lastBlock ) internal view returns (uint256) { uint256 unlockedAmount; address[] memory _vaults = IRewardBondDepositor(rewardBondDepositor).getVaultsFromAccount(_user); for (uint256 i = 0; i < _vaults.length; i++) { unlockedAmount = unlockedAmount.add(_getRedeemableRewardBondByVault(_user, _vaults[i], _lastEpoch, _lastBlock)); } return unlockedAmount; } function _getPendingRewardBond( address _user, uint256 _lastEpoch, uint256 _lastBlock ) internal view returns (uint256) { uint256 pendingAmount; address[] memory _vaults = IRewardBondDepositor(rewardBondDepositor).getVaultsFromAccount(_user); for (uint256 i = 0; i < _vaults.length; i++) { pendingAmount = pendingAmount.add(_getPendingRewardBondByVault(_user, _vaults[i], _lastEpoch, _lastBlock)); } return pendingAmount; } function _getRedeemableRewardBondByVault( address _user, address _vault, uint256 _startEpoch, uint256 _lastBlock ) internal view returns (uint256) { IRewardBondDepositor _depositor = IRewardBondDepositor(rewardBondDepositor); // gas saving uint256 unlockedAmount; uint256[] memory _shares = _depositor.getAccountRewardShareSince(_startEpoch, _user, _vault); for (uint256 i = 0; i < _shares.length; i++) { if (_shares[i] == 0) continue; uint256 _epoch = _startEpoch + i; uint256 _unlockBlock = rewardBondLocks[_epoch].unlockBlock; if (_unlockBlock <= _lastBlock + 1) continue; uint256 _amount = rewardBondLocks[_epoch].amounts[_vault]; uint256 _lockedBlock = rewardBondLocks[_epoch].lockedBlock; { uint256 _totalShare = _depositor.rewardShares(_epoch, _vault); _amount = _amount.mul(_shares[i]).div(_totalShare); } // [_lockedBlock, _unlockBlock), [_lastBlock + 1, block.number + 1) uint256 _left = Math.max(_lockedBlock, _lastBlock + 1); uint256 _right = Math.min(_unlockBlock, block.number + 1); if (_left < _right) { unlockedAmount = unlockedAmount.add(_amount.mul(_right - _left).div(_unlockBlock - _lockedBlock)); } } return unlockedAmount; } function _getPendingRewardBondByVault( address _user, address _vault, uint256 _startEpoch, uint256 _lastBlock ) internal view returns (uint256) { IRewardBondDepositor _depositor = IRewardBondDepositor(rewardBondDepositor); // gas saving uint256 pendingAmount; uint256[] memory _shares = _depositor.getAccountRewardShareSince(_startEpoch, _user, _vault); for (uint256 i = 0; i < _shares.length; i++) { if (_shares[i] == 0) continue; uint256 _epoch = _startEpoch + i; uint256 _unlockBlock = rewardBondLocks[_epoch].unlockBlock; if (_unlockBlock <= _lastBlock + 1) continue; uint256 _amount = rewardBondLocks[_epoch].amounts[_vault]; uint256 _lockedBlock = rewardBondLocks[_epoch].lockedBlock; { uint256 _totalShare = _depositor.rewardShares(_epoch, _vault); _amount = _amount.mul(_shares[i]).div(_totalShare); } // [_lockedBlock, _unlockBlock), [_lastBlock + 1, oo) uint256 _left = Math.max(_lockedBlock, _lastBlock + 1); if (_left < _unlockBlock) { pendingAmount = pendingAmount.add(_amount.mul(_unlockBlock - _left).div(_unlockBlock - _lockedBlock)); } } return pendingAmount; } /// @dev Find the possible start epoch for current user to calculate pending/unlocked ALD for vault. /// @param _user The address of user. /// @param _lastBlock The last block user interacted with the contract. function _findPossibleStartEpoch(address _user, uint256 _lastBlock) internal view returns (uint256) { uint256 _minLockedBlock = _findEarlistRewardLockedBlock(_user); uint256 _lastEpoch = checkpoint[_user].epochNumber; if (_minLockedBlock == 0) { // No locks available or all locked ALD are redeemed, in this case, // + _lastBlock = 0: user didn't interact with the contract, we should calculate from the first epoch // + _lastBlock != 0: user has interacted with the contract, we should calculate from the last epoch if (_lastBlock == 0) return 0; else return _lastEpoch; } else { // Locks available, we should find the epoch number by searching _minLockedBlock return _findEpochByLockedBlock(_minLockedBlock, _lastEpoch); } } /// @dev find the epoch whose lockedBlock is `_lockedBlock`. /// @param _lockedBlock the epoch to find /// @param _epochHint the hint for search the epoch function _findEpochByLockedBlock(uint256 _lockedBlock, uint256 _epochHint) internal view returns (uint256) { // usually at most `bondLockingPeriod` loop is enough. while (_epochHint > 0) { if (rewardBondLocks[_epochHint].lockedBlock == _lockedBlock) break; _epochHint = _epochHint - 1; } return _epochHint; } /// @dev find the earlist reward locked block, which will be used to find possible start epoch /// @param _user The address of user. function _findEarlistRewardLockedBlock(address _user) internal view returns (uint256) { UserLockedBalance[] storage _locks = userRewardBondLocks[_user]; uint256 length = _locks.length; // no locks or all unlocked and redeemed if (length == 0) return 0; uint256 _minLockedBlock = _locks[0].lockedBlock; for (uint256 i = 1; i < length; i++) { uint256 _lockedBlock = _locks[i].lockedBlock; if (_lockedBlock < _minLockedBlock) { _minLockedBlock = _lockedBlock; } } return _minLockedBlock; } }
@dev return the unlocked xALD amount from user bond. @param _user The address of user. be carefull when no checkpoint for _user
function unlockedBondXALD(address _user) external view returns (uint256) { uint256 _lastBlock = checkpoint[_user].blockNumber; uint256 unlockedAmount = _getRedeemableWithList(userDirectBondLocks[_user], _lastBlock); return IWXALD(wxALD).wrappedXALDToXALD(unlockedAmount); }
2,461,636
[ 1, 2463, 326, 25966, 619, 1013, 40, 3844, 628, 729, 8427, 18, 225, 389, 1355, 1021, 1758, 434, 729, 18, 506, 7671, 2854, 1347, 1158, 9776, 364, 389, 1355, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 25966, 9807, 60, 1013, 40, 12, 2867, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 389, 2722, 1768, 273, 9776, 63, 67, 1355, 8009, 2629, 1854, 31, 203, 203, 565, 2254, 5034, 25966, 6275, 273, 389, 588, 426, 24903, 429, 1190, 682, 12, 1355, 5368, 9807, 19159, 63, 67, 1355, 6487, 389, 2722, 1768, 1769, 203, 203, 565, 327, 467, 59, 60, 1013, 40, 12, 27226, 1013, 40, 2934, 18704, 60, 1013, 40, 14955, 1013, 40, 12, 318, 15091, 6275, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Сочетаемость глаголов (и отглагольных частей речи) с предложным // паттерном. // LC->07.08.2018 facts гл_предл language=Russian { arity=3 //violation_score=-5 generic return=boolean } #define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{} #region Предлог_В // ------------------- С ПРЕДЛОГОМ 'В' --------------------------- #region Предложный // Глаголы и отглагольные части речи, присоединяющие // предложное дополнение с предлогом В и сущ. в предложном падеже. wordentry_set Гл_В_Предл = { rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль // вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб rus_verbs:воевать{}, // Воевал во Франции. rus_verbs:устать{}, // Устали в дороге? rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения. rus_verbs:решить{}, // Что решат в правительстве? rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает. rus_verbs:обстоять{}, // В действительности же дело обстояло не так. rus_verbs:подыматься{}, rus_verbs:поехать{}, // поедем в такси! rus_verbs:уехать{}, // он уехал в такси rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей rus_verbs:ОБЛАЧИТЬ{}, rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло. rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ) rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ) rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ) rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ) rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ) rus_verbs:ЗАМАЯЧИТЬ{}, rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ) rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ) rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ) rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ) rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ) rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ) rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ) rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ) rus_verbs:ПоТЕРЯТЬ{}, rus_verbs:УТЕРЯТЬ{}, rus_verbs:РАСТЕРЯТЬ{}, rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.) rus_verbs:СОМКНУТЬСЯ{}, rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ) rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ) rus_verbs:ВЫСТОЯТЬ{}, rus_verbs:ПОСТОЯТЬ{}, rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ) rus_verbs:ВЗВЕШИВАТЬ{}, rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ) прилагательное:быстрый{}, // Кисель быстр в приготовлении rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень rus_verbs:призывать{}, rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ) rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ) rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ) rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ) rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ) rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ) rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ) rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ) rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ) rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ) rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ) rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ) rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ) rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ) rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ) rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ) rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ) rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ) rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ) rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ) rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ) rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ) rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ) rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ) rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ) rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ) rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ) rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ) инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан глагол:проводить{ вид:несоверш }, деепричастие:проводя{}, rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл) rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл) rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл) rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл) rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл) rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл) rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл) rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл) rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл) rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл) rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл) rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл) rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл) rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл) rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл) прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В) rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл) rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл) rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл) rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл) rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл) rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл) rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл) rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл) rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В) rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В) rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл) rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В) rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл) rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл) rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В) rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл) rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл) rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В) rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл) rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В) rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В) rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В) rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В) rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл) rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В) частица:нет{}, // В этом нет сомнения. частица:нету{}, // В этом нету сомнения. rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов. прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В) rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В) rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В) rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В) rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл) rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В) rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в) rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В) rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В) rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В) rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В) rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В) rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В) rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В) rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В) rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В) rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В) rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В) rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В) rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В) rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:РАСКЛАДЫВАТЬСЯ{}, rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В) rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В) rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В) rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В) rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл) rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В) rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В) инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В) глагол:НАПИСАТЬ{ aux stress="напис^ать" }, прилагательное:НАПИСАННЫЙ{}, rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В) rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В) rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В) rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В) rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В) rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В) rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл) rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл) rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В) безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в) rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В) rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В) rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В) rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В) rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В) rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В) rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В) rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В) rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В) rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В) rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В) rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В) rus_verbs:объявить{}, // В газете объявили о конкурсе. rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В) rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В) rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в) rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в) rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в) rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в) инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В) глагол:ПАРИТЬ{ aux stress="пар^ить"}, деепричастие:паря{ aux stress="пар^я" }, прилагательное:ПАРЯЩИЙ{}, прилагательное:ПАРИВШИЙ{}, rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В) rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В) rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в) rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В) rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В) rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В) rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В) rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В) rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В) rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в) rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в) rus_verbs:принять{}, // Документ принят в следующей редакции (принять в) rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в) rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В) rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в) rus_verbs:звучать{}, // в доме звучала музыка (звучать в) rus_verbs:колебаться{}, // колеблется в выборе (колебаться в) rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в) rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в) rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в) rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в) rus_verbs:вычитывать{}, // вычитывать в книге rus_verbs:гудеть{}, // У него в ушах гудит. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки. rus_verbs:разойтись{}, // Они разошлись в темноте. rus_verbs:прибежать{}, // Мальчик прибежал в слезах. rus_verbs:биться{}, // Она билась в истерике. rus_verbs:регистрироваться{}, // регистрироваться в системе rus_verbs:считать{}, // я буду считать в уме rus_verbs:трахаться{}, // трахаться в гамаке rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке rus_verbs:разрушать{}, // разрушать в дробилке rus_verbs:засидеться{}, // засидеться в гостях rus_verbs:засиживаться{}, // засиживаться в гостях rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке) rus_verbs:навестить{}, // навестить в доме престарелых rus_verbs:запомнить{}, // запомнить в кэше rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.) rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка) rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику. rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.) rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу rus_verbs:оглядываться{}, // оглядываться в зеркале rus_verbs:нарисовать{}, // нарисовать в тетрадке rus_verbs:пробить{}, // пробить отверствие в стене rus_verbs:повертеть{}, // повертеть в руке rus_verbs:вертеть{}, // Я вертел в руках rus_verbs:рваться{}, // Веревка рвется в месте надреза rus_verbs:распространяться{}, // распространяться в среде наркоманов rus_verbs:попрощаться{}, // попрощаться в здании морга rus_verbs:соображать{}, // соображать в уме инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот) rus_verbs:разобрать{}, // разобрать в гараже rus_verbs:помереть{}, // помереть в пути rus_verbs:различить{}, // различить в темноте rus_verbs:рисовать{}, // рисовать в графическом редакторе rus_verbs:проследить{}, // проследить в записях камер слежения rus_verbs:совершаться{}, // Правосудие совершается в суде rus_verbs:задремать{}, // задремать в кровати rus_verbs:ругаться{}, // ругаться в комнате rus_verbs:зазвучать{}, // зазвучать в радиоприемниках rus_verbs:задохнуться{}, // задохнуться в воде rus_verbs:порождать{}, // порождать в неокрепших умах rus_verbs:отдыхать{}, // отдыхать в санатории rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении rus_verbs:образовать{}, // образовать в пробирке темную взвесь rus_verbs:отмечать{}, // отмечать в списке rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте rus_verbs:плясать{}, // плясать в откружении незнакомых людей rus_verbs:повысить{}, // повысить в звании rus_verbs:поджидать{}, // поджидать в подъезде rus_verbs:отказать{}, // отказать в пересмотре дела rus_verbs:раствориться{}, // раствориться в бензине rus_verbs:отражать{}, // отражать в стихах rus_verbs:дремать{}, // дремать в гамаке rus_verbs:применяться{}, // применяться в домашних условиях rus_verbs:присниться{}, // присниться во сне rus_verbs:трястись{}, // трястись в драндулете rus_verbs:сохранять{}, // сохранять в неприкосновенности rus_verbs:расстрелять{}, // расстрелять в ложбине rus_verbs:рассчитать{}, // рассчитать в программе rus_verbs:перебирать{}, // перебирать в руке rus_verbs:разбиться{}, // разбиться в аварии rus_verbs:поискать{}, // поискать в углу rus_verbs:мучиться{}, // мучиться в тесной клетке rus_verbs:замелькать{}, // замелькать в телевизоре rus_verbs:грустить{}, // грустить в одиночестве rus_verbs:крутить{}, // крутить в банке rus_verbs:объявиться{}, // объявиться в городе rus_verbs:подготовить{}, // подготовить в тайне rus_verbs:различать{}, // различать в смеси rus_verbs:обнаруживать{}, // обнаруживать в крови rus_verbs:киснуть{}, // киснуть в захолустье rus_verbs:оборваться{}, // оборваться в начале фразы rus_verbs:запутаться{}, // запутаться в веревках rus_verbs:общаться{}, // общаться в интимной обстановке rus_verbs:сочинить{}, // сочинить в ресторане rus_verbs:изобрести{}, // изобрести в домашней лаборатории rus_verbs:прокомментировать{}, // прокомментировать в своем блоге rus_verbs:давить{}, // давить в зародыше rus_verbs:повториться{}, // повториться в новом обличье rus_verbs:отставать{}, // отставать в общем зачете rus_verbs:разработать{}, // разработать в лаборатории rus_verbs:качать{}, // качать в кроватке rus_verbs:заменить{}, // заменить в двигателе rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере rus_verbs:забегать{}, // забегать в спешке rus_verbs:наделать{}, // наделать в решении ошибок rus_verbs:исказиться{}, // исказиться в кривом зеркале rus_verbs:тушить{}, // тушить в помещении пожар rus_verbs:охранять{}, // охранять в здании входы rus_verbs:приметить{}, // приметить в кустах rus_verbs:скрыть{}, // скрыть в складках одежды rus_verbs:удерживать{}, // удерживать в заложниках rus_verbs:увеличиваться{}, // увеличиваться в размере rus_verbs:красоваться{}, // красоваться в новом платье rus_verbs:сохраниться{}, // сохраниться в тепле rus_verbs:лечить{}, // лечить в стационаре rus_verbs:смешаться{}, // смешаться в баке rus_verbs:прокатиться{}, // прокатиться в троллейбусе rus_verbs:договариваться{}, // договариваться в закрытом кабинете rus_verbs:опубликовать{}, // опубликовать в официальном блоге rus_verbs:охотиться{}, // охотиться в прериях rus_verbs:отражаться{}, // отражаться в окне rus_verbs:понизить{}, // понизить в должности rus_verbs:обедать{}, // обедать в ресторане rus_verbs:посидеть{}, // посидеть в тени rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете rus_verbs:свершиться{}, // свершиться в суде rus_verbs:ночевать{}, // ночевать в гостинице rus_verbs:темнеть{}, // темнеть в воде rus_verbs:гибнуть{}, // гибнуть в застенках rus_verbs:усиливаться{}, // усиливаться в направлении главного удара rus_verbs:расплыться{}, // расплыться в улыбке rus_verbs:превышать{}, // превышать в несколько раз rus_verbs:проживать{}, // проживать в отдельной коморке rus_verbs:голубеть{}, // голубеть в тепле rus_verbs:исследовать{}, // исследовать в естественных условиях rus_verbs:обитать{}, // обитать в лесу rus_verbs:скучать{}, // скучать в одиночестве rus_verbs:сталкиваться{}, // сталкиваться в воздухе rus_verbs:таиться{}, // таиться в глубине rus_verbs:спасать{}, // спасать в море rus_verbs:заблудиться{}, // заблудиться в лесу rus_verbs:создаться{}, // создаться в новом виде rus_verbs:пошарить{}, // пошарить в кармане rus_verbs:планировать{}, // планировать в программе rus_verbs:отбить{}, // отбить в нижней части rus_verbs:отрицать{}, // отрицать в суде свою вину rus_verbs:основать{}, // основать в пустыне новый город rus_verbs:двоить{}, // двоить в глазах rus_verbs:устоять{}, // устоять в лодке rus_verbs:унять{}, // унять в ногах дрожь rus_verbs:отзываться{}, // отзываться в обзоре rus_verbs:притормозить{}, // притормозить в траве rus_verbs:читаться{}, // читаться в глазах rus_verbs:житься{}, // житься в деревне rus_verbs:заиграть{}, // заиграть в жилах rus_verbs:шевелить{}, // шевелить в воде rus_verbs:зазвенеть{}, // зазвенеть в ушах rus_verbs:зависнуть{}, // зависнуть в библиотеке rus_verbs:затаить{}, // затаить в душе обиду rus_verbs:сознаться{}, // сознаться в совершении rus_verbs:протекать{}, // протекать в легкой форме rus_verbs:выясняться{}, // выясняться в ходе эксперимента rus_verbs:скрестить{}, // скрестить в неволе rus_verbs:наводить{}, // наводить в комнате порядок rus_verbs:значиться{}, // значиться в документах rus_verbs:заинтересовать{}, // заинтересовать в получении результатов rus_verbs:познакомить{}, // познакомить в непринужденной обстановке rus_verbs:рассеяться{}, // рассеяться в воздухе rus_verbs:грохнуть{}, // грохнуть в подвале rus_verbs:обвинять{}, // обвинять в вымогательстве rus_verbs:столпиться{}, // столпиться в фойе rus_verbs:порыться{}, // порыться в сумке rus_verbs:ослабить{}, // ослабить в верхней части rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки rus_verbs:спастись{}, // спастись в хижине rus_verbs:прерваться{}, // прерваться в середине фразы rus_verbs:применять{}, // применять в повседневной работе rus_verbs:строиться{}, // строиться в зоне отчуждения rus_verbs:путешествовать{}, // путешествовать в самолете rus_verbs:побеждать{}, // побеждать в честной битве rus_verbs:погубить{}, // погубить в себе артиста rus_verbs:рассматриваться{}, // рассматриваться в следующей главе rus_verbs:продаваться{}, // продаваться в специализированном магазине rus_verbs:разместиться{}, // разместиться в аудитории rus_verbs:повидать{}, // повидать в жизни rus_verbs:настигнуть{}, // настигнуть в пригородах rus_verbs:сгрудиться{}, // сгрудиться в центре загона rus_verbs:укрыться{}, // укрыться в доме rus_verbs:расплакаться{}, // расплакаться в суде rus_verbs:пролежать{}, // пролежать в канаве rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде rus_verbs:поскользнуться{}, // поскользнуться в коридоре rus_verbs:таскать{}, // таскать в руках rus_verbs:нападать{}, // нападать в вольере rus_verbs:просматривать{}, // просматривать в браузере rus_verbs:обдумать{}, // обдумать в дороге rus_verbs:обвинить{}, // обвинить в измене rus_verbs:останавливать{}, // останавливать в дверях rus_verbs:теряться{}, // теряться в догадках rus_verbs:погибать{}, // погибать в бою rus_verbs:обозначать{}, // обозначать в списке rus_verbs:запрещать{}, // запрещать в парке rus_verbs:долететь{}, // долететь в вертолёте rus_verbs:тесниться{}, // тесниться в каморке rus_verbs:уменьшаться{}, // уменьшаться в размере rus_verbs:издавать{}, // издавать в небольшом издательстве rus_verbs:хоронить{}, // хоронить в море rus_verbs:перемениться{}, // перемениться в лице rus_verbs:установиться{}, // установиться в северных областях rus_verbs:прикидывать{}, // прикидывать в уме rus_verbs:затаиться{}, // затаиться в траве rus_verbs:раздобыть{}, // раздобыть в аптеке rus_verbs:перебросить{}, // перебросить в товарном составе rus_verbs:погружаться{}, // погружаться в батискафе rus_verbs:поживать{}, // поживать в одиночестве rus_verbs:признаваться{}, // признаваться в любви rus_verbs:захватывать{}, // захватывать в здании rus_verbs:покачиваться{}, // покачиваться в лодке rus_verbs:крутиться{}, // крутиться в колесе rus_verbs:помещаться{}, // помещаться в ящике rus_verbs:питаться{}, // питаться в столовой rus_verbs:отдохнуть{}, // отдохнуть в пансионате rus_verbs:кататься{}, // кататься в коляске rus_verbs:поработать{}, // поработать в цеху rus_verbs:подразумевать{}, // подразумевать в задании rus_verbs:ограбить{}, // ограбить в подворотне rus_verbs:преуспеть{}, // преуспеть в бизнесе rus_verbs:заерзать{}, // заерзать в кресле rus_verbs:разъяснить{}, // разъяснить в другой статье rus_verbs:продвинуться{}, // продвинуться в изучении rus_verbs:поколебаться{}, // поколебаться в начале rus_verbs:засомневаться{}, // засомневаться в честности rus_verbs:приникнуть{}, // приникнуть в уме rus_verbs:скривить{}, // скривить в усмешке rus_verbs:рассечь{}, // рассечь в центре опухоли rus_verbs:перепутать{}, // перепутать в роддоме rus_verbs:посмеяться{}, // посмеяться в перерыве rus_verbs:отмечаться{}, // отмечаться в полицейском участке rus_verbs:накопиться{}, // накопиться в отстойнике rus_verbs:уносить{}, // уносить в руках rus_verbs:навещать{}, // навещать в больнице rus_verbs:остыть{}, // остыть в проточной воде rus_verbs:запереться{}, // запереться в комнате rus_verbs:обогнать{}, // обогнать в первом круге rus_verbs:убеждаться{}, // убеждаться в неизбежности rus_verbs:подбирать{}, // подбирать в магазине rus_verbs:уничтожать{}, // уничтожать в полете rus_verbs:путаться{}, // путаться в показаниях rus_verbs:притаиться{}, // притаиться в темноте rus_verbs:проплывать{}, // проплывать в лодке rus_verbs:засесть{}, // засесть в окопе rus_verbs:подцепить{}, // подцепить в баре rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок rus_verbs:оправдаться{}, // оправдаться в суде rus_verbs:созреть{}, // созреть в естественных условиях rus_verbs:раскрываться{}, // раскрываться в подходящих условиях rus_verbs:ожидаться{}, // ожидаться в верхней части rus_verbs:одеваться{}, // одеваться в дорогих бутиках rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта rus_verbs:грабить{}, // грабить в подворотне rus_verbs:ужинать{}, // ужинать в ресторане rus_verbs:гонять{}, // гонять в жилах rus_verbs:уверить{}, // уверить в безопасности rus_verbs:потеряться{}, // потеряться в лесу rus_verbs:устанавливаться{}, // устанавливаться в комнате rus_verbs:предоставлять{}, // предоставлять в суде rus_verbs:протянуться{}, // протянуться в стене rus_verbs:допрашивать{}, // допрашивать в бункере rus_verbs:проработать{}, // проработать в кабинете rus_verbs:сосредоточить{}, // сосредоточить в своих руках rus_verbs:утвердить{}, // утвердить в должности rus_verbs:сочинять{}, // сочинять в дороге rus_verbs:померкнуть{}, // померкнуть в глазах rus_verbs:показываться{}, // показываться в окошке rus_verbs:похудеть{}, // похудеть в талии rus_verbs:проделывать{}, // проделывать в стене rus_verbs:прославиться{}, // прославиться в интернете rus_verbs:сдохнуть{}, // сдохнуть в нищете rus_verbs:раскинуться{}, // раскинуться в степи rus_verbs:развить{}, // развить в себе способности rus_verbs:уставать{}, // уставать в цеху rus_verbs:укрепить{}, // укрепить в земле rus_verbs:числиться{}, // числиться в списке rus_verbs:образовывать{}, // образовывать в смеси rus_verbs:екнуть{}, // екнуть в груди rus_verbs:одобрять{}, // одобрять в своей речи rus_verbs:запить{}, // запить в одиночестве rus_verbs:забыться{}, // забыться в тяжелом сне rus_verbs:чернеть{}, // чернеть в кислой среде rus_verbs:размещаться{}, // размещаться в гараже rus_verbs:соорудить{}, // соорудить в гараже rus_verbs:развивать{}, // развивать в себе rus_verbs:пастись{}, // пастись в пойме rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы rus_verbs:ослабнуть{}, // ослабнуть в сочленении rus_verbs:таить{}, // таить в себе инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке rus_verbs:приостановиться{}, // приостановиться в конце rus_verbs:топтаться{}, // топтаться в грязи rus_verbs:громить{}, // громить в финале rus_verbs:заменять{}, // заменять в основном составе rus_verbs:подъезжать{}, // подъезжать в колясках rus_verbs:вычислить{}, // вычислить в уме rus_verbs:заказывать{}, // заказывать в магазине rus_verbs:осуществить{}, // осуществить в реальных условиях rus_verbs:обосноваться{}, // обосноваться в дупле rus_verbs:пытать{}, // пытать в камере rus_verbs:поменять{}, // поменять в магазине rus_verbs:совершиться{}, // совершиться в суде rus_verbs:пролетать{}, // пролетать в вертолете rus_verbs:сбыться{}, // сбыться во сне rus_verbs:разговориться{}, // разговориться в отделении rus_verbs:преподнести{}, // преподнести в красивой упаковке rus_verbs:напечатать{}, // напечатать в типографии rus_verbs:прорвать{}, // прорвать в центре rus_verbs:раскачиваться{}, // раскачиваться в кресле rus_verbs:задерживаться{}, // задерживаться в дверях rus_verbs:угощать{}, // угощать в кафе rus_verbs:проступать{}, // проступать в глубине rus_verbs:шарить{}, // шарить в математике rus_verbs:увеличивать{}, // увеличивать в конце rus_verbs:расцвести{}, // расцвести в оранжерее rus_verbs:закипеть{}, // закипеть в баке rus_verbs:подлететь{}, // подлететь в вертолете rus_verbs:рыться{}, // рыться в куче rus_verbs:пожить{}, // пожить в гостинице rus_verbs:добираться{}, // добираться в попутном транспорте rus_verbs:перекрыть{}, // перекрыть в коридоре rus_verbs:продержаться{}, // продержаться в барокамере rus_verbs:разыскивать{}, // разыскивать в толпе rus_verbs:освобождать{}, // освобождать в зале суда rus_verbs:подметить{}, // подметить в человеке rus_verbs:передвигаться{}, // передвигаться в узкой юбке rus_verbs:продумать{}, // продумать в уме rus_verbs:извиваться{}, // извиваться в траве rus_verbs:процитировать{}, // процитировать в статье rus_verbs:прогуливаться{}, // прогуливаться в парке rus_verbs:защемить{}, // защемить в двери rus_verbs:увеличиться{}, // увеличиться в объеме rus_verbs:проявиться{}, // проявиться в результатах rus_verbs:заскользить{}, // заскользить в ботинках rus_verbs:пересказать{}, // пересказать в своем выступлении rus_verbs:протестовать{}, // протестовать в здании парламента rus_verbs:указываться{}, // указываться в путеводителе rus_verbs:копошиться{}, // копошиться в песке rus_verbs:проигнорировать{}, // проигнорировать в своей работе rus_verbs:купаться{}, // купаться в речке rus_verbs:подсчитать{}, // подсчитать в уме rus_verbs:разволноваться{}, // разволноваться в классе rus_verbs:придумывать{}, // придумывать в своем воображении rus_verbs:предусмотреть{}, // предусмотреть в программе rus_verbs:завертеться{}, // завертеться в колесе rus_verbs:зачерпнуть{}, // зачерпнуть в ручье rus_verbs:очистить{}, // очистить в химической лаборатории rus_verbs:прозвенеть{}, // прозвенеть в коридорах rus_verbs:уменьшиться{}, // уменьшиться в размере rus_verbs:колыхаться{}, // колыхаться в проточной воде rus_verbs:ознакомиться{}, // ознакомиться в автобусе rus_verbs:ржать{}, // ржать в аудитории rus_verbs:раскинуть{}, // раскинуть в микрорайоне rus_verbs:разлиться{}, // разлиться в воде rus_verbs:сквозить{}, // сквозить в словах rus_verbs:задушить{}, // задушить в объятиях rus_verbs:осудить{}, // осудить в особом порядке rus_verbs:разгромить{}, // разгромить в честном поединке rus_verbs:подслушать{}, // подслушать в кулуарах rus_verbs:проповедовать{}, // проповедовать в сельских районах rus_verbs:озарить{}, // озарить во сне rus_verbs:потирать{}, // потирать в предвкушении rus_verbs:описываться{}, // описываться в статье rus_verbs:качаться{}, // качаться в кроватке rus_verbs:усилить{}, // усилить в центре rus_verbs:прохаживаться{}, // прохаживаться в новом костюме rus_verbs:полечить{}, // полечить в больничке rus_verbs:сниматься{}, // сниматься в римейке rus_verbs:сыскать{}, // сыскать в наших краях rus_verbs:поприветствовать{}, // поприветствовать в коридоре rus_verbs:подтвердиться{}, // подтвердиться в эксперименте rus_verbs:плескаться{}, // плескаться в теплой водичке rus_verbs:расширяться{}, // расширяться в первом сегменте rus_verbs:мерещиться{}, // мерещиться в тумане rus_verbs:сгущаться{}, // сгущаться в воздухе rus_verbs:храпеть{}, // храпеть во сне rus_verbs:подержать{}, // подержать в руках rus_verbs:накинуться{}, // накинуться в подворотне rus_verbs:планироваться{}, // планироваться в закрытом режиме rus_verbs:пробудить{}, // пробудить в себе rus_verbs:побриться{}, // побриться в ванной rus_verbs:сгинуть{}, // сгинуть в пучине rus_verbs:окрестить{}, // окрестить в церкви инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления rus_verbs:замкнуться{}, // замкнуться в себе rus_verbs:прибавлять{}, // прибавлять в весе rus_verbs:проплыть{}, // проплыть в лодке rus_verbs:растворяться{}, // растворяться в тумане rus_verbs:упрекать{}, // упрекать в небрежности rus_verbs:затеряться{}, // затеряться в лабиринте rus_verbs:перечитывать{}, // перечитывать в поезде rus_verbs:перелететь{}, // перелететь в вертолете rus_verbs:оживать{}, // оживать в теплой воде rus_verbs:заглохнуть{}, // заглохнуть в полете rus_verbs:кольнуть{}, // кольнуть в боку rus_verbs:копаться{}, // копаться в куче rus_verbs:развлекаться{}, // развлекаться в клубе rus_verbs:отливать{}, // отливать в кустах rus_verbs:зажить{}, // зажить в деревне rus_verbs:одолжить{}, // одолжить в соседнем кабинете rus_verbs:заклинать{}, // заклинать в своей речи rus_verbs:различаться{}, // различаться в мелочах rus_verbs:печататься{}, // печататься в типографии rus_verbs:угадываться{}, // угадываться в контурах rus_verbs:обрывать{}, // обрывать в начале rus_verbs:поглаживать{}, // поглаживать в кармане rus_verbs:подписывать{}, // подписывать в присутствии понятых rus_verbs:добывать{}, // добывать в разломе rus_verbs:скопиться{}, // скопиться в воротах rus_verbs:повстречать{}, // повстречать в бане rus_verbs:совпасть{}, // совпасть в упрощенном виде rus_verbs:разрываться{}, // разрываться в точке спайки rus_verbs:улавливать{}, // улавливать в датчике rus_verbs:повстречаться{}, // повстречаться в лифте rus_verbs:отразить{}, // отразить в отчете rus_verbs:пояснять{}, // пояснять в примечаниях rus_verbs:накормить{}, // накормить в столовке rus_verbs:поужинать{}, // поужинать в ресторане инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить в молоке rus_verbs:освоить{}, // освоить в работе rus_verbs:зародиться{}, // зародиться в голове rus_verbs:отплыть{}, // отплыть в старой лодке rus_verbs:отстаивать{}, // отстаивать в суде rus_verbs:осуждать{}, // осуждать в своем выступлении rus_verbs:переговорить{}, // переговорить в перерыве rus_verbs:разгораться{}, // разгораться в сердце rus_verbs:укрыть{}, // укрыть в шалаше rus_verbs:томиться{}, // томиться в застенках rus_verbs:клубиться{}, // клубиться в воздухе rus_verbs:сжигать{}, // сжигать в топке rus_verbs:позавтракать{}, // позавтракать в кафешке rus_verbs:функционировать{}, // функционировать в лабораторных условиях rus_verbs:смять{}, // смять в руке rus_verbs:разместить{}, // разместить в интернете rus_verbs:пронести{}, // пронести в потайном кармане rus_verbs:руководствоваться{}, // руководствоваться в работе rus_verbs:нашарить{}, // нашарить в потемках rus_verbs:закрутить{}, // закрутить в вихре rus_verbs:просматриваться{}, // просматриваться в дальней перспективе rus_verbs:распознать{}, // распознать в незнакомце rus_verbs:повеситься{}, // повеситься в камере rus_verbs:обшарить{}, // обшарить в поисках наркотиков rus_verbs:наполняться{}, // наполняется в карьере rus_verbs:засвистеть{}, // засвистеть в воздухе rus_verbs:процветать{}, // процветать в мягком климате rus_verbs:шуршать{}, // шуршать в простенке rus_verbs:подхватывать{}, // подхватывать в полете инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе прилагательное:роившийся{}, прилагательное:роящийся{}, // деепричастие:роясь{ aux stress="ро^ясь" }, rus_verbs:преобладать{}, // преобладать в тексте rus_verbs:посветлеть{}, // посветлеть в лице rus_verbs:игнорировать{}, // игнорировать в рекомендациях rus_verbs:обсуждаться{}, // обсуждаться в кулуарах rus_verbs:отказывать{}, // отказывать в визе rus_verbs:ощупывать{}, // ощупывать в кармане rus_verbs:разливаться{}, // разливаться в цеху rus_verbs:расписаться{}, // расписаться в получении rus_verbs:учинить{}, // учинить в казарме rus_verbs:плестись{}, // плестись в хвосте rus_verbs:объявляться{}, // объявляться в группе rus_verbs:повышаться{}, // повышаться в первой части rus_verbs:напрягать{}, // напрягать в паху rus_verbs:разрабатывать{}, // разрабатывать в студии rus_verbs:хлопотать{}, // хлопотать в мэрии rus_verbs:прерывать{}, // прерывать в самом начале rus_verbs:каяться{}, // каяться в грехах rus_verbs:освоиться{}, // освоиться в кабине rus_verbs:подплыть{}, // подплыть в лодке rus_verbs:замигать{}, // замигать в темноте rus_verbs:оскорблять{}, // оскорблять в выступлении rus_verbs:торжествовать{}, // торжествовать в душе rus_verbs:поправлять{}, // поправлять в прологе rus_verbs:угадывать{}, // угадывать в размытом изображении rus_verbs:потоптаться{}, // потоптаться в прихожей rus_verbs:переправиться{}, // переправиться в лодочке rus_verbs:увериться{}, // увериться в невиновности rus_verbs:забрезжить{}, // забрезжить в конце тоннеля rus_verbs:утвердиться{}, // утвердиться во мнении rus_verbs:завывать{}, // завывать в трубе rus_verbs:заварить{}, // заварить в заварнике rus_verbs:скомкать{}, // скомкать в руке rus_verbs:перемещаться{}, // перемещаться в капсуле инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле rus_verbs:праздновать{}, // праздновать в баре rus_verbs:мигать{}, // мигать в темноте rus_verbs:обучить{}, // обучить в мастерской rus_verbs:орудовать{}, // орудовать в кладовке rus_verbs:упорствовать{}, // упорствовать в заблуждении rus_verbs:переминаться{}, // переминаться в прихожей rus_verbs:подрасти{}, // подрасти в теплице rus_verbs:предписываться{}, // предписываться в законе rus_verbs:приписать{}, // приписать в конце rus_verbs:задаваться{}, // задаваться в своей статье rus_verbs:чинить{}, // чинить в домашних условиях rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке rus_verbs:пообедать{}, // пообедать в ресторанчике rus_verbs:жрать{}, // жрать в чуланчике rus_verbs:исполняться{}, // исполняться в антракте rus_verbs:гнить{}, // гнить в тюрьме rus_verbs:глодать{}, // глодать в конуре rus_verbs:прослушать{}, // прослушать в дороге rus_verbs:истратить{}, // истратить в кабаке rus_verbs:стареть{}, // стареть в одиночестве rus_verbs:разжечь{}, // разжечь в сердце rus_verbs:совещаться{}, // совещаться в кабинете rus_verbs:покачивать{}, // покачивать в кроватке rus_verbs:отсидеть{}, // отсидеть в одиночке rus_verbs:формировать{}, // формировать в умах rus_verbs:захрапеть{}, // захрапеть во сне rus_verbs:петься{}, // петься в хоре rus_verbs:объехать{}, // объехать в автобусе rus_verbs:поселить{}, // поселить в гостинице rus_verbs:предаться{}, // предаться в книге rus_verbs:заворочаться{}, // заворочаться во сне rus_verbs:напрятать{}, // напрятать в карманах rus_verbs:очухаться{}, // очухаться в незнакомом месте rus_verbs:ограничивать{}, // ограничивать в движениях rus_verbs:завертеть{}, // завертеть в руках rus_verbs:печатать{}, // печатать в редакторе rus_verbs:теплиться{}, // теплиться в сердце rus_verbs:увязнуть{}, // увязнуть в зыбучем песке rus_verbs:усмотреть{}, // усмотреть в обращении rus_verbs:отыскаться{}, // отыскаться в запасах rus_verbs:потушить{}, // потушить в горле огонь rus_verbs:поубавиться{}, // поубавиться в размере rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти rus_verbs:смыть{}, // смыть в ванной rus_verbs:заместить{}, // заместить в кресле rus_verbs:угасать{}, // угасать в одиночестве rus_verbs:сразить{}, // сразить в споре rus_verbs:фигурировать{}, // фигурировать в бюллетене rus_verbs:расплываться{}, // расплываться в глазах rus_verbs:сосчитать{}, // сосчитать в уме rus_verbs:сгуститься{}, // сгуститься в воздухе rus_verbs:цитировать{}, // цитировать в своей статье rus_verbs:помяться{}, // помяться в давке rus_verbs:затрагивать{}, // затрагивать в процессе выполнения rus_verbs:обтереть{}, // обтереть в гараже rus_verbs:подстрелить{}, // подстрелить в пойме реки rus_verbs:растереть{}, // растереть в руке rus_verbs:подавлять{}, // подавлять в зародыше rus_verbs:смешиваться{}, // смешиваться в чане инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке rus_verbs:сократиться{}, // сократиться в обхвате rus_verbs:занервничать{}, // занервничать в кабинете rus_verbs:соприкоснуться{}, // соприкоснуться в полете rus_verbs:обозначить{}, // обозначить в объявлении rus_verbs:обучаться{}, // обучаться в училище rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы rus_verbs:лелеять{}, // лелеять в сердце rus_verbs:поддерживаться{}, // поддерживаться в суде rus_verbs:уплыть{}, // уплыть в лодочке rus_verbs:резвиться{}, // резвиться в саду rus_verbs:поерзать{}, // поерзать в гамаке rus_verbs:оплатить{}, // оплатить в ресторане rus_verbs:похвастаться{}, // похвастаться в компании rus_verbs:знакомиться{}, // знакомиться в классе rus_verbs:приплыть{}, // приплыть в подводной лодке rus_verbs:зажигать{}, // зажигать в классе rus_verbs:смыслить{}, // смыслить в математике rus_verbs:закопать{}, // закопать в огороде rus_verbs:порхать{}, // порхать в зарослях rus_verbs:потонуть{}, // потонуть в бумажках rus_verbs:стирать{}, // стирать в холодной воде rus_verbs:подстерегать{}, // подстерегать в придорожных кустах rus_verbs:погулять{}, // погулять в парке rus_verbs:предвкушать{}, // предвкушать в воображении rus_verbs:ошеломить{}, // ошеломить в бою rus_verbs:удостовериться{}, // удостовериться в безопасности rus_verbs:огласить{}, // огласить в заключительной части rus_verbs:разбогатеть{}, // разбогатеть в деревне rus_verbs:грохотать{}, // грохотать в мастерской rus_verbs:реализоваться{}, // реализоваться в должности rus_verbs:красть{}, // красть в магазине rus_verbs:нарваться{}, // нарваться в коридоре rus_verbs:застывать{}, // застывать в неудобной позе rus_verbs:толкаться{}, // толкаться в тесной комнате rus_verbs:извлекать{}, // извлекать в аппарате rus_verbs:обжигать{}, // обжигать в печи rus_verbs:запечатлеть{}, // запечатлеть в кинохронике rus_verbs:тренироваться{}, // тренироваться в зале rus_verbs:поспорить{}, // поспорить в кабинете rus_verbs:рыскать{}, // рыскать в лесу rus_verbs:надрываться{}, // надрываться в шахте rus_verbs:сняться{}, // сняться в фильме rus_verbs:закружить{}, // закружить в танце rus_verbs:затонуть{}, // затонуть в порту rus_verbs:побыть{}, // побыть в гостях rus_verbs:почистить{}, // почистить в носу rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре rus_verbs:подслушивать{}, // подслушивать в классе rus_verbs:сгорать{}, // сгорать в танке rus_verbs:разочароваться{}, // разочароваться в артисте инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках rus_verbs:мять{}, // мять в руках rus_verbs:подраться{}, // подраться в классе rus_verbs:замести{}, // замести в прихожей rus_verbs:откладываться{}, // откладываться в печени rus_verbs:обозначаться{}, // обозначаться в перечне rus_verbs:просиживать{}, // просиживать в интернете rus_verbs:соприкасаться{}, // соприкасаться в точке rus_verbs:начертить{}, // начертить в тетрадке rus_verbs:уменьшать{}, // уменьшать в поперечнике rus_verbs:тормозить{}, // тормозить в облаке rus_verbs:затевать{}, // затевать в лаборатории rus_verbs:затопить{}, // затопить в бухте rus_verbs:задерживать{}, // задерживать в лифте rus_verbs:прогуляться{}, // прогуляться в лесу rus_verbs:прорубить{}, // прорубить во льду rus_verbs:очищать{}, // очищать в кислоте rus_verbs:полулежать{}, // полулежать в гамаке rus_verbs:исправить{}, // исправить в задании rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи rus_verbs:замучить{}, // замучить в плену rus_verbs:разрушаться{}, // разрушаться в верхней части rus_verbs:ерзать{}, // ерзать в кресле rus_verbs:покопаться{}, // покопаться в залежах rus_verbs:раскаяться{}, // раскаяться в содеянном rus_verbs:пробежаться{}, // пробежаться в парке rus_verbs:полежать{}, // полежать в гамаке rus_verbs:позаимствовать{}, // позаимствовать в книге rus_verbs:снижать{}, // снижать в несколько раз rus_verbs:черпать{}, // черпать в поэзии rus_verbs:заверять{}, // заверять в своей искренности rus_verbs:проглядеть{}, // проглядеть в сумерках rus_verbs:припарковать{}, // припарковать во дворе rus_verbs:сверлить{}, // сверлить в стене rus_verbs:здороваться{}, // здороваться в аудитории rus_verbs:рожать{}, // рожать в воде rus_verbs:нацарапать{}, // нацарапать в тетрадке rus_verbs:затопать{}, // затопать в коридоре rus_verbs:прописать{}, // прописать в правилах rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах rus_verbs:снизить{}, // снизить в несколько раз rus_verbs:заблуждаться{}, // заблуждаться в своей теории rus_verbs:откопать{}, // откопать в отвалах rus_verbs:смастерить{}, // смастерить в лаборатории rus_verbs:замедлиться{}, // замедлиться в парафине rus_verbs:избивать{}, // избивать в участке rus_verbs:мыться{}, // мыться в бане rus_verbs:сварить{}, // сварить в кастрюльке rus_verbs:раскопать{}, // раскопать в снегу rus_verbs:крепиться{}, // крепиться в держателе rus_verbs:дробить{}, // дробить в мельнице rus_verbs:попить{}, // попить в ресторанчике rus_verbs:затронуть{}, // затронуть в душе rus_verbs:лязгнуть{}, // лязгнуть в тишине rus_verbs:заправлять{}, // заправлять в полете rus_verbs:размножаться{}, // размножаться в неволе rus_verbs:потопить{}, // потопить в Тихом Океане rus_verbs:кушать{}, // кушать в столовой rus_verbs:замолкать{}, // замолкать в замешательстве rus_verbs:измеряться{}, // измеряться в дюймах rus_verbs:сбываться{}, // сбываться в мечтах rus_verbs:задернуть{}, // задернуть в комнате rus_verbs:затихать{}, // затихать в темноте rus_verbs:прослеживаться{}, // прослеживается в журнале rus_verbs:прерываться{}, // прерывается в начале rus_verbs:изображаться{}, // изображается в любых фильмах rus_verbs:фиксировать{}, // фиксировать в данной точке rus_verbs:ослаблять{}, // ослаблять в поясе rus_verbs:зреть{}, // зреть в теплице rus_verbs:зеленеть{}, // зеленеть в огороде rus_verbs:критиковать{}, // критиковать в статье rus_verbs:облететь{}, // облететь в частном вертолете rus_verbs:разбросать{}, // разбросать в комнате rus_verbs:заразиться{}, // заразиться в людном месте rus_verbs:рассеять{}, // рассеять в бою rus_verbs:печься{}, // печься в духовке rus_verbs:поспать{}, // поспать в палатке rus_verbs:заступиться{}, // заступиться в драке rus_verbs:сплетаться{}, // сплетаться в середине rus_verbs:поместиться{}, // поместиться в мешке rus_verbs:спереть{}, // спереть в лавке // инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде // инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш }, rus_verbs:проваляться{}, // проваляться в постели rus_verbs:лечиться{}, // лечиться в стационаре rus_verbs:определиться{}, // определиться в честном бою rus_verbs:обработать{}, // обработать в растворе rus_verbs:пробивать{}, // пробивать в стене rus_verbs:перемешаться{}, // перемешаться в чане rus_verbs:чесать{}, // чесать в паху rus_verbs:пролечь{}, // пролечь в пустынной местности rus_verbs:скитаться{}, // скитаться в дальних странах rus_verbs:затрудняться{}, // затрудняться в выборе rus_verbs:отряхнуться{}, // отряхнуться в коридоре rus_verbs:разыгрываться{}, // разыгрываться в лотерее rus_verbs:помолиться{}, // помолиться в церкви rus_verbs:предписывать{}, // предписывать в рецепте rus_verbs:порваться{}, // порваться в слабом месте rus_verbs:греться{}, // греться в здании rus_verbs:опровергать{}, // опровергать в своем выступлении rus_verbs:помянуть{}, // помянуть в своем выступлении rus_verbs:допросить{}, // допросить в прокуратуре rus_verbs:материализоваться{}, // материализоваться в соседнем здании rus_verbs:рассеиваться{}, // рассеиваться в воздухе rus_verbs:перевозить{}, // перевозить в вагоне rus_verbs:отбывать{}, // отбывать в тюрьме rus_verbs:попахивать{}, // попахивать в отхожем месте rus_verbs:перечислять{}, // перечислять в заключении rus_verbs:зарождаться{}, // зарождаться в дебрях rus_verbs:предъявлять{}, // предъявлять в своем письме rus_verbs:распространять{}, // распространять в сети rus_verbs:пировать{}, // пировать в соседнем селе rus_verbs:начертать{}, // начертать в летописи rus_verbs:расцветать{}, // расцветать в подходящих условиях rus_verbs:царствовать{}, // царствовать в южной части материка rus_verbs:накопить{}, // накопить в буфере rus_verbs:закрутиться{}, // закрутиться в рутине rus_verbs:отработать{}, // отработать в забое rus_verbs:обокрасть{}, // обокрасть в автобусе rus_verbs:прокладывать{}, // прокладывать в снегу rus_verbs:ковырять{}, // ковырять в носу rus_verbs:копить{}, // копить в очереди rus_verbs:полечь{}, // полечь в степях rus_verbs:щебетать{}, // щебетать в кустиках rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении rus_verbs:посеять{}, // посеять в огороде rus_verbs:разъезжать{}, // разъезжать в кабриолете rus_verbs:замечаться{}, // замечаться в лесу rus_verbs:просчитать{}, // просчитать в уме rus_verbs:маяться{}, // маяться в командировке rus_verbs:выхватывать{}, // выхватывать в тексте rus_verbs:креститься{}, // креститься в деревенской часовне rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты rus_verbs:настигать{}, // настигать в огороде rus_verbs:разгуливать{}, // разгуливать в роще rus_verbs:насиловать{}, // насиловать в квартире rus_verbs:побороть{}, // побороть в себе rus_verbs:учитывать{}, // учитывать в расчетах rus_verbs:искажать{}, // искажать в заметке rus_verbs:пропить{}, // пропить в кабаке rus_verbs:катать{}, // катать в лодочке rus_verbs:припрятать{}, // припрятать в кармашке rus_verbs:запаниковать{}, // запаниковать в бою rus_verbs:рассыпать{}, // рассыпать в траве rus_verbs:застревать{}, // застревать в ограде rus_verbs:зажигаться{}, // зажигаться в сумерках rus_verbs:жарить{}, // жарить в масле rus_verbs:накапливаться{}, // накапливаться в костях rus_verbs:распуститься{}, // распуститься в горшке rus_verbs:проголосовать{}, // проголосовать в передвижном пункте rus_verbs:странствовать{}, // странствовать в автомобиле rus_verbs:осматриваться{}, // осматриваться в хоромах rus_verbs:разворачивать{}, // разворачивать в спортзале rus_verbs:заскучать{}, // заскучать в самолете rus_verbs:напутать{}, // напутать в расчете rus_verbs:перекусить{}, // перекусить в столовой rus_verbs:спасаться{}, // спасаться в автономной капсуле rus_verbs:посовещаться{}, // посовещаться в комнате rus_verbs:доказываться{}, // доказываться в статье rus_verbs:познаваться{}, // познаваться в беде rus_verbs:загрустить{}, // загрустить в одиночестве rus_verbs:оживить{}, // оживить в памяти rus_verbs:переворачиваться{}, // переворачиваться в гробу rus_verbs:заприметить{}, // заприметить в лесу rus_verbs:отравиться{}, // отравиться в забегаловке rus_verbs:продержать{}, // продержать в клетке rus_verbs:выявить{}, // выявить в костях rus_verbs:заседать{}, // заседать в совете rus_verbs:расплачиваться{}, // расплачиваться в первой кассе rus_verbs:проломить{}, // проломить в двери rus_verbs:подражать{}, // подражать в мелочах rus_verbs:подсчитывать{}, // подсчитывать в уме rus_verbs:опережать{}, // опережать во всем rus_verbs:сформироваться{}, // сформироваться в облаке rus_verbs:укрепиться{}, // укрепиться в мнении rus_verbs:отстоять{}, // отстоять в очереди rus_verbs:развертываться{}, // развертываться в месте испытания rus_verbs:замерзать{}, // замерзать во льду rus_verbs:утопать{}, // утопать в снегу rus_verbs:раскаиваться{}, // раскаиваться в содеянном rus_verbs:организовывать{}, // организовывать в пионерлагере rus_verbs:перевестись{}, // перевестись в наших краях rus_verbs:смешивать{}, // смешивать в блендере rus_verbs:ютиться{}, // ютиться в тесной каморке rus_verbs:прождать{}, // прождать в аудитории rus_verbs:подыскивать{}, // подыскивать в женском общежитии rus_verbs:замочить{}, // замочить в сортире rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке rus_verbs:растирать{}, // растирать в ступке rus_verbs:замедлять{}, // замедлять в парафине rus_verbs:переспать{}, // переспать в палатке rus_verbs:рассекать{}, // рассекать в кабриолете rus_verbs:отыскивать{}, // отыскивать в залежах rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке rus_verbs:укрываться{}, // укрываться в землянке rus_verbs:запечься{}, // запечься в золе rus_verbs:догорать{}, // догорать в темноте rus_verbs:застилать{}, // застилать в коридоре rus_verbs:сыскаться{}, // сыскаться в деревне rus_verbs:переделать{}, // переделать в мастерской rus_verbs:разъяснять{}, // разъяснять в своей лекции rus_verbs:селиться{}, // селиться в центре rus_verbs:оплачивать{}, // оплачивать в магазине rus_verbs:переворачивать{}, // переворачивать в закрытой банке rus_verbs:упражняться{}, // упражняться в остроумии rus_verbs:пометить{}, // пометить в списке rus_verbs:припомниться{}, // припомниться в завещании rus_verbs:приютить{}, // приютить в амбаре rus_verbs:натерпеться{}, // натерпеться в темнице rus_verbs:затеваться{}, // затеваться в клубе rus_verbs:уплывать{}, // уплывать в лодке rus_verbs:скиснуть{}, // скиснуть в бидоне rus_verbs:заколоть{}, // заколоть в боку rus_verbs:замерцать{}, // замерцать в темноте rus_verbs:фиксироваться{}, // фиксироваться в протоколе rus_verbs:запираться{}, // запираться в комнате rus_verbs:съезжаться{}, // съезжаться в каретах rus_verbs:толочься{}, // толочься в ступе rus_verbs:потанцевать{}, // потанцевать в клубе rus_verbs:побродить{}, // побродить в парке rus_verbs:назревать{}, // назревать в коллективе rus_verbs:дохнуть{}, // дохнуть в питомнике rus_verbs:крестить{}, // крестить в деревенской церквушке rus_verbs:рассчитаться{}, // рассчитаться в банке rus_verbs:припарковаться{}, // припарковаться во дворе rus_verbs:отхватить{}, // отхватить в магазинчике rus_verbs:остывать{}, // остывать в холодильнике rus_verbs:составляться{}, // составляться в атмосфере тайны rus_verbs:переваривать{}, // переваривать в тишине rus_verbs:хвастать{}, // хвастать в казино rus_verbs:отрабатывать{}, // отрабатывать в теплице rus_verbs:разлечься{}, // разлечься в кровати rus_verbs:прокручивать{}, // прокручивать в голове rus_verbs:очертить{}, // очертить в воздухе rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей rus_verbs:выявлять{}, // выявлять в боевых условиях rus_verbs:караулить{}, // караулить в лифте rus_verbs:расставлять{}, // расставлять в бойницах rus_verbs:прокрутить{}, // прокрутить в голове rus_verbs:пересказывать{}, // пересказывать в первой главе rus_verbs:задавить{}, // задавить в зародыше rus_verbs:хозяйничать{}, // хозяйничать в холодильнике rus_verbs:хвалиться{}, // хвалиться в детском садике rus_verbs:оперировать{}, // оперировать в полевом госпитале rus_verbs:формулировать{}, // формулировать в следующей главе rus_verbs:застигнуть{}, // застигнуть в неприглядном виде rus_verbs:замурлыкать{}, // замурлыкать в тепле rus_verbs:поддакивать{}, // поддакивать в споре rus_verbs:прочертить{}, // прочертить в воздухе rus_verbs:отменять{}, // отменять в городе коменданский час rus_verbs:колдовать{}, // колдовать в лаборатории rus_verbs:отвозить{}, // отвозить в машине rus_verbs:трахать{}, // трахать в гамаке rus_verbs:повозиться{}, // повозиться в мешке rus_verbs:ремонтировать{}, // ремонтировать в центре rus_verbs:робеть{}, // робеть в гостях rus_verbs:перепробовать{}, // перепробовать в деле инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш }, rus_verbs:покаяться{}, // покаяться в церкви rus_verbs:попрыгать{}, // попрыгать в бассейне rus_verbs:умалчивать{}, // умалчивать в своем докладе rus_verbs:ковыряться{}, // ковыряться в старой технике rus_verbs:расписывать{}, // расписывать в деталях rus_verbs:вязнуть{}, // вязнуть в песке rus_verbs:погрязнуть{}, // погрязнуть в скандалах rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу rus_verbs:зажимать{}, // зажимать в углу rus_verbs:стискивать{}, // стискивать в ладонях rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса rus_verbs:израсходовать{}, // израсходовать в полете rus_verbs:клокотать{}, // клокотать в жерле rus_verbs:обвиняться{}, // обвиняться в растрате rus_verbs:уединиться{}, // уединиться в кладовке rus_verbs:подохнуть{}, // подохнуть в болоте rus_verbs:кипятиться{}, // кипятиться в чайнике rus_verbs:уродиться{}, // уродиться в лесу rus_verbs:продолжиться{}, // продолжиться в баре rus_verbs:расшифровать{}, // расшифровать в специальном устройстве rus_verbs:посапывать{}, // посапывать в кровати rus_verbs:скрючиться{}, // скрючиться в мешке rus_verbs:лютовать{}, // лютовать в отдаленных селах rus_verbs:расписать{}, // расписать в статье rus_verbs:публиковаться{}, // публиковаться в научном журнале rus_verbs:зарегистрировать{}, // зарегистрировать в комитете rus_verbs:прожечь{}, // прожечь в листе rus_verbs:переждать{}, // переждать в окопе rus_verbs:публиковать{}, // публиковать в журнале rus_verbs:морщить{}, // морщить в уголках глаз rus_verbs:спиться{}, // спиться в одиночестве rus_verbs:изведать{}, // изведать в гареме rus_verbs:обмануться{}, // обмануться в ожиданиях rus_verbs:сочетать{}, // сочетать в себе rus_verbs:подрабатывать{}, // подрабатывать в магазине rus_verbs:репетировать{}, // репетировать в студии rus_verbs:рябить{}, // рябить в глазах rus_verbs:намочить{}, // намочить в луже rus_verbs:скатать{}, // скатать в руке rus_verbs:одевать{}, // одевать в магазине rus_verbs:испечь{}, // испечь в духовке rus_verbs:сбрить{}, // сбрить в подмышках rus_verbs:зажужжать{}, // зажужжать в ухе rus_verbs:сберечь{}, // сберечь в тайном месте rus_verbs:согреться{}, // согреться в хижине инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш }, rus_verbs:переплыть{}, // переплыть в лодочке rus_verbs:передохнуть{}, // передохнуть в тени rus_verbs:отсвечивать{}, // отсвечивать в зеркалах rus_verbs:переправляться{}, // переправляться в лодках rus_verbs:накупить{}, // накупить в магазине rus_verbs:проторчать{}, // проторчать в очереди rus_verbs:проскальзывать{}, // проскальзывать в сообщениях rus_verbs:застукать{}, // застукать в солярии rus_verbs:наесть{}, // наесть в отпуске rus_verbs:подвизаться{}, // подвизаться в новом деле rus_verbs:вычистить{}, // вычистить в саду rus_verbs:кормиться{}, // кормиться в лесу rus_verbs:покурить{}, // покурить в саду rus_verbs:понизиться{}, // понизиться в ранге rus_verbs:зимовать{}, // зимовать в избушке rus_verbs:проверяться{}, // проверяться в службе безопасности rus_verbs:подпирать{}, // подпирать в первом забое rus_verbs:кувыркаться{}, // кувыркаться в постели rus_verbs:похрапывать{}, // похрапывать в постели rus_verbs:завязнуть{}, // завязнуть в песке rus_verbs:трактовать{}, // трактовать в исследовательской статье rus_verbs:замедляться{}, // замедляться в тяжелой воде rus_verbs:шастать{}, // шастать в здании rus_verbs:заночевать{}, // заночевать в пути rus_verbs:наметиться{}, // наметиться в исследованиях рака rus_verbs:освежить{}, // освежить в памяти rus_verbs:оспаривать{}, // оспаривать в суде rus_verbs:умещаться{}, // умещаться в ячейке rus_verbs:искупить{}, // искупить в бою rus_verbs:отсиживаться{}, // отсиживаться в тылу rus_verbs:мчать{}, // мчать в кабриолете rus_verbs:обличать{}, // обличать в своем выступлении rus_verbs:сгнить{}, // сгнить в тюряге rus_verbs:опробовать{}, // опробовать в деле rus_verbs:тренировать{}, // тренировать в зале rus_verbs:прославить{}, // прославить в академии rus_verbs:учитываться{}, // учитываться в дипломной работе rus_verbs:повеселиться{}, // повеселиться в лагере rus_verbs:поумнеть{}, // поумнеть в карцере rus_verbs:перестрелять{}, // перестрелять в воздухе rus_verbs:проведать{}, // проведать в больнице rus_verbs:измучиться{}, // измучиться в деревне rus_verbs:прощупать{}, // прощупать в глубине rus_verbs:изготовлять{}, // изготовлять в сарае rus_verbs:свирепствовать{}, // свирепствовать в популяции rus_verbs:иссякать{}, // иссякать в источнике rus_verbs:гнездиться{}, // гнездиться в дупле rus_verbs:разогнаться{}, // разогнаться в спортивной машине rus_verbs:опознавать{}, // опознавать в неизвестном rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках rus_verbs:редактировать{}, // редактировать в редакторе rus_verbs:покупаться{}, // покупаться в магазине rus_verbs:промышлять{}, // промышлять в роще rus_verbs:растягиваться{}, // растягиваться в коридоре rus_verbs:приобретаться{}, // приобретаться в антикварных лавках инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш }, rus_verbs:запечатлеться{}, // запечатлеться в мозгу rus_verbs:укрывать{}, // укрывать в подвале rus_verbs:закрепиться{}, // закрепиться в первой башне rus_verbs:освежать{}, // освежать в памяти rus_verbs:громыхать{}, // громыхать в ванной инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш }, rus_verbs:добываться{}, // добываться в шахтах rus_verbs:растворить{}, // растворить в кислоте rus_verbs:приплясывать{}, // приплясывать в гримерке rus_verbs:доживать{}, // доживать в доме престарелых rus_verbs:отпраздновать{}, // отпраздновать в ресторане rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях rus_verbs:помыть{}, // помыть в проточной воде инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш }, прилагательное:увязавший{ вид:несоверш }, rus_verbs:наличествовать{}, // наличествовать в запаснике rus_verbs:нащупывать{}, // нащупывать в кармане rus_verbs:повествоваться{}, // повествоваться в рассказе rus_verbs:отремонтировать{}, // отремонтировать в техцентре rus_verbs:покалывать{}, // покалывать в правом боку rus_verbs:сиживать{}, // сиживать в саду rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях rus_verbs:укрепляться{}, // укрепляться в мнении rus_verbs:разниться{}, // разниться во взглядах rus_verbs:сполоснуть{}, // сполоснуть в водичке rus_verbs:скупать{}, // скупать в магазине rus_verbs:почесывать{}, // почесывать в паху rus_verbs:оформлять{}, // оформлять в конторе rus_verbs:распускаться{}, // распускаться в садах rus_verbs:зарябить{}, // зарябить в глазах rus_verbs:загореть{}, // загореть в Испании rus_verbs:очищаться{}, // очищаться в баке rus_verbs:остудить{}, // остудить в холодной воде rus_verbs:разбомбить{}, // разбомбить в горах rus_verbs:издохнуть{}, // издохнуть в бедности rus_verbs:проехаться{}, // проехаться в новой машине rus_verbs:задействовать{}, // задействовать в анализе rus_verbs:произрастать{}, // произрастать в степи rus_verbs:разуться{}, // разуться в прихожей rus_verbs:сооружать{}, // сооружать в огороде rus_verbs:зачитывать{}, // зачитывать в суде rus_verbs:состязаться{}, // состязаться в остроумии rus_verbs:ополоснуть{}, // ополоснуть в молоке rus_verbs:уместиться{}, // уместиться в кармане rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом rus_verbs:стираться{}, // стираться в стиральной машине rus_verbs:искупаться{}, // искупаться в прохладной реке rus_verbs:курировать{}, // курировать в правительстве rus_verbs:закупить{}, // закупить в магазине rus_verbs:плодиться{}, // плодиться в подходящих условиях rus_verbs:горланить{}, // горланить в парке rus_verbs:першить{}, // першить в горле rus_verbs:пригрезиться{}, // пригрезиться во сне rus_verbs:исправлять{}, // исправлять в тетрадке rus_verbs:расслабляться{}, // расслабляться в гамаке rus_verbs:скапливаться{}, // скапливаться в нижней части rus_verbs:сплетничать{}, // сплетничают в комнате rus_verbs:раздевать{}, // раздевать в кабинке rus_verbs:окопаться{}, // окопаться в лесу rus_verbs:загорать{}, // загорать в Испании rus_verbs:подпевать{}, // подпевать в церковном хоре rus_verbs:прожужжать{}, // прожужжать в динамике rus_verbs:изучаться{}, // изучаться в дикой природе rus_verbs:заклубиться{}, // заклубиться в воздухе rus_verbs:подметать{}, // подметать в зале rus_verbs:подозреваться{}, // подозреваться в совершении кражи rus_verbs:обогащать{}, // обогащать в специальном аппарате rus_verbs:издаться{}, // издаться в другом издательстве rus_verbs:справить{}, // справить в кустах нужду rus_verbs:помыться{}, // помыться в бане rus_verbs:проскакивать{}, // проскакивать в словах rus_verbs:попивать{}, // попивать в кафе чай rus_verbs:оформляться{}, // оформляться в регистратуре rus_verbs:чирикать{}, // чирикать в кустах rus_verbs:скупить{}, // скупить в магазинах rus_verbs:переночевать{}, // переночевать в гостинице rus_verbs:концентрироваться{}, // концентрироваться в пробирке rus_verbs:одичать{}, // одичать в лесу rus_verbs:ковырнуть{}, // ковырнуть в ухе rus_verbs:затеплиться{}, // затеплиться в глубине души rus_verbs:разгрести{}, // разгрести в задачах залежи rus_verbs:застопориться{}, // застопориться в начале списка rus_verbs:перечисляться{}, // перечисляться во введении rus_verbs:покататься{}, // покататься в парке аттракционов rus_verbs:изловить{}, // изловить в поле rus_verbs:прославлять{}, // прославлять в стихах rus_verbs:промочить{}, // промочить в луже rus_verbs:поделывать{}, // поделывать в отпуске rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии rus_verbs:подстеречь{}, // подстеречь в подъезде rus_verbs:прикупить{}, // прикупить в магазине rus_verbs:перемешивать{}, // перемешивать в кастрюле rus_verbs:тискать{}, // тискать в углу rus_verbs:купать{}, // купать в теплой водичке rus_verbs:завариться{}, // завариться в стакане rus_verbs:притулиться{}, // притулиться в углу rus_verbs:пострелять{}, // пострелять в тире rus_verbs:навесить{}, // навесить в больнице инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш }, rus_verbs:нежиться{}, // нежится в постельке rus_verbs:притомиться{}, // притомиться в школе rus_verbs:раздвоиться{}, // раздвоиться в глазах rus_verbs:навалить{}, // навалить в углу rus_verbs:замуровать{}, // замуровать в склепе rus_verbs:поселяться{}, // поселяться в кроне дуба rus_verbs:потягиваться{}, // потягиваться в кровати rus_verbs:укачать{}, // укачать в поезде rus_verbs:отлеживаться{}, // отлеживаться в гамаке rus_verbs:разменять{}, // разменять в кассе rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде rus_verbs:ржаветь{}, // ржаветь в воде rus_verbs:уличить{}, // уличить в плагиате rus_verbs:мутиться{}, // мутиться в голове rus_verbs:растворять{}, // растворять в бензоле rus_verbs:двоиться{}, // двоиться в глазах rus_verbs:оговорить{}, // оговорить в договоре rus_verbs:подделать{}, // подделать в документе rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети rus_verbs:растолстеть{}, // растолстеть в талии rus_verbs:повоевать{}, // повоевать в городских условиях rus_verbs:прибраться{}, // гнушаться прибраться в хлеву rus_verbs:поглощаться{}, // поглощаться в металлической фольге rus_verbs:ухать{}, // ухать в лесу rus_verbs:подписываться{}, // подписываться в петиции rus_verbs:покатать{}, // покатать в машинке rus_verbs:излечиться{}, // излечиться в клинике rus_verbs:трепыхаться{}, // трепыхаться в мешке rus_verbs:кипятить{}, // кипятить в кастрюле rus_verbs:понастроить{}, // понастроить в прибрежной зоне rus_verbs:перебывать{}, // перебывать во всех европейских столицах rus_verbs:оглашать{}, // оглашать в итоговой части rus_verbs:преуспевать{}, // преуспевать в новом бизнесе rus_verbs:консультироваться{}, // консультироваться в техподдержке rus_verbs:накапливать{}, // накапливать в печени rus_verbs:перемешать{}, // перемешать в контейнере rus_verbs:наследить{}, // наследить в коридоре rus_verbs:выявиться{}, // выявиться в результе rus_verbs:забулькать{}, // забулькать в болоте rus_verbs:отваривать{}, // отваривать в молоке rus_verbs:запутываться{}, // запутываться в веревках rus_verbs:нагреться{}, // нагреться в микроволновой печке rus_verbs:рыбачить{}, // рыбачить в открытом море rus_verbs:укорениться{}, // укорениться в сознании широких народных масс rus_verbs:умывать{}, // умывать в тазике rus_verbs:защекотать{}, // защекотать в носу rus_verbs:заходиться{}, // заходиться в плаче инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш }, деепричастие:искупав{}, деепричастие:искупая{}, rus_verbs:заморозить{}, // заморозить в холодильнике rus_verbs:закреплять{}, // закреплять в металлическом держателе rus_verbs:расхватать{}, // расхватать в магазине rus_verbs:истязать{}, // истязать в тюремном подвале rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете rus_verbs:подогреть{}, // подогрей в микроволновке rus_verbs:подогревать{}, rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку rus_verbs:проделать{}, // проделать в стене дыру инфинитив:жениться{ вид:соверш }, // жениться в Техасе инфинитив:жениться{ вид:несоверш }, глагол:жениться{ вид:соверш }, глагол:жениться{ вид:несоверш }, деепричастие:женившись{}, деепричастие:женясь{}, прилагательное:женатый{}, прилагательное:женившийся{вид:соверш}, прилагательное:женящийся{}, rus_verbs:всхрапнуть{}, // всхрапнуть во сне rus_verbs:всхрапывать{}, // всхрапывать во сне rus_verbs:ворочаться{}, // Собака ворочается во сне rus_verbs:воссоздаваться{}, // воссоздаваться в памяти rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу инфинитив:атаковать{ вид:соверш }, глагол:атаковать{ вид:несоверш }, глагол:атаковать{ вид:соверш }, прилагательное:атакованный{}, прилагательное:атаковавший{}, прилагательное:атакующий{}, инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени инфинитив:аккумулировать{вид:соверш}, глагол:аккумулировать{вид:несоверш}, глагол:аккумулировать{вид:соверш}, прилагательное:аккумулированный{}, прилагательное:аккумулирующий{}, //прилагательное:аккумулировавший{ вид:несоверш }, прилагательное:аккумулировавший{ вид:соверш }, rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию rus_verbs:вырасти{}, // Он вырос в глазах коллег. rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо. rus_verbs:убить{}, // убить в себе зверя инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани инфинитив:абсорбироваться{ вид:несоверш }, глагол:абсорбироваться{ вид:соверш }, глагол:абсорбироваться{ вид:несоверш }, rus_verbs:поставить{}, // поставить в углу rus_verbs:сжимать{}, // сжимать в кулаке rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы инфинитив:активизироваться{ вид:соверш }, глагол:активизироваться{ вид:несоверш }, глагол:активизироваться{ вид:соверш }, rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе rus_verbs:базировать{}, // установка будет базирована в лесу rus_verbs:барахтаться{}, // дети барахтались в воде rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины rus_verbs:блуждать{}, // Туристы блуждали в лесу rus_verbs:брать{}, // Жена берет деньги в тумбочке rus_verbs:бродить{}, // парочки бродили в парке rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде rus_verbs:вариться{}, // Курица варится в кастрюле rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году rus_verbs:прокручиваться{}, // Ключ прокручивается в замке rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке rus_verbs:храниться{}, // Настройки хранятся в текстовом файле rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле rus_verbs:витать{}, // Мальчик витает в облаках rus_verbs:владычествовать{}, // Король владычествует в стране rus_verbs:властвовать{}, // Олигархи властвовали в стране rus_verbs:возбудить{}, // возбудить в сердце тоску rus_verbs:возбуждать{}, // возбуждать в сердце тоску rus_verbs:возвыситься{}, // возвыситься в глазах современников rus_verbs:возжечь{}, // возжечь в храме огонь rus_verbs:возжечься{}, // Огонь возжёгся в храме rus_verbs:возжигать{}, // возжигать в храме огонь rus_verbs:возжигаться{}, // Огонь возжигается в храме rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь rus_verbs:вознамериться{}, // вознамериться уйти в монастырь rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове rus_verbs:возникнуть{}, // Новые идейки возникли в голове rus_verbs:возродиться{}, // возродиться в новом качестве rus_verbs:возрождать{}, // возрождать в новом качестве rus_verbs:возрождаться{}, // возрождаться в новом амплуа rus_verbs:ворошить{}, // ворошить в камине кочергой золу rus_verbs:воспевать{}, // Поэты воспевают героев в одах rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами rus_verbs:воспеть{}, // Поэты воспели в этой оде героев rus_verbs:воспретить{}, // воспретить в помещении азартные игры rus_verbs:восславить{}, // Поэты восславили в одах rus_verbs:восславлять{}, // Поэты восславляют в одах rus_verbs:восславляться{}, // Героя восславляются в одах rus_verbs:воссоздать{}, // воссоздает в памяти образ человека rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека rus_verbs:воссоздаться{}, // воссоздаться в памяти rus_verbs:вскипятить{}, // вскипятить в чайнике воду rus_verbs:вскипятиться{}, // вскипятиться в чайнике rus_verbs:встретить{}, // встретить в классе старого приятеля rus_verbs:встретиться{}, // встретиться в классе rus_verbs:встречать{}, // встречать в лесу голодного медведя rus_verbs:встречаться{}, // встречаться в кафе rus_verbs:выбривать{}, // выбривать что-то в подмышках rus_verbs:выбрить{}, // выбрить что-то в паху rus_verbs:вывалять{}, // вывалять кого-то в грязи rus_verbs:вываляться{}, // вываляться в грязи rus_verbs:вываривать{}, // вываривать в молоке rus_verbs:вывариваться{}, // вывариваться в молоке rus_verbs:выварить{}, // выварить в молоке rus_verbs:вывариться{}, // вывариться в молоке rus_verbs:выгрызать{}, // выгрызать в сыре отверствие rus_verbs:выгрызть{}, // выгрызть в сыре отверстие rus_verbs:выгуливать{}, // выгуливать в парке собаку rus_verbs:выгулять{}, // выгулять в парке собаку rus_verbs:выдолбить{}, // выдолбить в стволе углубление rus_verbs:выжить{}, // выжить в пустыне rus_verbs:Выискать{}, // Выискать в программе ошибку rus_verbs:выискаться{}, // Ошибка выискалась в программе rus_verbs:выискивать{}, // выискивать в программе ошибку rus_verbs:выискиваться{}, // выискиваться в программе rus_verbs:выкраивать{}, // выкраивать в расписании время rus_verbs:выкраиваться{}, // выкраиваться в расписании инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере глагол:выкупаться{вид:соверш}, rus_verbs:выловить{}, // выловить в пруду rus_verbs:вымачивать{}, // вымачивать в молоке rus_verbs:вымачиваться{}, // вымачиваться в молоке rus_verbs:вынюхивать{}, // вынюхивать в траве следы rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду rus_verbs:выпачкаться{}, // выпачкаться в грязи rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков rus_verbs:выращивать{}, // выращивать в теплице помидоры rus_verbs:выращиваться{}, // выращиваться в теплице rus_verbs:вырыть{}, // вырыть в земле глубокую яму rus_verbs:высадить{}, // высадить в пустынной местности rus_verbs:высадиться{}, // высадиться в пустынной местности rus_verbs:высаживать{}, // высаживать в пустыне rus_verbs:высверливать{}, // высверливать в доске отверствие rus_verbs:высверливаться{}, // высверливаться в стене rus_verbs:высверлить{}, // высверлить в стене отверствие rus_verbs:высверлиться{}, // высверлиться в стене rus_verbs:выскоблить{}, // выскоблить в столешнице канавку rus_verbs:высматривать{}, // высматривать в темноте rus_verbs:заметить{}, // заметить в помещении rus_verbs:оказаться{}, // оказаться в первых рядах rus_verbs:душить{}, // душить в объятиях rus_verbs:оставаться{}, // оставаться в классе rus_verbs:появиться{}, // впервые появиться в фильме rus_verbs:лежать{}, // лежать в футляре rus_verbs:раздаться{}, // раздаться в плечах rus_verbs:ждать{}, // ждать в здании вокзала rus_verbs:жить{}, // жить в трущобах rus_verbs:постелить{}, // постелить в прихожей rus_verbs:оказываться{}, // оказываться в неприятной ситуации rus_verbs:держать{}, // держать в голове rus_verbs:обнаружить{}, // обнаружить в себе способность rus_verbs:начинать{}, // начинать в лаборатории rus_verbs:рассказывать{}, // рассказывать в лицах rus_verbs:ожидать{}, // ожидать в помещении rus_verbs:продолжить{}, // продолжить в помещении rus_verbs:состоять{}, // состоять в группе rus_verbs:родиться{}, // родиться в рубашке rus_verbs:искать{}, // искать в кармане rus_verbs:иметься{}, // иметься в наличии rus_verbs:говориться{}, // говориться в среде панков rus_verbs:клясться{}, // клясться в верности rus_verbs:узнавать{}, // узнавать в нем своего сына rus_verbs:признаться{}, // признаться в ошибке rus_verbs:сомневаться{}, // сомневаться в искренности rus_verbs:толочь{}, // толочь в ступе rus_verbs:понадобиться{}, // понадобиться в суде rus_verbs:служить{}, // служить в пехоте rus_verbs:потолочь{}, // потолочь в ступе rus_verbs:появляться{}, // появляться в театре rus_verbs:сжать{}, // сжать в объятиях rus_verbs:действовать{}, // действовать в постановке rus_verbs:селить{}, // селить в гостинице rus_verbs:поймать{}, // поймать в лесу rus_verbs:увидать{}, // увидать в толпе rus_verbs:подождать{}, // подождать в кабинете rus_verbs:прочесть{}, // прочесть в глазах rus_verbs:тонуть{}, // тонуть в реке rus_verbs:ощущать{}, // ощущать в животе rus_verbs:ошибиться{}, // ошибиться в расчетах rus_verbs:отметить{}, // отметить в списке rus_verbs:показывать{}, // показывать в динамике rus_verbs:скрыться{}, // скрыться в траве rus_verbs:убедиться{}, // убедиться в корректности rus_verbs:прозвучать{}, // прозвучать в наушниках rus_verbs:разговаривать{}, // разговаривать в фойе rus_verbs:издать{}, // издать в России rus_verbs:прочитать{}, // прочитать в газете rus_verbs:попробовать{}, // попробовать в деле rus_verbs:замечать{}, // замечать в программе ошибку rus_verbs:нести{}, // нести в руках rus_verbs:пропасть{}, // пропасть в плену rus_verbs:носить{}, // носить в кармане rus_verbs:гореть{}, // гореть в аду rus_verbs:поправить{}, // поправить в программе rus_verbs:застыть{}, // застыть в неудобной позе rus_verbs:получать{}, // получать в кассе rus_verbs:потребоваться{}, // потребоваться в работе rus_verbs:спрятать{}, // спрятать в шкафу rus_verbs:учиться{}, // учиться в институте rus_verbs:развернуться{}, // развернуться в коридоре rus_verbs:подозревать{}, // подозревать в мошенничестве rus_verbs:играть{}, // играть в команде rus_verbs:сыграть{}, // сыграть в команде rus_verbs:строить{}, // строить в деревне rus_verbs:устроить{}, // устроить в доме вечеринку rus_verbs:находить{}, // находить в лесу rus_verbs:нуждаться{}, // нуждаться в деньгах rus_verbs:испытать{}, // испытать в рабочей обстановке rus_verbs:мелькнуть{}, // мелькнуть в прицеле rus_verbs:очутиться{}, // очутиться в закрытом помещении инфинитив:использовать{вид:соверш}, // использовать в работе инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, глагол:использовать{вид:соверш}, rus_verbs:лететь{}, // лететь в самолете rus_verbs:смеяться{}, // смеяться в цирке rus_verbs:ездить{}, // ездить в лимузине rus_verbs:заснуть{}, // заснуть в неудобной позе rus_verbs:застать{}, // застать в неформальной обстановке rus_verbs:очнуться{}, // очнуться в незнакомой обстановке rus_verbs:твориться{}, // Что творится в закрытой зоне rus_verbs:разглядеть{}, // разглядеть в темноте rus_verbs:изучать{}, // изучать в естественных условиях rus_verbs:удержаться{}, // удержаться в седле rus_verbs:побывать{}, // побывать в зоопарке rus_verbs:уловить{}, // уловить в словах нотку отчаяния rus_verbs:приобрести{}, // приобрести в лавке rus_verbs:исчезать{}, // исчезать в тумане rus_verbs:уверять{}, // уверять в своей невиновности rus_verbs:продолжаться{}, // продолжаться в воздухе rus_verbs:открывать{}, // открывать в городе новый стадион rus_verbs:поддержать{}, // поддержать в парке порядок rus_verbs:солить{}, // солить в бочке rus_verbs:прожить{}, // прожить в деревне rus_verbs:создавать{}, // создавать в театре rus_verbs:обсуждать{}, // обсуждать в коллективе rus_verbs:заказать{}, // заказать в магазине rus_verbs:отыскать{}, // отыскать в гараже rus_verbs:уснуть{}, // уснуть в кресле rus_verbs:задержаться{}, // задержаться в театре rus_verbs:подобрать{}, // подобрать в коллекции rus_verbs:пробовать{}, // пробовать в работе rus_verbs:курить{}, // курить в закрытом помещении rus_verbs:устраивать{}, // устраивать в лесу засаду rus_verbs:установить{}, // установить в багажнике rus_verbs:запереть{}, // запереть в сарае rus_verbs:содержать{}, // содержать в достатке rus_verbs:синеть{}, // синеть в кислородной атмосфере rus_verbs:слышаться{}, // слышаться в голосе rus_verbs:закрыться{}, // закрыться в здании rus_verbs:скрываться{}, // скрываться в квартире rus_verbs:родить{}, // родить в больнице rus_verbs:описать{}, // описать в заметках rus_verbs:перехватить{}, // перехватить в коридоре rus_verbs:менять{}, // менять в магазине rus_verbs:скрывать{}, // скрывать в чужой квартире rus_verbs:стиснуть{}, // стиснуть в стальных объятиях rus_verbs:останавливаться{}, // останавливаться в гостинице rus_verbs:мелькать{}, // мелькать в телевизоре rus_verbs:присутствовать{}, // присутствовать в аудитории rus_verbs:украсть{}, // украсть в магазине rus_verbs:победить{}, // победить в войне rus_verbs:расположиться{}, // расположиться в гостинице rus_verbs:упомянуть{}, // упомянуть в своей книге rus_verbs:плыть{}, // плыть в старой бочке rus_verbs:нащупать{}, // нащупать в глубине rus_verbs:проявляться{}, // проявляться в работе rus_verbs:затихнуть{}, // затихнуть в норе rus_verbs:построить{}, // построить в гараже rus_verbs:поддерживать{}, // поддерживать в исправном состоянии rus_verbs:заработать{}, // заработать в стартапе rus_verbs:сломать{}, // сломать в суставе rus_verbs:снимать{}, // снимать в гардеробе rus_verbs:сохранить{}, // сохранить в коллекции rus_verbs:располагаться{}, // располагаться в отдельном кабинете rus_verbs:сражаться{}, // сражаться в честном бою rus_verbs:спускаться{}, // спускаться в батискафе rus_verbs:уничтожить{}, // уничтожить в схроне rus_verbs:изучить{}, // изучить в естественных условиях rus_verbs:рождаться{}, // рождаться в муках rus_verbs:пребывать{}, // пребывать в прострации rus_verbs:прилететь{}, // прилететь в аэробусе rus_verbs:догнать{}, // догнать в переулке rus_verbs:изобразить{}, // изобразить в танце rus_verbs:проехать{}, // проехать в легковушке rus_verbs:убедить{}, // убедить в разумности rus_verbs:приготовить{}, // приготовить в духовке rus_verbs:собирать{}, // собирать в лесу rus_verbs:поплыть{}, // поплыть в катере rus_verbs:доверять{}, // доверять в управлении rus_verbs:разобраться{}, // разобраться в законах rus_verbs:ловить{}, // ловить в озере rus_verbs:проесть{}, // проесть в куске металла отверстие rus_verbs:спрятаться{}, // спрятаться в подвале rus_verbs:провозгласить{}, // провозгласить в речи rus_verbs:изложить{}, // изложить в своём выступлении rus_verbs:замяться{}, // замяться в коридоре rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна rus_verbs:хранить{}, // хранить в шкатулке rus_verbs:шутить{}, // шутить в классе глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях инфинитив:рассыпаться{ aux stress="рассып^аться" }, rus_verbs:чертить{}, // чертить в тетрадке rus_verbs:отразиться{}, // отразиться в аттестате rus_verbs:греть{}, // греть в микроволновке rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса rus_verbs:рассуждать{}, // Автор рассуждает в своей статье rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда rus_verbs:окружать{}, // окружать в лесу rus_verbs:сопровождать{}, // сопровождать в операции rus_verbs:заканчиваться{}, // заканчиваться в дороге rus_verbs:поселиться{}, // поселиться в загородном доме rus_verbs:охватывать{}, // охватывать в хронологии rus_verbs:запеть{}, // запеть в кино инфинитив:провозить{вид:несоверш}, // провозить в багаже глагол:провозить{вид:несоверш}, rus_verbs:мочить{}, // мочить в сортире rus_verbs:перевернуться{}, // перевернуться в полёте rus_verbs:улететь{}, // улететь в теплые края rus_verbs:сдержать{}, // сдержать в руках rus_verbs:преследовать{}, // преследовать в любой другой стране rus_verbs:драться{}, // драться в баре rus_verbs:просидеть{}, // просидеть в классе rus_verbs:убираться{}, // убираться в квартире rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения rus_verbs:пугать{}, // пугать в прессе rus_verbs:отреагировать{}, // отреагировать в прессе rus_verbs:проверять{}, // проверять в аппарате rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив rus_verbs:летать{}, // летать в комфортабельном частном самолёте rus_verbs:толпиться{}, // толпиться в фойе rus_verbs:плавать{}, // плавать в специальном костюме rus_verbs:пробыть{}, // пробыть в воде слишком долго rus_verbs:прикинуть{}, // прикинуть в уме rus_verbs:застрять{}, // застрять в лифте rus_verbs:метаться{}, // метаться в кровате rus_verbs:сжечь{}, // сжечь в печке rus_verbs:расслабиться{}, // расслабиться в ванной rus_verbs:услыхать{}, // услыхать в автобусе rus_verbs:удержать{}, // удержать в вертикальном положении rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы rus_verbs:рассмотреть{}, // рассмотреть в капле воды rus_verbs:просмотреть{}, // просмотреть в браузере rus_verbs:учесть{}, // учесть в планах rus_verbs:уезжать{}, // уезжать в чьей-то машине rus_verbs:похоронить{}, // похоронить в мерзлой земле rus_verbs:растянуться{}, // растянуться в расслабленной позе rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке rus_verbs:гулять{}, // гулять в парке rus_verbs:утонуть{}, // утонуть в реке rus_verbs:зажать{}, // зажать в медвежьих объятиях rus_verbs:усомниться{}, // усомниться в объективности rus_verbs:танцевать{}, // танцевать в спортзале rus_verbs:проноситься{}, // проноситься в голове rus_verbs:трудиться{}, // трудиться в кооперативе глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный }, rus_verbs:сушить{}, // сушить в сушильном шкафу rus_verbs:зашевелиться{}, // зашевелиться в траве rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке rus_verbs:промелькнуть{}, // промелькнуть в окне rus_verbs:поучаствовать{}, // поучаствовать в обсуждении rus_verbs:закрыть{}, // закрыть в комнате rus_verbs:запирать{}, // запирать в комнате rus_verbs:закрывать{}, // закрывать в доме rus_verbs:заблокировать{}, // заблокировать в доме rus_verbs:зацвести{}, // В садах зацвела сирень rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу. rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе rus_verbs:стоять{}, // войска, стоявшие в Риме rus_verbs:закалить{}, // ветераны, закаленные в боях rus_verbs:выступать{}, // пришлось выступать в тюрьме. rus_verbs:выступить{}, // пришлось выступить в тюрьме. rus_verbs:закопошиться{}, // Мыши закопошились в траве rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре rus_verbs:закрываться{}, // закрываться в комнате rus_verbs:провалиться{}, // провалиться в прокате деепричастие:авторизируясь{ вид:несоверш }, глагол:авторизироваться{ вид:несоверш }, инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе rus_verbs:существовать{}, // существовать в вакууме деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, // находиться в вакууме rus_verbs:регистрировать{}, // регистрировать в инспекции глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш }, инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции rus_verbs:поковыряться{}, // поковыряться в носу rus_verbs:оттаять{}, // оттаять в кипятке rus_verbs:распинаться{}, // распинаться в проклятиях rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения. прилагательное:несчастный{}, // Он очень несчастен в семейной жизни. rus_verbs:объясниться{}, // Он объяснился в любви. прилагательное:нетвердый{}, // Он нетвёрд в истории. rus_verbs:заниматься{}, // Он занимается в читальном зале. rus_verbs:вращаться{}, // Он вращается в учёных кругах. прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне. rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры. rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения. rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев. rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях. rus_verbs:продолжать{}, // Продолжайте в том же духе. rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:болтать{}, // Не болтай в присутствии начальника! rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника! rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине. rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах rus_verbs:сходиться{}, // Все дороги сходятся в Москве rus_verbs:убирать{}, // убирать в комнате rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста rus_verbs:уединяться{}, // уединяться в пустыне rus_verbs:уживаться{}, // уживаться в одном коллективе rus_verbs:укорять{}, // укорять друга в забывчивости rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем rus_verbs:работать{}, // Я работаю в театре. rus_verbs:признать{}, // Я признал в нём старого друга. rus_verbs:преподавать{}, // Я преподаю в университете. rus_verbs:понимать{}, // Я плохо понимаю в живописи. rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа rus_verbs:замереть{}, // вся толпа замерла в восхищении rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле. rus_verbs:идти{}, // Я иду в неопределённом направлении. rus_verbs:заболеть{}, // Я заболел в дороге. rus_verbs:ехать{}, // Я еду в автобусе rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю. rus_verbs:провести{}, // Юные годы он провёл в Италии. rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти. rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении. rus_verbs:произойти{}, // Это произошло в одном городе в Японии. rus_verbs:привидеться{}, // Это мне привиделось во сне. rus_verbs:держаться{}, // Это дело держится в большом секрете. rus_verbs:привиться{}, // Это выражение не привилось в русском языке. rus_verbs:восстановиться{}, // Эти писатели восстановились в правах. rus_verbs:быть{}, // Эта книга есть в любом книжном магазине. прилагательное:популярный{}, // Эта идея очень популярна в массах. rus_verbs:шуметь{}, // Шумит в голове. rus_verbs:остаться{}, // Шляпа осталась в поезде. rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях. rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе. rus_verbs:пересохнуть{}, // У меня в горле пересохло. rus_verbs:щекотать{}, // У меня в горле щекочет. rus_verbs:колоть{}, // У меня в боку колет. прилагательное:свежий{}, // Событие ещё свежо в памяти. rus_verbs:собрать{}, // Соберите всех учеников во дворе. rus_verbs:белеть{}, // Снег белеет в горах. rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте? rus_verbs:таять{}, // Сахар тает в кипятке. rus_verbs:жать{}, // Сапог жмёт в подъёме. rus_verbs:возиться{}, // Ребята возятся в углу. rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме. rus_verbs:кружиться{}, // Они кружились в вальсе. rus_verbs:выставлять{}, // Они выставляют его в смешном виде. rus_verbs:бывать{}, // Она часто бывает в обществе. rus_verbs:петь{}, // Она поёт в опере. rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях. rus_verbs:валяться{}, // Вещи валялись в беспорядке. rus_verbs:пройти{}, // Весь день прошёл в беготне. rus_verbs:продавать{}, // В этом магазине продают обувь. rus_verbs:заключаться{}, // В этом заключается вся сущность. rus_verbs:звенеть{}, // В ушах звенит. rus_verbs:проступить{}, // В тумане проступили очертания корабля. rus_verbs:бить{}, // В саду бьёт фонтан. rus_verbs:проскользнуть{}, // В речи проскользнул упрёк. rus_verbs:оставить{}, // Не оставь товарища в опасности. rus_verbs:прогулять{}, // Мы прогуляли час в парке. rus_verbs:перебить{}, // Мы перебили врагов в бою. rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице. rus_verbs:видеть{}, // Он многое видел в жизни. // глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере. rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах. rus_verbs:кинуть{}, // Он кинул меня в беде. rus_verbs:приходить{}, // Приходи в сентябре rus_verbs:воскрешать{}, // воскрешать в памяти rus_verbs:соединять{}, // соединять в себе rus_verbs:разбираться{}, // умение разбираться в вещах rus_verbs:делать{}, // В её комнате делали обыск. rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина. rus_verbs:начаться{}, // В деревне начались полевые работы. rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль. rus_verbs:вертеться{}, // В голове вертится вчерашний разговор. rus_verbs:веять{}, // В воздухе веет прохладой. rus_verbs:висеть{}, // В воздухе висит зной. rus_verbs:носиться{}, // В воздухе носятся комары. rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее rus_verbs:воскресить{}, // воскресить в памяти rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина прилагательное:уверенный{ причастие }, // Она уверена в своих силах. прилагательное:постоянный{}, // Она постоянна во вкусах. прилагательное:сильный{}, // Он не силён в математике. прилагательное:повинный{}, // Он не повинен в этом. прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве. rus_verbs:сесть{}, // Она села в тени rus_verbs:заливаться{}, // в нашем парке заливаются соловьи rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени // rus_verbs:расти{}, // дерево, растущее в лесу rus_verbs:происходить{}, // что происходит в поликлиннике rus_verbs:спать{}, // кто спит в моей кровати rus_verbs:мыть{}, // мыть машину в саду ГЛ_ИНФ(царить), // В воздухе царило безмолвие ГЛ_ИНФ(мести), // мести в прихожей пол ГЛ_ИНФ(прятать), // прятать в яме ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне. // ГЛ_ИНФ(собраться), // собраться в порту ГЛ_ИНФ(случиться), // что-то случилось в больнице ГЛ_ИНФ(зажечься), // в небе зажглись звёзды ГЛ_ИНФ(купить), // купи молока в магазине прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР } // Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds fact гл_предл { if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } } then return true } // С локативом: // собраться в порту fact гл_предл { if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } } then return true } #endregion Предложный #region Винительный // Для глаголов движения с выраженным направлением действия может присоединяться // предложный паттерн с винительным падежом. wordentry_set Гл_В_Вин = { rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок. глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе. глагол:ввергать{}, инфинитив:ввергнуть{}, инфинитив:ввергать{}, rus_verbs:двинуться{}, // Двинулись в путь и мы. rus_verbs:сплавать{}, // Сплавать в Россию! rus_verbs:уложиться{}, // Уложиться в воскресенье. rus_verbs:спешить{}, // Спешите в Лондон rus_verbs:кинуть{}, // Киньте в море. rus_verbs:проситься{}, // Просилась в Никарагуа. rus_verbs:притопать{}, // Притопал в Будапешт. rus_verbs:скататься{}, // Скатался в Красноярск. rus_verbs:соскользнуть{}, // Соскользнул в пике. rus_verbs:соскальзывать{}, rus_verbs:играть{}, // Играл в дутье. глагол:айда{}, // Айда в каморы. rus_verbs:отзывать{}, // Отзывали в Москву... rus_verbs:сообщаться{}, // Сообщается в Лондон. rus_verbs:вдуматься{}, // Вдумайтесь в них. rus_verbs:проехать{}, // Проехать в Лунево... rus_verbs:спрыгивать{}, // Спрыгиваем в него. rus_verbs:верить{}, // Верю в вас! rus_verbs:прибыть{}, // Прибыл в Подмосковье. rus_verbs:переходить{}, // Переходите в школу. rus_verbs:доложить{}, // Доложили в Москву. rus_verbs:подаваться{}, // Подаваться в Россию? rus_verbs:спрыгнуть{}, // Спрыгнул в него. rus_verbs:вывезти{}, // Вывезли в Китай. rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю. rus_verbs:пропихнуть{}, rus_verbs:транспортироваться{}, rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения rus_verbs:дуть{}, rus_verbs:БОГАТЕТЬ{}, // rus_verbs:РАЗБОГАТЕТЬ{}, // rus_verbs:ВОЗРАСТАТЬ{}, // rus_verbs:ВОЗРАСТИ{}, // rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ) rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ) rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ) rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ) rus_verbs:ЗАМАНИВАТЬ{}, rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ) rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ) rus_verbs:ВРУБАТЬСЯ{}, rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ) rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ) rus_verbs:ОБЛАЧАТЬ{}, rus_verbs:ОБЛАЧИТЬСЯ{}, rus_verbs:ОБЛАЧАТЬСЯ{}, rus_verbs:НАРЯДИТЬСЯ{}, rus_verbs:НАРЯЖАТЬСЯ{}, rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ) rus_verbs:ЗАХВАТЫВАТЬ{}, rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ) rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ) rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ) rus_verbs:ПОСТРОИТЬСЯ{}, rus_verbs:ВЫСТРОИТЬСЯ{}, rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ) rus_verbs:ВЫПУСКАТЬ{}, rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ) rus_verbs:ВЦЕПИТЬСЯ{}, rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ) rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ) rus_verbs:ОТСТУПАТЬ{}, rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ) rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ) rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ) rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ) rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ) rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ) rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин) rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ) rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ) rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ) rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ) rus_verbs:СЖИМАТЬСЯ{}, rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ) rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ) rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ) rus_verbs:ПОКРАСИТЬ{}, // rus_verbs:ПЕРЕКРАСИТЬ{}, // rus_verbs:ОКРАСИТЬ{}, // rus_verbs:ЗАКРАСИТЬ{}, // rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ) rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ) rus_verbs:СТЯНУТЬ{}, // rus_verbs:ЗАТЯНУТЬ{}, // rus_verbs:ВТЯНУТЬ{}, // rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ) деепричастие:придя{}, // Немного придя в себя rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ) rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ) rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ) rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ) rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ) rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ) rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин) rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин) rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин) rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин) rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин) rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин) rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин) rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В) rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В) rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В) rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В) rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин) rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В) rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В) rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин) rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В) rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В) rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В) rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В) rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В) rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В) rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В) rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В) rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В) rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны. rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В) rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям. rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В) rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в) rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В) rus_verbs:валить{}, // валить все в одну кучу (валить в) rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в) rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в) rus_verbs:клониться{}, // он клонился в сторону (клониться в) rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в) rus_verbs:запасть{}, // Эти слова запали мне в душу. rus_verbs:давать{}, // В этой лавке дают в долг? rus_verbs:ездить{}, // Каждый день грузовик ездит в город. rus_verbs:претвориться{}, // Замысел претворился в жизнь. rus_verbs:разойтись{}, // Они разошлись в разные стороны. rus_verbs:выйти{}, // Охотник вышел в поле с ружьём. rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом. rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны rus_verbs:переодеваться{}, // переодеваться в женское платье rus_verbs:перерастать{}, // перерастать в массовые беспорядки rus_verbs:завязываться{}, // завязываться в узел rus_verbs:похватать{}, // похватать в руки rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:помещать{}, // помещать в изолятор rus_verbs:зыркнуть{}, // зыркнуть в окошко rus_verbs:закатать{}, // закатать в асфальт rus_verbs:усаживаться{}, // усаживаться в кресло rus_verbs:загонять{}, // загонять в сарай rus_verbs:подбрасывать{}, // подбрасывать в воздух rus_verbs:телеграфировать{}, // телеграфировать в центр rus_verbs:вязать{}, // вязать в стопы rus_verbs:подлить{}, // подлить в огонь rus_verbs:заполучить{}, // заполучить в распоряжение rus_verbs:подогнать{}, // подогнать в док rus_verbs:ломиться{}, // ломиться в открытую дверь rus_verbs:переправить{}, // переправить в деревню rus_verbs:затягиваться{}, // затягиваться в трубу rus_verbs:разлетаться{}, // разлетаться в стороны rus_verbs:кланяться{}, // кланяться в ножки rus_verbs:устремляться{}, // устремляться в открытое море rus_verbs:переместиться{}, // переместиться в другую аудиторию rus_verbs:ложить{}, // ложить в ящик rus_verbs:отвозить{}, // отвозить в аэропорт rus_verbs:напрашиваться{}, // напрашиваться в гости rus_verbs:напроситься{}, // напроситься в гости rus_verbs:нагрянуть{}, // нагрянуть в гости rus_verbs:заворачивать{}, // заворачивать в фольгу rus_verbs:заковать{}, // заковать в кандалы rus_verbs:свезти{}, // свезти в сарай rus_verbs:притащиться{}, // притащиться в дом rus_verbs:завербовать{}, // завербовать в разведку rus_verbs:рубиться{}, // рубиться в компьютерные игры rus_verbs:тыкаться{}, // тыкаться в материнскую грудь инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш }, деепричастие:ссыпав{}, деепричастие:ссыпая{}, rus_verbs:засасывать{}, // засасывать в себя rus_verbs:скакнуть{}, // скакнуть в будущее rus_verbs:подвозить{}, // подвозить в театр rus_verbs:переиграть{}, // переиграть в покер rus_verbs:мобилизовать{}, // мобилизовать в действующую армию rus_verbs:залетать{}, // залетать в закрытое воздушное пространство rus_verbs:подышать{}, // подышать в трубочку rus_verbs:смотаться{}, // смотаться в институт rus_verbs:рассовать{}, // рассовать в кармашки rus_verbs:захаживать{}, // захаживать в дом инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард деепричастие:сгоняя{}, rus_verbs:посылаться{}, // посылаться в порт rus_verbs:отлить{}, // отлить в кастрюлю rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение rus_verbs:поплакать{}, // поплакать в платочек rus_verbs:обуться{}, // обуться в сапоги rus_verbs:закапать{}, // закапать в глаза инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш }, деепричастие:свозив{}, деепричастие:свозя{}, rus_verbs:преобразовать{}, // преобразовать в линейное уравнение rus_verbs:кутаться{}, // кутаться в плед rus_verbs:смещаться{}, // смещаться в сторону rus_verbs:зазывать{}, // зазывать в свой магазин инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш }, деепричастие:трансформируясь{}, деепричастие:трансформировавшись{}, rus_verbs:погружать{}, // погружать в кипящее масло rus_verbs:обыграть{}, // обыграть в теннис rus_verbs:закутать{}, // закутать в одеяло rus_verbs:изливаться{}, // изливаться в воду rus_verbs:закатывать{}, // закатывать в асфальт rus_verbs:мотнуться{}, // мотнуться в банк rus_verbs:избираться{}, // избираться в сенат rus_verbs:наниматься{}, // наниматься в услужение rus_verbs:настучать{}, // настучать в органы rus_verbs:запихивать{}, // запихивать в печку rus_verbs:закапывать{}, // закапывать в нос rus_verbs:засобираться{}, // засобираться в поход rus_verbs:копировать{}, // копировать в другую папку rus_verbs:замуровать{}, // замуровать в стену rus_verbs:упечь{}, // упечь в тюрьму rus_verbs:зрить{}, // зрить в корень rus_verbs:стягиваться{}, // стягиваться в одну точку rus_verbs:усаживать{}, // усаживать в тренажер rus_verbs:протолкнуть{}, // протолкнуть в отверстие rus_verbs:расшибиться{}, // расшибиться в лепешку rus_verbs:приглашаться{}, // приглашаться в кабинет rus_verbs:садить{}, // садить в телегу rus_verbs:уткнуть{}, // уткнуть в подушку rus_verbs:протечь{}, // протечь в подвал rus_verbs:перегнать{}, // перегнать в другую страну rus_verbs:переползти{}, // переползти в тень rus_verbs:зарываться{}, // зарываться в грунт rus_verbs:переодеть{}, // переодеть в сухую одежду rus_verbs:припуститься{}, // припуститься в пляс rus_verbs:лопотать{}, // лопотать в микрофон rus_verbs:прогнусавить{}, // прогнусавить в микрофон rus_verbs:мочиться{}, // мочиться в штаны rus_verbs:загружать{}, // загружать в патронник rus_verbs:радировать{}, // радировать в центр rus_verbs:промотать{}, // промотать в конец rus_verbs:помчать{}, // помчать в школу rus_verbs:съезжать{}, // съезжать в кювет rus_verbs:завозить{}, // завозить в магазин rus_verbs:заявляться{}, // заявляться в школу rus_verbs:наглядеться{}, // наглядеться в зеркало rus_verbs:сворачиваться{}, // сворачиваться в клубочек rus_verbs:устремлять{}, // устремлять взор в будущее rus_verbs:забредать{}, // забредать в глухие уголки rus_verbs:перемотать{}, // перемотать в самое начало диалога rus_verbs:сморкаться{}, // сморкаться в носовой платочек rus_verbs:перетекать{}, // перетекать в другой сосуд rus_verbs:закачать{}, // закачать в шарик rus_verbs:запрятать{}, // запрятать в сейф rus_verbs:пинать{}, // пинать в живот rus_verbs:затрубить{}, // затрубить в горн rus_verbs:подглядывать{}, // подглядывать в замочную скважину инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш }, деепричастие:подсыпав{}, деепричастие:подсыпая{}, rus_verbs:засовывать{}, // засовывать в пенал rus_verbs:отрядить{}, // отрядить в командировку rus_verbs:справлять{}, // справлять в кусты rus_verbs:поторапливаться{}, // поторапливаться в самолет rus_verbs:скопировать{}, // скопировать в кэш rus_verbs:подливать{}, // подливать в огонь rus_verbs:запрячь{}, // запрячь в повозку rus_verbs:окраситься{}, // окраситься в пурпур rus_verbs:уколоть{}, // уколоть в шею rus_verbs:слететься{}, // слететься в гнездо rus_verbs:резаться{}, // резаться в карты rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш) деепричастие:задвигая{}, rus_verbs:доставляться{}, // доставляться в ресторан rus_verbs:поплевать{}, // поплевать в чашку rus_verbs:попереться{}, // попереться в магазин rus_verbs:хаживать{}, // хаживать в церковь rus_verbs:преображаться{}, // преображаться в королеву rus_verbs:организоваться{}, // организоваться в группу rus_verbs:ужалить{}, // ужалить в руку rus_verbs:протискиваться{}, // протискиваться в аудиторию rus_verbs:препроводить{}, // препроводить в закуток rus_verbs:разъезжаться{}, // разъезжаться в разные стороны rus_verbs:пропыхтеть{}, // пропыхтеть в трубку rus_verbs:уволочь{}, // уволочь в нору rus_verbs:отодвигаться{}, // отодвигаться в сторону rus_verbs:разливать{}, // разливать в стаканы rus_verbs:сбегаться{}, // сбегаться в актовый зал rus_verbs:наведаться{}, // наведаться в кладовку rus_verbs:перекочевать{}, // перекочевать в горы rus_verbs:прощебетать{}, // прощебетать в трубку rus_verbs:перекладывать{}, // перекладывать в другой карман rus_verbs:углубляться{}, // углубляться в теорию rus_verbs:переименовать{}, // переименовать в город rus_verbs:переметнуться{}, // переметнуться в лагерь противника rus_verbs:разносить{}, // разносить в щепки rus_verbs:осыпаться{}, // осыпаться в холода rus_verbs:попроситься{}, // попроситься в туалет rus_verbs:уязвить{}, // уязвить в сердце rus_verbs:перетащить{}, // перетащить в дом rus_verbs:закутаться{}, // закутаться в плед // rus_verbs:упаковать{}, // упаковать в бумагу инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость rus_verbs:хихикать{}, // хихикать в кулачок rus_verbs:объединить{}, // объединить в сеть инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию деепричастие:слетав{}, rus_verbs:заползти{}, // заползти в норку rus_verbs:перерасти{}, // перерасти в крупную аферу rus_verbs:списать{}, // списать в утиль rus_verbs:просачиваться{}, // просачиваться в бункер rus_verbs:пускаться{}, // пускаться в погоню rus_verbs:согревать{}, // согревать в мороз rus_verbs:наливаться{}, // наливаться в емкость rus_verbs:унестись{}, // унестись в небо rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф rus_verbs:сигануть{}, // сигануть в воду rus_verbs:окунуть{}, // окунуть в ледяную воду rus_verbs:просочиться{}, // просочиться в сапог rus_verbs:соваться{}, // соваться в толпу rus_verbs:протолкаться{}, // протолкаться в гардероб rus_verbs:заложить{}, // заложить в ломбард rus_verbs:перекатить{}, // перекатить в сарай rus_verbs:поставлять{}, // поставлять в Китай rus_verbs:залезать{}, // залезать в долги rus_verbs:отлучаться{}, // отлучаться в туалет rus_verbs:сбиваться{}, // сбиваться в кучу rus_verbs:зарыть{}, // зарыть в землю rus_verbs:засадить{}, // засадить в тело rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь rus_verbs:переставить{}, // переставить в шкаф rus_verbs:отчалить{}, // отчалить в плавание rus_verbs:набираться{}, // набираться в команду rus_verbs:лягнуть{}, // лягнуть в живот rus_verbs:притворить{}, // притворить в жизнь rus_verbs:проковылять{}, // проковылять в гардероб rus_verbs:прикатить{}, // прикатить в гараж rus_verbs:залететь{}, // залететь в окно rus_verbs:переделать{}, // переделать в мопед rus_verbs:протащить{}, // протащить в совет rus_verbs:обмакнуть{}, // обмакнуть в воду rus_verbs:отклоняться{}, // отклоняться в сторону rus_verbs:запихать{}, // запихать в пакет rus_verbs:избирать{}, // избирать в совет rus_verbs:загрузить{}, // загрузить в буфер rus_verbs:уплывать{}, // уплывать в Париж rus_verbs:забивать{}, // забивать в мерзлоту rus_verbs:потыкать{}, // потыкать в безжизненную тушу rus_verbs:съезжаться{}, // съезжаться в санаторий rus_verbs:залепить{}, // залепить в рыло rus_verbs:набиться{}, // набиться в карманы rus_verbs:уползти{}, // уползти в нору rus_verbs:упрятать{}, // упрятать в камеру rus_verbs:переместить{}, // переместить в камеру анабиоза rus_verbs:закрасться{}, // закрасться в душу rus_verbs:сместиться{}, // сместиться в инфракрасную область rus_verbs:запускать{}, // запускать в серию rus_verbs:потрусить{}, // потрусить в чащобу rus_verbs:забрасывать{}, // забрасывать в чистую воду rus_verbs:переселить{}, // переселить в отдаленную деревню rus_verbs:переезжать{}, // переезжать в новую квартиру rus_verbs:приподнимать{}, // приподнимать в воздух rus_verbs:добавиться{}, // добавиться в конец очереди rus_verbs:убыть{}, // убыть в часть rus_verbs:передвигать{}, // передвигать в соседнюю клетку rus_verbs:добавляться{}, // добавляться в очередь rus_verbs:дописать{}, // дописать в перечень rus_verbs:записываться{}, // записываться в кружок rus_verbs:продаться{}, // продаться в кредитное рабство rus_verbs:переписывать{}, // переписывать в тетрадку rus_verbs:заплыть{}, // заплыть в территориальные воды инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" }, rus_verbs:отбирать{}, // отбирать в гвардию rus_verbs:нашептывать{}, // нашептывать в микрофон rus_verbs:ковылять{}, // ковылять в стойло rus_verbs:прилетать{}, // прилетать в Париж rus_verbs:пролиться{}, // пролиться в канализацию rus_verbs:запищать{}, // запищать в микрофон rus_verbs:подвезти{}, // подвезти в больницу rus_verbs:припереться{}, // припереться в театр rus_verbs:утечь{}, // утечь в сеть rus_verbs:прорываться{}, // прорываться в буфет rus_verbs:увозить{}, // увозить в ремонт rus_verbs:съедать{}, // съедать в обед rus_verbs:просунуться{}, // просунуться в дверь rus_verbs:перенестись{}, // перенестись в прошлое rus_verbs:завезти{}, // завезти в магазин rus_verbs:проложить{}, // проложить в деревню rus_verbs:объединяться{}, // объединяться в профсоюз rus_verbs:развиться{}, // развиться в бабочку rus_verbs:засеменить{}, // засеменить в кабинку rus_verbs:скатываться{}, // скатываться в яму rus_verbs:завозиться{}, // завозиться в магазин rus_verbs:нанимать{}, // нанимать в рейс rus_verbs:поспеть{}, // поспеть в класс rus_verbs:кидаться{}, // кинаться в крайности rus_verbs:поспевать{}, // поспевать в оперу rus_verbs:обернуть{}, // обернуть в фольгу rus_verbs:обратиться{}, // обратиться в прокуратуру rus_verbs:истолковать{}, // истолковать в свою пользу rus_verbs:таращиться{}, // таращиться в дисплей rus_verbs:прыснуть{}, // прыснуть в кулачок rus_verbs:загнуть{}, // загнуть в другую сторону rus_verbs:раздать{}, // раздать в разные руки rus_verbs:назначить{}, // назначить в приемную комиссию rus_verbs:кидать{}, // кидать в кусты rus_verbs:увлекать{}, // увлекать в лес rus_verbs:переселиться{}, // переселиться в чужое тело rus_verbs:присылать{}, // присылать в город rus_verbs:уплыть{}, // уплыть в Европу rus_verbs:запричитать{}, // запричитать в полный голос rus_verbs:утащить{}, // утащить в логово rus_verbs:завернуться{}, // завернуться в плед rus_verbs:заносить{}, // заносить в блокнот rus_verbs:пятиться{}, // пятиться в дом rus_verbs:наведываться{}, // наведываться в больницу rus_verbs:нырять{}, // нырять в прорубь rus_verbs:зачастить{}, // зачастить в бар rus_verbs:назначаться{}, // назначается в комиссию rus_verbs:мотаться{}, // мотаться в областной центр rus_verbs:разыграть{}, // разыграть в карты rus_verbs:пропищать{}, // пропищать в микрофон rus_verbs:пихнуть{}, // пихнуть в бок rus_verbs:эмигрировать{}, // эмигрировать в Канаду rus_verbs:подключить{}, // подключить в сеть rus_verbs:упереть{}, // упереть в фундамент rus_verbs:уплатить{}, // уплатить в кассу rus_verbs:потащиться{}, // потащиться в медпункт rus_verbs:пригнать{}, // пригнать в стойло rus_verbs:оттеснить{}, // оттеснить в фойе rus_verbs:стучаться{}, // стучаться в ворота rus_verbs:перечислить{}, // перечислить в фонд rus_verbs:сомкнуть{}, // сомкнуть в круг rus_verbs:закачаться{}, // закачаться в резервуар rus_verbs:кольнуть{}, // кольнуть в бок rus_verbs:накрениться{}, // накрениться в сторону берега rus_verbs:подвинуться{}, // подвинуться в другую сторону rus_verbs:разнести{}, // разнести в клочья rus_verbs:отливать{}, // отливать в форму rus_verbs:подкинуть{}, // подкинуть в карман rus_verbs:уводить{}, // уводить в кабинет rus_verbs:ускакать{}, // ускакать в школу rus_verbs:ударять{}, // ударять в барабаны rus_verbs:даться{}, // даться в руки rus_verbs:поцеловаться{}, // поцеловаться в губы rus_verbs:посветить{}, // посветить в подвал rus_verbs:тыкать{}, // тыкать в арбуз rus_verbs:соединяться{}, // соединяться в кольцо rus_verbs:растянуть{}, // растянуть в тонкую ниточку rus_verbs:побросать{}, // побросать в пыль rus_verbs:стукнуться{}, // стукнуться в закрытую дверь rus_verbs:проигрывать{}, // проигрывать в теннис rus_verbs:дунуть{}, // дунуть в трубочку rus_verbs:улетать{}, // улетать в Париж rus_verbs:переводиться{}, // переводиться в филиал rus_verbs:окунуться{}, // окунуться в водоворот событий rus_verbs:попрятаться{}, // попрятаться в норы rus_verbs:перевезти{}, // перевезти в соседнюю палату rus_verbs:топать{}, // топать в школу rus_verbs:относить{}, // относить в помещение rus_verbs:укладывать{}, // укладывать в стопку rus_verbs:укатить{}, // укатил в турне rus_verbs:убирать{}, // убирать в сумку rus_verbs:помалкивать{}, // помалкивать в тряпочку rus_verbs:ронять{}, // ронять в грязь rus_verbs:глазеть{}, // глазеть в бинокль rus_verbs:преобразиться{}, // преобразиться в другого человека rus_verbs:запрыгнуть{}, // запрыгнуть в поезд rus_verbs:сгодиться{}, // сгодиться в суп rus_verbs:проползти{}, // проползти в нору rus_verbs:забираться{}, // забираться в коляску rus_verbs:сбежаться{}, // сбежались в класс rus_verbs:закатиться{}, // закатиться в угол rus_verbs:плевать{}, // плевать в душу rus_verbs:поиграть{}, // поиграть в демократию rus_verbs:кануть{}, // кануть в небытие rus_verbs:опаздывать{}, // опаздывать в школу rus_verbs:отползти{}, // отползти в сторону rus_verbs:стекаться{}, // стекаться в отстойник rus_verbs:запихнуть{}, // запихнуть в пакет rus_verbs:вышвырнуть{}, // вышвырнуть в коридор rus_verbs:связываться{}, // связываться в плотный узел rus_verbs:затолкать{}, // затолкать в ухо rus_verbs:скрутить{}, // скрутить в трубочку rus_verbs:сворачивать{}, // сворачивать в трубочку rus_verbs:сплестись{}, // сплестись в узел rus_verbs:заскочить{}, // заскочить в кабинет rus_verbs:проваливаться{}, // проваливаться в сон rus_verbs:уверовать{}, // уверовать в свою безнаказанность rus_verbs:переписать{}, // переписать в тетрадку rus_verbs:переноситься{}, // переноситься в мир фантазий rus_verbs:заводить{}, // заводить в помещение rus_verbs:сунуться{}, // сунуться в аудиторию rus_verbs:устраиваться{}, // устраиваться в автомастерскую rus_verbs:пропускать{}, // пропускать в зал инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш }, деепричастие:сбегая{}, деепричастие:сбегав{}, rus_verbs:прибегать{}, // прибегать в школу rus_verbs:съездить{}, // съездить в лес rus_verbs:захлопать{}, // захлопать в ладошки rus_verbs:опрокинуться{}, // опрокинуться в грязь инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш }, деепричастие:насыпая{}, деепричастие:насыпав{}, rus_verbs:употреблять{}, // употреблять в пищу rus_verbs:приводиться{}, // приводиться в действие rus_verbs:пристроить{}, // пристроить в надежные руки rus_verbs:юркнуть{}, // юркнуть в нору rus_verbs:объединиться{}, // объединиться в банду rus_verbs:сажать{}, // сажать в одиночку rus_verbs:соединить{}, // соединить в кольцо rus_verbs:забрести{}, // забрести в кафешку rus_verbs:свернуться{}, // свернуться в клубочек rus_verbs:пересесть{}, // пересесть в другой автобус rus_verbs:постучаться{}, // постучаться в дверцу rus_verbs:соединять{}, // соединять в кольцо rus_verbs:приволочь{}, // приволочь в коморку rus_verbs:смахивать{}, // смахивать в ящик стола rus_verbs:забежать{}, // забежать в помещение rus_verbs:целиться{}, // целиться в беглеца rus_verbs:прокрасться{}, // прокрасться в хранилище rus_verbs:заковылять{}, // заковылять в травтамологию rus_verbs:прискакать{}, // прискакать в стойло rus_verbs:колотить{}, // колотить в дверь rus_verbs:смотреться{}, // смотреться в зеркало rus_verbs:подложить{}, // подложить в салон rus_verbs:пущать{}, // пущать в королевские покои rus_verbs:согнуть{}, // согнуть в дугу rus_verbs:забарабанить{}, // забарабанить в дверь rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы rus_verbs:убраться{}, // убраться в специальную нишу rus_verbs:насмотреться{}, // насмотреться в зеркало rus_verbs:чмокнуть{}, // чмокнуть в щечку rus_verbs:усмехаться{}, // усмехаться в бороду rus_verbs:передвинуть{}, // передвинуть в конец очереди rus_verbs:допускаться{}, // допускаться в опочивальню rus_verbs:задвинуть{}, // задвинуть в дальний угол rus_verbs:отправлять{}, // отправлять в центр rus_verbs:сбрасывать{}, // сбрасывать в жерло rus_verbs:расстреливать{}, // расстреливать в момент обнаружения rus_verbs:заволочь{}, // заволочь в закуток rus_verbs:пролить{}, // пролить в воду rus_verbs:зарыться{}, // зарыться в сено rus_verbs:переливаться{}, // переливаться в емкость rus_verbs:затащить{}, // затащить в клуб rus_verbs:перебежать{}, // перебежать в лагерь врагов rus_verbs:одеть{}, // одеть в новое платье инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу деепричастие:задвигаясь{}, rus_verbs:клюнуть{}, // клюнуть в темечко rus_verbs:наливать{}, // наливать в кружку rus_verbs:пролезть{}, // пролезть в ушко rus_verbs:откладывать{}, // откладывать в ящик rus_verbs:протянуться{}, // протянуться в соседний дом rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь rus_verbs:устанавливать{}, // устанавливать в машину rus_verbs:употребляться{}, // употребляться в пищу rus_verbs:переключиться{}, // переключиться в реверсный режим rus_verbs:пискнуть{}, // пискнуть в микрофон rus_verbs:заявиться{}, // заявиться в класс rus_verbs:налиться{}, // налиться в стакан rus_verbs:заливать{}, // заливать в бак rus_verbs:ставиться{}, // ставиться в очередь инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны деепричастие:писаясь{}, rus_verbs:целоваться{}, // целоваться в губы rus_verbs:наносить{}, // наносить в область сердца rus_verbs:посмеяться{}, // посмеяться в кулачок rus_verbs:употребить{}, // употребить в пищу rus_verbs:прорваться{}, // прорваться в столовую rus_verbs:укладываться{}, // укладываться в ровные стопки rus_verbs:пробиться{}, // пробиться в финал rus_verbs:забить{}, // забить в землю rus_verbs:переложить{}, // переложить в другой карман rus_verbs:опускать{}, // опускать в свежевырытую могилу rus_verbs:поторопиться{}, // поторопиться в школу rus_verbs:сдвинуться{}, // сдвинуться в сторону rus_verbs:капать{}, // капать в смесь rus_verbs:погружаться{}, // погружаться во тьму rus_verbs:направлять{}, // направлять в кабинку rus_verbs:погрузить{}, // погрузить во тьму rus_verbs:примчаться{}, // примчаться в школу rus_verbs:упираться{}, // упираться в дверь rus_verbs:удаляться{}, // удаляться в комнату совещаний rus_verbs:ткнуться{}, // ткнуться в окошко rus_verbs:убегать{}, // убегать в чащу rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру rus_verbs:наговорить{}, // наговорить в микрофон rus_verbs:переносить{}, // переносить в дом rus_verbs:прилечь{}, // прилечь в кроватку rus_verbs:поворачивать{}, // поворачивать в обратную сторону rus_verbs:проскочить{}, // проскочить в щель rus_verbs:совать{}, // совать в духовку rus_verbs:переодеться{}, // переодеться в чистую одежду rus_verbs:порвать{}, // порвать в лоскуты rus_verbs:завязать{}, // завязать в бараний рог rus_verbs:съехать{}, // съехать в кювет rus_verbs:литься{}, // литься в канистру rus_verbs:уклониться{}, // уклониться в левую сторону rus_verbs:смахнуть{}, // смахнуть в мусорное ведро rus_verbs:спускать{}, // спускать в шахту rus_verbs:плеснуть{}, // плеснуть в воду rus_verbs:подуть{}, // подуть в угольки rus_verbs:набирать{}, // набирать в команду rus_verbs:хлопать{}, // хлопать в ладошки rus_verbs:ранить{}, // ранить в самое сердце rus_verbs:посматривать{}, // посматривать в иллюминатор rus_verbs:превращать{}, // превращать воду в вино rus_verbs:толкать{}, // толкать в пучину rus_verbs:отбыть{}, // отбыть в расположение части rus_verbs:сгрести{}, // сгрести в карман rus_verbs:удрать{}, // удрать в тайгу rus_verbs:пристроиться{}, // пристроиться в хорошую фирму rus_verbs:сбиться{}, // сбиться в плотную группу rus_verbs:заключать{}, // заключать в объятия rus_verbs:отпускать{}, // отпускать в поход rus_verbs:устремить{}, // устремить взгляд в будущее rus_verbs:обронить{}, // обронить в траву rus_verbs:сливаться{}, // сливаться в речку rus_verbs:стекать{}, // стекать в канаву rus_verbs:свалить{}, // свалить в кучу rus_verbs:подтянуть{}, // подтянуть в кабину rus_verbs:скатиться{}, // скатиться в канаву rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь rus_verbs:заторопиться{}, // заторопиться в буфет rus_verbs:протиснуться{}, // протиснуться в центр толпы rus_verbs:прятать{}, // прятать в укромненькое местечко rus_verbs:пропеть{}, // пропеть в микрофон rus_verbs:углубиться{}, // углубиться в джунгли rus_verbs:сползти{}, // сползти в яму rus_verbs:записывать{}, // записывать в память rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР) rus_verbs:колотиться{}, // колотиться в дверь rus_verbs:просунуть{}, // просунуть в отверстие rus_verbs:провожать{}, // провожать в армию rus_verbs:катить{}, // катить в гараж rus_verbs:поражать{}, // поражать в самое сердце rus_verbs:отлететь{}, // отлететь в дальний угол rus_verbs:закинуть{}, // закинуть в речку rus_verbs:катиться{}, // катиться в пропасть rus_verbs:забросить{}, // забросить в дальний угол rus_verbs:отвезти{}, // отвезти в лагерь rus_verbs:втопить{}, // втопить педаль в пол rus_verbs:втапливать{}, // втапливать педать в пол rus_verbs:утопить{}, // утопить кнопку в панель rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?) rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег rus_verbs:поскакать{}, // поскакать в атаку rus_verbs:прицелиться{}, // прицелиться в бегущего зайца rus_verbs:прыгать{}, // прыгать в кровать rus_verbs:приглашать{}, // приглашать в дом rus_verbs:понестись{}, // понестись в ворота rus_verbs:заехать{}, // заехать в гаражный бокс rus_verbs:опускаться{}, // опускаться в бездну rus_verbs:переехать{}, // переехать в коттедж rus_verbs:поместить{}, // поместить в карантин rus_verbs:ползти{}, // ползти в нору rus_verbs:добавлять{}, // добавлять в корзину rus_verbs:уткнуться{}, // уткнуться в подушку rus_verbs:продавать{}, // продавать в рабство rus_verbs:спрятаться{}, // Белка спрячется в дупло. rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию rus_verbs:воткнуть{}, // воткни вилку в розетку rus_verbs:нести{}, // нести в больницу rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку rus_verbs:впаивать{}, // впаивать деталь в плату rus_verbs:впаиваться{}, // деталь впаивается в плату rus_verbs:впархивать{}, // впархивать в помещение rus_verbs:впаять{}, // впаять деталь в плату rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат rus_verbs:вперивать{}, // вперивать взгляд в экран rus_verbs:впериваться{}, // впериваться в экран rus_verbs:вперить{}, // вперить взгляд в экран rus_verbs:впериться{}, // впериться в экран rus_verbs:вперять{}, // вперять взгляд в экран rus_verbs:вперяться{}, // вперяться в экран rus_verbs:впечатать{}, // впечатать текст в первую главу rus_verbs:впечататься{}, // впечататься в стену rus_verbs:впечатывать{}, // впечатывать текст в первую главу rus_verbs:впечатываться{}, // впечатываться в стену rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами rus_verbs:впитаться{}, // Жидкость впиталась в ткань rus_verbs:впитываться{}, // Жидкость впитывается в ткань rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник rus_verbs:вплавиться{}, // Провод вплавился в плату rus_verbs:вплеснуть{}, // вплеснуть краситель в бак rus_verbs:вплести{}, // вплести ленту в волосы rus_verbs:вплестись{}, // вплестись в волосы rus_verbs:вплетать{}, // вплетать ленты в волосы rus_verbs:вплывать{}, // корабль вплывает в порт rus_verbs:вплыть{}, // яхта вплыла в бухту rus_verbs:вползать{}, // дракон вползает в пещеру rus_verbs:вползти{}, // дракон вполз в свою пещеру rus_verbs:впорхнуть{}, // бабочка впорхнула в окно rus_verbs:впрессовать{}, // впрессовать деталь в плиту rus_verbs:впрессоваться{}, // впрессоваться в плиту rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту rus_verbs:впрессовываться{}, // впрессовываться в плиту rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания rus_verbs:впрягать{}, // впрягать лошадь в телегу rus_verbs:впрягаться{}, // впрягаться в работу rus_verbs:впрячь{}, // впрячь лошадь в телегу rus_verbs:впрячься{}, // впрячься в работу rus_verbs:впускать{}, // впускать посетителей в музей rus_verbs:впускаться{}, // впускаться в помещение rus_verbs:впустить{}, // впустить посетителей в музей rus_verbs:впутать{}, // впутать кого-то во что-то rus_verbs:впутаться{}, // впутаться во что-то rus_verbs:впутывать{}, // впутывать кого-то во что-то rus_verbs:впутываться{}, // впутываться во что-то rus_verbs:врабатываться{}, // врабатываться в режим rus_verbs:вработаться{}, // вработаться в режим rus_verbs:врастать{}, // врастать в кожу rus_verbs:врасти{}, // врасти в кожу инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь инфинитив:врезать{ вид:соверш }, глагол:врезать{ вид:несоверш }, глагол:врезать{ вид:соверш }, деепричастие:врезая{}, деепричастие:врезав{}, прилагательное:врезанный{}, инфинитив:врезаться{ вид:несоверш }, // врезаться в стену инфинитив:врезаться{ вид:соверш }, глагол:врезаться{ вид:несоверш }, деепричастие:врезаясь{}, деепричастие:врезавшись{}, rus_verbs:врубить{}, // врубить в нагрузку rus_verbs:врываться{}, // врываться в здание rus_verbs:закачивать{}, // Насос закачивает топливо в бак rus_verbs:ввезти{}, // Предприятие ввезло товар в страну rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу rus_verbs:ввивать{}, // Женщина ввивает полоску в косу rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека rus_verbs:вламываться{}, // Полиция вламывается в квартиру rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом rus_verbs:вовлечься{}, // вовлечься в занятие спортом rus_verbs:спуститься{}, // спуститься в подвал rus_verbs:спускаться{}, // спускаться в подвал rus_verbs:отправляться{}, // отправляться в дальнее плавание инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство инфинитив:эмитировать{ вид:несоверш }, глагол:эмитировать{ вид:соверш }, глагол:эмитировать{ вид:несоверш }, деепричастие:эмитируя{}, деепричастие:эмитировав{}, прилагательное:эмитировавший{ вид:несоверш }, // прилагательное:эмитировавший{ вид:соверш }, прилагательное:эмитирующий{}, прилагательное:эмитируемый{}, прилагательное:эмитированный{}, инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию инфинитив:этапировать{вид:соверш}, глагол:этапировать{вид:несоверш}, глагол:этапировать{вид:соверш}, деепричастие:этапируя{}, прилагательное:этапируемый{}, прилагательное:этапированный{}, rus_verbs:этапироваться{}, // Преступники этапируются в колонию rus_verbs:баллотироваться{}, // они баллотировались в жюри rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну rus_verbs:бросать{}, // Они бросали в фонтан медные монетки rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:бросить{}, // Он бросил в фонтан медную монетку rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя rus_verbs:буксировать{}, // Буксир буксирует танкер в порт rus_verbs:буксироваться{}, // Сухогруз буксируется в порт rus_verbs:вбегать{}, // Курьер вбегает в дверь rus_verbs:вбежать{}, // Курьер вбежал в дверь rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту rus_verbs:вбиваться{}, // Штырь вбивается в плиту rus_verbs:вбирать{}, // Вата вбирает в себя влагу rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру rus_verbs:вбросить{}, // Судья вбросил мяч в игру rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту rus_verbs:ввариваться{}, // Арматура вваривается в плиту rus_verbs:вварить{}, // Робот вварил арматурину в плиту rus_verbs:влезть{}, // Предприятие ввезло товар в страну rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача rus_verbs:вверяться{}, // Пациент вверяется в руки врача rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров rus_verbs:ввиваться{}, // полоска ввивается в косу rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров // rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон rus_verbs:ввязаться{}, // Разведрота ввязалась в бой rus_verbs:ввязываться{}, // Передовые части ввязываются в бой rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь rus_verbs:вдвинуться{}, // деталь вдвинулась в печь rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко rus_verbs:вделать{}, // мастер вделал розетку в стену rus_verbs:вделывать{}, // мастер вделывает выключатель в стену rus_verbs:вделываться{}, // кронштейн вделывается в стену rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку rus_verbs:вернуться{}, // Дети вернулись в библиотеку rus_verbs:вжаться{}, // Водитель вжался в кресло rus_verbs:вживаться{}, // Актер вживается в новую роль rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента rus_verbs:вживляться{}, // Стимулятор вживляется в тело rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло rus_verbs:вжиться{}, // Актер вжился в свою новую роль rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо rus_verbs:взвинтиться{}, // Цены взвинтились в небо rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо rus_verbs:взвиться{}, // Шарики взвились в небо rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо rus_verbs:взмывать{}, // шарики взмывают в небо rus_verbs:взмыть{}, // Шарики взмыли в небо rus_verbs:вильнуть{}, // Машина вильнула в левую сторону rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю rus_verbs:вкапываться{}, // Свая вкапывается в землю rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж rus_verbs:вкатиться{}, // машина вкатилась в гараж rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж rus_verbs:вкатываться{}, // машина вкатывается в гараж rus_verbs:вкачать{}, // Механики вкачали в бак много топлива rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак rus_verbs:вкачиваться{}, // Топливо вкачивается в бак rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер rus_verbs:вкидываться{}, // Груз вкидывается в контейнер rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции rus_verbs:вкладываться{}, // Инвестор вкладывается в акции rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист rus_verbs:вклиниваться{}, // Машина вклинивается в поток rus_verbs:вклиниться{}, // машина вклинилась в поток rus_verbs:включать{}, // Команда включает компьютер в сеть rus_verbs:включаться{}, // Машина включается в глобальную сеть rus_verbs:включить{}, // Команда включила компьютер в сеть rus_verbs:включиться{}, // Компьютер включился в сеть rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон rus_verbs:влазить{}, // Разъем влазит в отверствие rus_verbs:вламывать{}, // Полиция вламывается в квартиру rus_verbs:влетать{}, // Самолет влетает в грозовой фронт rus_verbs:влететь{}, // Самолет влетел в грозовой фронт rus_verbs:вливать{}, // Механик вливает масло в картер rus_verbs:вливаться{}, // Масло вливается в картер rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности rus_verbs:влить{}, // Механик влил свежее масло в картер rus_verbs:влиться{}, // Свежее масло влилось в бак rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства rus_verbs:вложиться{}, // Инвесторы вложились в эти акции rus_verbs:влюбиться{}, // Коля влюбился в Олю rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов rus_verbs:вляпаться{}, // Коля вляпался в неприятность rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности rus_verbs:вменить{}, // вменить в вину rus_verbs:вменять{}, // вменять в обязанность rus_verbs:вмерзать{}, // Колеса вмерзают в лед rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед rus_verbs:вмести{}, // вмести в дом rus_verbs:вместить{}, // вместить в ёмкость rus_verbs:вместиться{}, // Прибор не вместился в зонд rus_verbs:вмешаться{}, // Начальник вмешался в конфликт rus_verbs:вмешивать{}, // Не вмешивай меня в это дело rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус rus_verbs:вминать{}, // вминать в корпус rus_verbs:вминаться{}, // кронштейн вминается в корпус rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт rus_verbs:вморозить{}, // Установка вморозила сваи в грунт rus_verbs:вмуровать{}, // Сейф был вмурован в стену rus_verbs:вмуровывать{}, // вмуровывать сейф в стену rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену rus_verbs:внедрить{}, // внедрить инновацию в производство rus_verbs:внедриться{}, // Шпион внедрился в руководство rus_verbs:внедрять{}, // внедрять инновации в производство rus_verbs:внедряться{}, // Шпионы внедряются в руководство rus_verbs:внести{}, // внести коробку в дом rus_verbs:внестись{}, // внестись в список приглашенных гостей rus_verbs:вникать{}, // Разработчик вникает в детали задачи rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев rus_verbs:вноситься{}, // вноситься в список главных персонажей rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом rus_verbs:вогнать{}, // вогнал человека в тоску rus_verbs:водворить{}, // водворить преступника в тюрьму rus_verbs:возвернуть{}, // возвернуть в родную стихию rus_verbs:возвернуться{}, // возвернуться в родную стихию rus_verbs:возвести{}, // возвести число в четную степень rus_verbs:возводить{}, // возводить число в четную степень rus_verbs:возводиться{}, // число возводится в четную степень rus_verbs:возвратить{}, // возвратить коров в стойло rus_verbs:возвратиться{}, // возвратиться в родной дом rus_verbs:возвращать{}, // возвращать коров в стойло rus_verbs:возвращаться{}, // возвращаться в родной дом rus_verbs:войти{}, // войти в галерею славы rus_verbs:вонзать{}, // Коля вонзает вилку в котлету rus_verbs:вонзаться{}, // Вилка вонзается в котлету rus_verbs:вонзить{}, // Коля вонзил вилку в котлету rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность rus_verbs:воплотиться{}, // Мечты воплотились в реальность rus_verbs:воплощать{}, // Коля воплощает мечты в реальность rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь rus_verbs:воспарить{}, // Душа воспарила в небо rus_verbs:воспарять{}, // Душа воспаряет в небо rus_verbs:врыть{}, // врыть опору в землю rus_verbs:врыться{}, // врыться в землю rus_verbs:всадить{}, // всадить пулю в сердце rus_verbs:всаживать{}, // всаживать нож в бок rus_verbs:всасывать{}, // всасывать воду в себя rus_verbs:всасываться{}, // всасываться в ёмкость rus_verbs:вселить{}, // вселить надежду в кого-либо rus_verbs:вселиться{}, // вселиться в пустующее здание rus_verbs:вселять{}, // вселять надежду в кого-то rus_verbs:вселяться{}, // вселяться в пустующее здание rus_verbs:вскидывать{}, // вскидывать руку в небо rus_verbs:вскинуть{}, // вскинуть руку в небо rus_verbs:вслушаться{}, // вслушаться в звуки rus_verbs:вслушиваться{}, // вслушиваться в шорох rus_verbs:всматриваться{}, // всматриваться в темноту rus_verbs:всмотреться{}, // всмотреться в темень rus_verbs:всовывать{}, // всовывать палец в отверстие rus_verbs:всовываться{}, // всовываться в форточку rus_verbs:всосать{}, // всосать жидкость в себя rus_verbs:всосаться{}, // всосаться в кожу rus_verbs:вставить{}, // вставить ключ в замок rus_verbs:вставлять{}, // вставлять ключ в замок rus_verbs:встраивать{}, // встраивать черный ход в систему защиты rus_verbs:встраиваться{}, // встраиваться в систему безопасности rus_verbs:встревать{}, // встревать в разговор rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности rus_verbs:встроиться{}, // встроиться в систему безопасности rus_verbs:встрять{}, // встрять в разговор rus_verbs:вступать{}, // вступать в действующую армию rus_verbs:вступить{}, // вступить в действующую армию rus_verbs:всунуть{}, // всунуть палец в отверстие rus_verbs:всунуться{}, // всунуться в форточку инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер инфинитив:всыпать{вид:несоверш}, глагол:всыпать{вид:соверш}, глагол:всыпать{вид:несоверш}, деепричастие:всыпав{}, деепричастие:всыпая{}, прилагательное:всыпавший{ вид:соверш }, // прилагательное:всыпавший{ вид:несоверш }, прилагательное:всыпанный{}, // прилагательное:всыпающий{}, инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер // инфинитив:всыпаться{ вид:соверш}, // глагол:всыпаться{ вид:соверш}, глагол:всыпаться{ вид:несоверш}, // деепричастие:всыпавшись{}, деепричастие:всыпаясь{}, // прилагательное:всыпавшийся{ вид:соверш }, // прилагательное:всыпавшийся{ вид:несоверш }, // прилагательное:всыпающийся{}, rus_verbs:вталкивать{}, // вталкивать деталь в ячейку rus_verbs:вталкиваться{}, // вталкиваться в ячейку rus_verbs:втаптывать{}, // втаптывать в грязь rus_verbs:втаптываться{}, // втаптываться в грязь rus_verbs:втаскивать{}, // втаскивать мешок в комнату rus_verbs:втаскиваться{}, // втаскиваться в комнату rus_verbs:втащить{}, // втащить мешок в комнату rus_verbs:втащиться{}, // втащиться в комнату rus_verbs:втекать{}, // втекать в бутылку rus_verbs:втемяшивать{}, // втемяшивать в голову rus_verbs:втемяшиваться{}, // втемяшиваться в голову rus_verbs:втемяшить{}, // втемяшить в голову rus_verbs:втемяшиться{}, // втемяшиться в голову rus_verbs:втереть{}, // втереть крем в кожу rus_verbs:втереться{}, // втереться в кожу rus_verbs:втесаться{}, // втесаться в группу rus_verbs:втесывать{}, // втесывать в группу rus_verbs:втесываться{}, // втесываться в группу rus_verbs:втечь{}, // втечь в бак rus_verbs:втирать{}, // втирать крем в кожу rus_verbs:втираться{}, // втираться в кожу rus_verbs:втискивать{}, // втискивать сумку в вагон rus_verbs:втискиваться{}, // втискиваться в переполненный вагон rus_verbs:втиснуть{}, // втиснуть сумку в вагон rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро rus_verbs:втолкать{}, // втолкать коляску в лифт rus_verbs:втолкаться{}, // втолкаться в вагон метро rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт rus_verbs:втолкнуться{}, // втолкнуться в вагон метро rus_verbs:втолочь{}, // втолочь в смесь rus_verbs:втоптать{}, // втоптать цветы в землю rus_verbs:вторгаться{}, // вторгаться в чужую зону rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь rus_verbs:втравить{}, // втравить кого-то в неприятности rus_verbs:втравливать{}, // втравливать кого-то в неприятности rus_verbs:втрамбовать{}, // втрамбовать камни в землю rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю rus_verbs:втрамбовываться{}, // втрамбовываться в землю rus_verbs:втрескаться{}, // втрескаться в кого-то rus_verbs:втрескиваться{}, // втрескиваться в кого-либо rus_verbs:втыкать{}, // втыкать вилку в котлетку rus_verbs:втыкаться{}, // втыкаться в розетку rus_verbs:втюриваться{}, // втюриваться в кого-либо rus_verbs:втюриться{}, // втюриться в кого-либо rus_verbs:втягивать{}, // втягивать что-то в себя rus_verbs:втягиваться{}, // втягиваться в себя rus_verbs:втянуться{}, // втянуться в себя rus_verbs:вцементировать{}, // вцементировать сваю в фундамент rus_verbs:вчеканить{}, // вчеканить надпись в лист rus_verbs:вчитаться{}, // вчитаться внимательнее в текст rus_verbs:вчитываться{}, // вчитываться внимательнее в текст rus_verbs:вчувствоваться{}, // вчувствоваться в роль rus_verbs:вшагивать{}, // вшагивать в новую жизнь rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь rus_verbs:вшивать{}, // вшивать заплату в рубашку rus_verbs:вшиваться{}, // вшиваться в ткань rus_verbs:вшить{}, // вшить заплату в ткань rus_verbs:въедаться{}, // въедаться в мякоть rus_verbs:въезжать{}, // въезжать в гараж rus_verbs:въехать{}, // въехать в гараж rus_verbs:выиграть{}, // Коля выиграл в шахматы rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы rus_verbs:выкладывать{}, // выкладывать в общий доступ rus_verbs:выкладываться{}, // выкладываться в общий доступ rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет rus_verbs:вылезать{}, // вылезать в открытое пространство rus_verbs:вылезти{}, // вылезти в открытое пространство rus_verbs:выливать{}, // выливать в бутылку rus_verbs:выливаться{}, // выливаться в ёмкость rus_verbs:вылить{}, // вылить отходы в канализацию rus_verbs:вылиться{}, // Топливо вылилось в воду rus_verbs:выложить{}, // выложить в общий доступ rus_verbs:выпадать{}, // выпадать в осадок rus_verbs:выпрыгивать{}, // выпрыгивать в окно rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно rus_verbs:выродиться{}, // выродиться в жалкое подобие rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков rus_verbs:высеваться{}, // высеваться в землю rus_verbs:высеять{}, // высеять в землю rus_verbs:выслать{}, // выслать в страну постоянного пребывания rus_verbs:высморкаться{}, // высморкаться в платок rus_verbs:высморкнуться{}, // высморкнуться в платок rus_verbs:выстреливать{}, // выстреливать в цель rus_verbs:выстреливаться{}, // выстреливаться в цель rus_verbs:выстрелить{}, // выстрелить в цель rus_verbs:вытекать{}, // вытекать в озеро rus_verbs:вытечь{}, // вытечь в воду rus_verbs:смотреть{}, // смотреть в будущее rus_verbs:подняться{}, // подняться в лабораторию rus_verbs:послать{}, // послать в магазин rus_verbs:слать{}, // слать в неизвестность rus_verbs:добавить{}, // добавить в суп rus_verbs:пройти{}, // пройти в лабораторию rus_verbs:положить{}, // положить в ящик rus_verbs:прислать{}, // прислать в полицию rus_verbs:упасть{}, // упасть в пропасть инфинитив:писать{ aux stress="пис^ать" }, // писать в газету инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки глагол:писать{ aux stress="п^исать" }, глагол:писать{ aux stress="пис^ать" }, деепричастие:писая{}, прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету rus_verbs:собираться{}, // собираться в поход rus_verbs:звать{}, // звать в ресторан rus_verbs:направиться{}, // направиться в ресторан rus_verbs:отправиться{}, // отправиться в ресторан rus_verbs:поставить{}, // поставить в угол rus_verbs:целить{}, // целить в мишень rus_verbs:попасть{}, // попасть в переплет rus_verbs:ударить{}, // ударить в больное место rus_verbs:закричать{}, // закричать в микрофон rus_verbs:опустить{}, // опустить в воду rus_verbs:принести{}, // принести в дом бездомного щенка rus_verbs:отдать{}, // отдать в хорошие руки rus_verbs:ходить{}, // ходить в школу rus_verbs:уставиться{}, // уставиться в экран rus_verbs:приходить{}, // приходить в бешенство rus_verbs:махнуть{}, // махнуть в Италию rus_verbs:сунуть{}, // сунуть в замочную скважину rus_verbs:явиться{}, // явиться в расположение части rus_verbs:уехать{}, // уехать в город rus_verbs:целовать{}, // целовать в лобик rus_verbs:повести{}, // повести в бой rus_verbs:опуститься{}, // опуститься в кресло rus_verbs:передать{}, // передать в архив rus_verbs:побежать{}, // побежать в школу rus_verbs:стечь{}, // стечь в воду rus_verbs:уходить{}, // уходить добровольцем в армию rus_verbs:привести{}, // привести в дом rus_verbs:шагнуть{}, // шагнуть в неизвестность rus_verbs:собраться{}, // собраться в поход rus_verbs:заглянуть{}, // заглянуть в основу rus_verbs:поспешить{}, // поспешить в церковь rus_verbs:поцеловать{}, // поцеловать в лоб rus_verbs:перейти{}, // перейти в высшую лигу rus_verbs:поверить{}, // поверить в искренность rus_verbs:глянуть{}, // глянуть в оглавление rus_verbs:зайти{}, // зайти в кафетерий rus_verbs:подобрать{}, // подобрать в лесу rus_verbs:проходить{}, // проходить в помещение rus_verbs:глядеть{}, // глядеть в глаза rus_verbs:пригласить{}, // пригласить в театр rus_verbs:позвать{}, // позвать в класс rus_verbs:усесться{}, // усесться в кресло rus_verbs:поступить{}, // поступить в институт rus_verbs:лечь{}, // лечь в постель rus_verbs:поклониться{}, // поклониться в пояс rus_verbs:потянуться{}, // потянуться в лес rus_verbs:колоть{}, // колоть в ягодицу rus_verbs:присесть{}, // присесть в кресло rus_verbs:оглядеться{}, // оглядеться в зеркало rus_verbs:поглядеть{}, // поглядеть в зеркало rus_verbs:превратиться{}, // превратиться в лягушку rus_verbs:принимать{}, // принимать во внимание rus_verbs:звонить{}, // звонить в колокола rus_verbs:привезти{}, // привезти в гостиницу rus_verbs:рухнуть{}, // рухнуть в пропасть rus_verbs:пускать{}, // пускать в дело rus_verbs:отвести{}, // отвести в больницу rus_verbs:сойти{}, // сойти в ад rus_verbs:набрать{}, // набрать в команду rus_verbs:собрать{}, // собрать в кулак rus_verbs:двигаться{}, // двигаться в каюту rus_verbs:падать{}, // падать в область нуля rus_verbs:полезть{}, // полезть в драку rus_verbs:направить{}, // направить в стационар rus_verbs:приводить{}, // приводить в чувство rus_verbs:толкнуть{}, // толкнуть в бок rus_verbs:кинуться{}, // кинуться в драку rus_verbs:ткнуть{}, // ткнуть в глаз rus_verbs:заключить{}, // заключить в объятия rus_verbs:подниматься{}, // подниматься в небо rus_verbs:расти{}, // расти в глубину rus_verbs:налить{}, // налить в кружку rus_verbs:швырнуть{}, // швырнуть в бездну rus_verbs:прыгнуть{}, // прыгнуть в дверь rus_verbs:промолчать{}, // промолчать в тряпочку rus_verbs:садиться{}, // садиться в кресло rus_verbs:лить{}, // лить в кувшин rus_verbs:дослать{}, // дослать деталь в держатель rus_verbs:переслать{}, // переслать в обработчик rus_verbs:удалиться{}, // удалиться в совещательную комнату rus_verbs:разглядывать{}, // разглядывать в бинокль rus_verbs:повесить{}, // повесить в шкаф инфинитив:походить{ вид:соверш }, // походить в институт глагол:походить{ вид:соверш }, деепричастие:походив{}, // прилагательное:походивший{вид:соверш}, rus_verbs:помчаться{}, // помчаться в класс rus_verbs:свалиться{}, // свалиться в яму rus_verbs:сбежать{}, // сбежать в Англию rus_verbs:стрелять{}, // стрелять в цель rus_verbs:обращать{}, // обращать в свою веру rus_verbs:завести{}, // завести в дом rus_verbs:приобрести{}, // приобрести в рассрочку rus_verbs:сбросить{}, // сбросить в яму rus_verbs:устроиться{}, // устроиться в крупную корпорацию rus_verbs:погрузиться{}, // погрузиться в пучину rus_verbs:течь{}, // течь в канаву rus_verbs:произвести{}, // произвести в звание майора rus_verbs:метать{}, // метать в цель rus_verbs:пустить{}, // пустить в дело rus_verbs:полететь{}, // полететь в Европу rus_verbs:пропустить{}, // пропустить в здание rus_verbs:рвануть{}, // рвануть в отпуск rus_verbs:заходить{}, // заходить в каморку rus_verbs:нырнуть{}, // нырнуть в прорубь rus_verbs:рвануться{}, // рвануться в атаку rus_verbs:приподняться{}, // приподняться в воздух rus_verbs:превращаться{}, // превращаться в крупную величину rus_verbs:прокричать{}, // прокричать в ухо rus_verbs:записать{}, // записать в блокнот rus_verbs:забраться{}, // забраться в шкаф rus_verbs:приезжать{}, // приезжать в деревню rus_verbs:продать{}, // продать в рабство rus_verbs:проникнуть{}, // проникнуть в центр rus_verbs:устремиться{}, // устремиться в открытое море rus_verbs:посадить{}, // посадить в кресло rus_verbs:упереться{}, // упереться в пол rus_verbs:ринуться{}, // ринуться в буфет rus_verbs:отдавать{}, // отдавать в кадетское училище rus_verbs:отложить{}, // отложить в долгий ящик rus_verbs:убежать{}, // убежать в приют rus_verbs:оценить{}, // оценить в миллион долларов rus_verbs:поднимать{}, // поднимать в стратосферу rus_verbs:отослать{}, // отослать в квалификационную комиссию rus_verbs:отодвинуть{}, // отодвинуть в дальний угол rus_verbs:торопиться{}, // торопиться в школу rus_verbs:попадаться{}, // попадаться в руки rus_verbs:поразить{}, // поразить в самое сердце rus_verbs:доставить{}, // доставить в квартиру rus_verbs:заслать{}, // заслать в тыл rus_verbs:сослать{}, // сослать в изгнание rus_verbs:запустить{}, // запустить в космос rus_verbs:удариться{}, // удариться в запой rus_verbs:ударяться{}, // ударяться в крайность rus_verbs:шептать{}, // шептать в лицо rus_verbs:уронить{}, // уронить в унитаз rus_verbs:прорычать{}, // прорычать в микрофон rus_verbs:засунуть{}, // засунуть в глотку rus_verbs:плыть{}, // плыть в открытое море rus_verbs:перенести{}, // перенести в духовку rus_verbs:светить{}, // светить в лицо rus_verbs:мчаться{}, // мчаться в ремонт rus_verbs:стукнуть{}, // стукнуть в лоб rus_verbs:обрушиться{}, // обрушиться в котлован rus_verbs:поглядывать{}, // поглядывать в экран rus_verbs:уложить{}, // уложить в кроватку инфинитив:попадать{ вид:несоверш }, // попадать в черный список глагол:попадать{ вид:несоверш }, прилагательное:попадающий{ вид:несоверш }, прилагательное:попадавший{ вид:несоверш }, деепричастие:попадая{}, rus_verbs:провалиться{}, // провалиться в яму rus_verbs:жаловаться{}, // жаловаться в комиссию rus_verbs:опоздать{}, // опоздать в школу rus_verbs:посылать{}, // посылать в парикмахерскую rus_verbs:погнать{}, // погнать в хлев rus_verbs:поступать{}, // поступать в институт rus_verbs:усадить{}, // усадить в кресло rus_verbs:проиграть{}, // проиграть в рулетку rus_verbs:прилететь{}, // прилететь в страну rus_verbs:повалиться{}, // повалиться в траву rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ rus_verbs:лезть{}, // лезть в чужие дела rus_verbs:потащить{}, // потащить в суд rus_verbs:направляться{}, // направляться в порт rus_verbs:поползти{}, // поползти в другую сторону rus_verbs:пуститься{}, // пуститься в пляс rus_verbs:забиться{}, // забиться в нору rus_verbs:залезть{}, // залезть в конуру rus_verbs:сдать{}, // сдать в утиль rus_verbs:тронуться{}, // тронуться в путь rus_verbs:сыграть{}, // сыграть в шахматы rus_verbs:перевернуть{}, // перевернуть в более удобную позу rus_verbs:сжимать{}, // сжимать пальцы в кулак rus_verbs:подтолкнуть{}, // подтолкнуть в бок rus_verbs:отнести{}, // отнести животное в лечебницу rus_verbs:одеться{}, // одеться в зимнюю одежду rus_verbs:плюнуть{}, // плюнуть в колодец rus_verbs:передавать{}, // передавать в прокуратуру rus_verbs:отскочить{}, // отскочить в лоб rus_verbs:призвать{}, // призвать в армию rus_verbs:увезти{}, // увезти в деревню rus_verbs:улечься{}, // улечься в кроватку rus_verbs:отшатнуться{}, // отшатнуться в сторону rus_verbs:ложиться{}, // ложиться в постель rus_verbs:пролететь{}, // пролететь в конец rus_verbs:класть{}, // класть в сейф rus_verbs:доставлять{}, // доставлять в кабинет rus_verbs:приобретать{}, // приобретать в кредит rus_verbs:сводить{}, // сводить в театр rus_verbs:унести{}, // унести в могилу rus_verbs:покатиться{}, // покатиться в яму rus_verbs:сходить{}, // сходить в магазинчик rus_verbs:спустить{}, // спустить в канализацию rus_verbs:проникать{}, // проникать в сердцевину rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд rus_verbs:пожаловаться{}, // пожаловаться в администрацию rus_verbs:стучать{}, // стучать в металлическую дверь rus_verbs:тащить{}, // тащить в ремонт rus_verbs:заглядывать{}, // заглядывать в ответы rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена rus_verbs:увести{}, // увести в следующий кабинет rus_verbs:успевать{}, // успевать в школу rus_verbs:пробраться{}, // пробраться в собачью конуру rus_verbs:подавать{}, // подавать в суд rus_verbs:прибежать{}, // прибежать в конюшню rus_verbs:рассмотреть{}, // рассмотреть в микроскоп rus_verbs:пнуть{}, // пнуть в живот rus_verbs:завернуть{}, // завернуть в декоративную пленку rus_verbs:уезжать{}, // уезжать в деревню rus_verbs:привлекать{}, // привлекать в свои ряды rus_verbs:перебраться{}, // перебраться в прибрежный город rus_verbs:долить{}, // долить в коктейль rus_verbs:палить{}, // палить в нападающих rus_verbs:отобрать{}, // отобрать в коллекцию rus_verbs:улететь{}, // улететь в неизвестность rus_verbs:выглянуть{}, // выглянуть в окно rus_verbs:выглядывать{}, // выглядывать в окно rus_verbs:пробираться{}, // грабитель, пробирающийся в дом инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог глагол:написать{ aux stress="напис^ать"}, прилагательное:написавший{ aux stress="напис^авший"}, rus_verbs:свернуть{}, // свернуть в колечко инфинитив:сползать{ вид:несоверш }, // сползать в овраг глагол:сползать{ вид:несоверш }, прилагательное:сползающий{ вид:несоверш }, прилагательное:сползавший{ вид:несоверш }, rus_verbs:барабанить{}, // барабанить в дверь rus_verbs:дописывать{}, // дописывать в конец rus_verbs:меняться{}, // меняться в лучшую сторону rus_verbs:измениться{}, // измениться в лучшую сторону rus_verbs:изменяться{}, // изменяться в лучшую сторону rus_verbs:вписаться{}, // вписаться в поворот rus_verbs:вписываться{}, // вписываться в повороты rus_verbs:переработать{}, // переработать в удобрение rus_verbs:перерабатывать{}, // перерабатывать в удобрение rus_verbs:уползать{}, // уползать в тень rus_verbs:заползать{}, // заползать в нору rus_verbs:перепрятать{}, // перепрятать в укромное место rus_verbs:заталкивать{}, // заталкивать в вагон rus_verbs:преобразовывать{}, // преобразовывать в список инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список глагол:конвертировать{ вид:несоверш }, инфинитив:конвертировать{ вид:соверш }, глагол:конвертировать{ вид:соверш }, деепричастие:конвертировав{}, деепричастие:конвертируя{}, rus_verbs:изорвать{}, // Он изорвал газету в клочки. rus_verbs:выходить{}, // Окна выходят в сад. rus_verbs:говорить{}, // Он говорил в защиту своего отца. rus_verbs:вырастать{}, // Он вырастает в большого художника. rus_verbs:вывести{}, // Он вывел детей в сад. // инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш }, // глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли. // прилагательное:раненый{}, // Он был ранен в левую руку. // прилагательное:одетый{}, // Он был одет в толстое осеннее пальто. rus_verbs:бухнуться{}, // Он бухнулся в воду. rus_verbs:склонять{}, // склонять защиту в свою пользу rus_verbs:впиться{}, // Пиявка впилась в тело. rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы rus_verbs:сохранять{}, // сохранить данные в файл rus_verbs:собирать{}, // собирать игрушки в ящик rus_verbs:упаковывать{}, // упаковывать вещи в чемодан rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:стрельнуть{}, // стрельни в толпу! rus_verbs:пулять{}, // пуляй в толпу rus_verbs:пульнуть{}, // пульни в толпу rus_verbs:становиться{}, // Становитесь в очередь. rus_verbs:вписать{}, // Юля вписала свое имя в список. rus_verbs:вписывать{}, // Мы вписывали свои имена в список прилагательное:видный{}, // Планета Марс видна в обычный бинокль rus_verbs:пойти{}, // Девочка рано пошла в школу rus_verbs:отойти{}, // Эти обычаи отошли в историю. rus_verbs:бить{}, // Холодный ветер бил ему в лицо. rus_verbs:входить{}, // Это входит в его обязанности. rus_verbs:принять{}, // меня приняли в пионеры rus_verbs:уйти{}, // Правительство РФ ушло в отставку rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году. rus_verbs:посвятить{}, // Я посвятил друга в свою тайну. инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза. rus_verbs:идти{}, // Я иду гулять в парк. rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт. rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей. rus_verbs:везти{}, // Учитель везёт детей в лагерь. rus_verbs:качать{}, // Судно качает во все стороны. rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами. rus_verbs:связать{}, // Свяжите свои вещи в узелок. rus_verbs:пронести{}, // Пронесите стол в дверь. rus_verbs:вынести{}, // Надо вынести примечания в конец. rus_verbs:устроить{}, // Она устроила сына в школу. rus_verbs:угодить{}, // Она угодила головой в дверь. rus_verbs:отвернуться{}, // Она резко отвернулась в сторону. rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль. rus_verbs:обратить{}, // Война обратила город в развалины. rus_verbs:сойтись{}, // Мы сошлись в школьные годы. rus_verbs:приехать{}, // Мы приехали в положенный час. rus_verbs:встать{}, // Дети встали в круг. rus_verbs:впасть{}, // Из-за болезни он впал в нужду. rus_verbs:придти{}, // придти в упадок rus_verbs:заявить{}, // Надо заявить в милицию о краже. rus_verbs:заявлять{}, // заявлять в полицию rus_verbs:ехать{}, // Мы будем ехать в Орёл rus_verbs:окрашиваться{}, // окрашиваться в красный цвет rus_verbs:решить{}, // Дело решено в пользу истца. rus_verbs:сесть{}, // Она села в кресло rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало. rus_verbs:влезать{}, // он влезает в мою квартирку rus_verbs:попасться{}, // в мою ловушку попалась мышь rus_verbs:лететь{}, // Мы летим в Орёл ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень ГЛ_ИНФ(взять), // Коля взял в руку камень ГЛ_ИНФ(поехать), // поехать в круиз ГЛ_ИНФ(подать), // подать в отставку инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море ГЛ_ИНФ(постучать) // постучать в дверь } // Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems fact гл_предл { if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } } then return true } #endregion Винительный // Все остальные варианты по умолчанию запрещаем. fact гл_предл { if context { * предлог:в{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:в{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:в{} * } then return false,-5 } #endregion Предлог_В #region Предлог_НА // ------------------- С ПРЕДЛОГОМ 'НА' --------------------------- #region ПРЕДЛОЖНЫЙ // НА+предложный падеж: // ЛЕЖАТЬ НА СТОЛЕ #region VerbList wordentry_set Гл_НА_Предл= { rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ) rus_verbs:ПРОСТУПИТЬ{}, // rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ) rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ) rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив) rus_verbs:ЗАМИРАТЬ{}, // rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ) rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ) rus_verbs:УПОЛЗАТЬ{}, // rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ) rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ) rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ) rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ) rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ) rus_verbs:искриться{}, rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ) rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ) rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ) rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ) rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ) rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ) rus_verbs:отвести{}, // отвести душу на людях rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра rus_verbs:сойтись{}, rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ) rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ) rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ) глагол:ДОСТИЧЬ{}, инфинитив:ДОСТИЧЬ{}, rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте rus_verbs:РАСКЛАДЫВАТЬ{}, rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ) rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ) rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ) rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ) rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ) rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ) rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ) rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта rus_verbs:подпрыгивать{}, rus_verbs:высветиться{}, // на компьютере высветится твоя подпись rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА) rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл) rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл) rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА) rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл) rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл) rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл) rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл) rus_verbs:ОТТОЧИТЬ{}, rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл) rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА) rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл) инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл) глагол:НАХОДИТЬСЯ{ вид:несоверш }, прилагательное:находившийся{ вид:несоверш }, прилагательное:находящийся{ вид:несоверш }, деепричастие:находясь{}, rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл) rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА) rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА) rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл) rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА) rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл) rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА) rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА) rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА) rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА) rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА) rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА) rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА) rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл) rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА) rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА) rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА) rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА) rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА) rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА) rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА) rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл) rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл) rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на) rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к) rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на) глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте) деепричастие:вычитав{}, rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на) rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере rus_verbs:развалиться{}, // Антонио развалился на диване rus_verbs:улечься{}, // Антонио улегся на полу rus_verbs:зарубить{}, // Заруби себе на носу. rus_verbs:ценить{}, // Его ценят на заводе. rus_verbs:вернуться{}, // Отец вернулся на закате. rus_verbs:шить{}, // Вы умеете шить на машинке? rus_verbs:бить{}, // Скот бьют на бойне. rus_verbs:выехать{}, // Мы выехали на рассвете. rus_verbs:валяться{}, // На полу валяется бумага. rus_verbs:разложить{}, // она разложила полотенце на песке rus_verbs:заниматься{}, // я занимаюсь на тренажере rus_verbs:позаниматься{}, rus_verbs:порхать{}, // порхать на лугу rus_verbs:пресекать{}, // пресекать на корню rus_verbs:изъясняться{}, // изъясняться на непонятном языке rus_verbs:развесить{}, // развесить на столбах rus_verbs:обрасти{}, // обрасти на южной части rus_verbs:откладываться{}, // откладываться на стенках артерий rus_verbs:уносить{}, // уносить на носилках rus_verbs:проплыть{}, // проплыть на плоту rus_verbs:подъезжать{}, // подъезжать на повозках rus_verbs:пульсировать{}, // пульсировать на лбу rus_verbs:рассесться{}, // птицы расселись на ветках rus_verbs:застопориться{}, // застопориться на первом пункте rus_verbs:изловить{}, // изловить на окраинах rus_verbs:покататься{}, // покататься на машинках rus_verbs:залопотать{}, // залопотать на неизвестном языке rus_verbs:растягивать{}, // растягивать на станке rus_verbs:поделывать{}, // поделывать на пляже rus_verbs:подстеречь{}, // подстеречь на площадке rus_verbs:проектировать{}, // проектировать на компьютере rus_verbs:притулиться{}, // притулиться на кушетке rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище rus_verbs:пострелять{}, // пострелять на испытательном полигоне rus_verbs:засиживаться{}, // засиживаться на работе rus_verbs:нежиться{}, // нежиться на солнышке rus_verbs:притомиться{}, // притомиться на рабочем месте rus_verbs:поселяться{}, // поселяться на чердаке rus_verbs:потягиваться{}, // потягиваться на земле rus_verbs:отлеживаться{}, // отлеживаться на койке rus_verbs:протаранить{}, // протаранить на танке rus_verbs:гарцевать{}, // гарцевать на коне rus_verbs:облупиться{}, // облупиться на носу rus_verbs:оговорить{}, // оговорить на собеседовании rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте rus_verbs:отпечатать{}, // отпечатать на картоне rus_verbs:сэкономить{}, // сэкономить на мелочах rus_verbs:покатать{}, // покатать на пони rus_verbs:колесить{}, // колесить на старой машине rus_verbs:понастроить{}, // понастроить на участках rus_verbs:поджарить{}, // поджарить на костре rus_verbs:узнаваться{}, // узнаваться на фотографии rus_verbs:отощать{}, // отощать на казенных харчах rus_verbs:редеть{}, // редеть на макушке rus_verbs:оглашать{}, // оглашать на общем собрании rus_verbs:лопотать{}, // лопотать на иврите rus_verbs:пригреть{}, // пригреть на груди rus_verbs:консультироваться{}, // консультироваться на форуме rus_verbs:приноситься{}, // приноситься на одежде rus_verbs:сушиться{}, // сушиться на балконе rus_verbs:наследить{}, // наследить на полу rus_verbs:нагреться{}, // нагреться на солнце rus_verbs:рыбачить{}, // рыбачить на озере rus_verbs:прокатить{}, // прокатить на выборах rus_verbs:запинаться{}, // запинаться на ровном месте rus_verbs:отрубиться{}, // отрубиться на мягкой подушке rus_verbs:заморозить{}, // заморозить на улице rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе rus_verbs:просохнуть{}, // просохнуть на батарее rus_verbs:развозить{}, // развозить на велосипеде rus_verbs:прикорнуть{}, // прикорнуть на диванчике rus_verbs:отпечататься{}, // отпечататься на коже rus_verbs:выявлять{}, // выявлять на таможне rus_verbs:расставлять{}, // расставлять на башнях rus_verbs:прокрутить{}, // прокрутить на пальце rus_verbs:умываться{}, // умываться на улице rus_verbs:пересказывать{}, // пересказывать на страницах романа rus_verbs:удалять{}, // удалять на пуховике rus_verbs:хозяйничать{}, // хозяйничать на складе rus_verbs:оперировать{}, // оперировать на поле боя rus_verbs:поносить{}, // поносить на голове rus_verbs:замурлыкать{}, // замурлыкать на коленях rus_verbs:передвигать{}, // передвигать на тележке rus_verbs:прочертить{}, // прочертить на земле rus_verbs:колдовать{}, // колдовать на кухне rus_verbs:отвозить{}, // отвозить на казенном транспорте rus_verbs:трахать{}, // трахать на природе rus_verbs:мастерить{}, // мастерить на кухне rus_verbs:ремонтировать{}, // ремонтировать на коленке rus_verbs:развезти{}, // развезти на велосипеде rus_verbs:робеть{}, // робеть на сцене инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш }, деепричастие:реализовав{}, деепричастие:реализуя{}, rus_verbs:покаяться{}, // покаяться на смертном одре rus_verbs:специализироваться{}, // специализироваться на тестировании rus_verbs:попрыгать{}, // попрыгать на батуте rus_verbs:переписывать{}, // переписывать на столе rus_verbs:расписывать{}, // расписывать на доске rus_verbs:зажимать{}, // зажимать на запястье rus_verbs:практиковаться{}, // практиковаться на мышах rus_verbs:уединиться{}, // уединиться на чердаке rus_verbs:подохнуть{}, // подохнуть на чужбине rus_verbs:приподниматься{}, // приподниматься на руках rus_verbs:уродиться{}, // уродиться на полях rus_verbs:продолжиться{}, // продолжиться на улице rus_verbs:посапывать{}, // посапывать на диване rus_verbs:ободрать{}, // ободрать на спине rus_verbs:скрючиться{}, // скрючиться на песке rus_verbs:тормознуть{}, // тормознуть на перекрестке rus_verbs:лютовать{}, // лютовать на хуторе rus_verbs:зарегистрировать{}, // зарегистрировать на сайте rus_verbs:переждать{}, // переждать на вершине холма rus_verbs:доминировать{}, // доминировать на территории rus_verbs:публиковать{}, // публиковать на сайте rus_verbs:морщить{}, // морщить на лбу rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном rus_verbs:подрабатывать{}, // подрабатывать на рынке rus_verbs:репетировать{}, // репетировать на заднем дворе rus_verbs:подвернуть{}, // подвернуть на брусчатке rus_verbs:зашелестеть{}, // зашелестеть на ветру rus_verbs:расчесывать{}, // расчесывать на спине rus_verbs:одевать{}, // одевать на рынке rus_verbs:испечь{}, // испечь на углях rus_verbs:сбрить{}, // сбрить на затылке rus_verbs:согреться{}, // согреться на печке rus_verbs:замаячить{}, // замаячить на горизонте rus_verbs:пересчитывать{}, // пересчитывать на пальцах rus_verbs:галдеть{}, // галдеть на крыльце rus_verbs:переплыть{}, // переплыть на плоту rus_verbs:передохнуть{}, // передохнуть на скамейке rus_verbs:прижиться{}, // прижиться на ферме rus_verbs:переправляться{}, // переправляться на плотах rus_verbs:накупить{}, // накупить на блошином рынке rus_verbs:проторчать{}, // проторчать на виду rus_verbs:мокнуть{}, // мокнуть на улице rus_verbs:застукать{}, // застукать на камбузе rus_verbs:завязывать{}, // завязывать на ботинках rus_verbs:повисать{}, // повисать на ветке rus_verbs:подвизаться{}, // подвизаться на государственной службе rus_verbs:кормиться{}, // кормиться на болоте rus_verbs:покурить{}, // покурить на улице rus_verbs:зимовать{}, // зимовать на болотах rus_verbs:застегивать{}, // застегивать на гимнастерке rus_verbs:поигрывать{}, // поигрывать на гитаре rus_verbs:погореть{}, // погореть на махинациях с землей rus_verbs:кувыркаться{}, // кувыркаться на батуте rus_verbs:похрапывать{}, // похрапывать на диване rus_verbs:пригревать{}, // пригревать на груди rus_verbs:завязнуть{}, // завязнуть на болоте rus_verbs:шастать{}, // шастать на втором этаже rus_verbs:заночевать{}, // заночевать на сеновале rus_verbs:отсиживаться{}, // отсиживаться на чердаке rus_verbs:мчать{}, // мчать на байке rus_verbs:сгнить{}, // сгнить на урановых рудниках rus_verbs:тренировать{}, // тренировать на манекенах rus_verbs:повеселиться{}, // повеселиться на празднике rus_verbs:измучиться{}, // измучиться на болоте rus_verbs:увянуть{}, // увянуть на подоконнике rus_verbs:раскрутить{}, // раскрутить на оси rus_verbs:выцвести{}, // выцвести на солнечном свету rus_verbs:изготовлять{}, // изготовлять на коленке rus_verbs:гнездиться{}, // гнездиться на вершине дерева rus_verbs:разогнаться{}, // разогнаться на мотоцикле rus_verbs:излагаться{}, // излагаться на страницах доклада rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге rus_verbs:расчесать{}, // расчесать на макушке rus_verbs:плавиться{}, // плавиться на солнце rus_verbs:редактировать{}, // редактировать на ноутбуке rus_verbs:подскакивать{}, // подскакивать на месте rus_verbs:покупаться{}, // покупаться на рынке rus_verbs:промышлять{}, // промышлять на мелководье rus_verbs:приобретаться{}, // приобретаться на распродажах rus_verbs:наигрывать{}, // наигрывать на банджо rus_verbs:маневрировать{}, // маневрировать на флангах rus_verbs:запечатлеться{}, // запечатлеться на записях камер rus_verbs:укрывать{}, // укрывать на чердаке rus_verbs:подорваться{}, // подорваться на фугасе rus_verbs:закрепиться{}, // закрепиться на занятых позициях rus_verbs:громыхать{}, // громыхать на кухне инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу деепричастие:подвигавшись{}, rus_verbs:добываться{}, // добываться на территории Анголы rus_verbs:приплясывать{}, // приплясывать на сцене rus_verbs:доживать{}, // доживать на больничной койке rus_verbs:отпраздновать{}, // отпраздновать на работе rus_verbs:сгубить{}, // сгубить на корню rus_verbs:схоронить{}, // схоронить на кладбище rus_verbs:тускнеть{}, // тускнеть на солнце rus_verbs:скопить{}, // скопить на счету rus_verbs:помыть{}, // помыть на своем этаже rus_verbs:пороть{}, // пороть на конюшне rus_verbs:наличествовать{}, // наличествовать на складе rus_verbs:нащупывать{}, // нащупывать на полке rus_verbs:змеиться{}, // змеиться на дне rus_verbs:пожелтеть{}, // пожелтеть на солнце rus_verbs:заостриться{}, // заостриться на конце rus_verbs:свезти{}, // свезти на поле rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре rus_verbs:подкрутить{}, // подкрутить на приборной панели rus_verbs:рубиться{}, // рубиться на мечах rus_verbs:сиживать{}, // сиживать на крыльце rus_verbs:тараторить{}, // тараторить на иностранном языке rus_verbs:теплеть{}, // теплеть на сердце rus_verbs:покачаться{}, // покачаться на ветке rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче rus_verbs:развязывать{}, // развязывать на ботинках rus_verbs:подвозить{}, // подвозить на мотороллере rus_verbs:вышивать{}, // вышивать на рубашке rus_verbs:скупать{}, // скупать на открытом рынке rus_verbs:оформлять{}, // оформлять на встрече rus_verbs:распускаться{}, // распускаться на клумбах rus_verbs:прогореть{}, // прогореть на спекуляциях rus_verbs:приползти{}, // приползти на коленях rus_verbs:загореть{}, // загореть на пляже rus_verbs:остудить{}, // остудить на балконе rus_verbs:нарвать{}, // нарвать на поляне rus_verbs:издохнуть{}, // издохнуть на болоте rus_verbs:разгружать{}, // разгружать на дороге rus_verbs:произрастать{}, // произрастать на болотах rus_verbs:разуться{}, // разуться на коврике rus_verbs:сооружать{}, // сооружать на площади rus_verbs:зачитывать{}, // зачитывать на митинге rus_verbs:уместиться{}, // уместиться на ладони rus_verbs:закупить{}, // закупить на рынке rus_verbs:горланить{}, // горланить на улице rus_verbs:экономить{}, // экономить на спичках rus_verbs:исправлять{}, // исправлять на доске rus_verbs:расслабляться{}, // расслабляться на лежаке rus_verbs:скапливаться{}, // скапливаться на крыше rus_verbs:сплетничать{}, // сплетничать на скамеечке rus_verbs:отъезжать{}, // отъезжать на лимузине rus_verbs:отчитывать{}, // отчитывать на собрании rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке rus_verbs:потчевать{}, // потчевать на лаврах rus_verbs:окопаться{}, // окопаться на окраине rus_verbs:загорать{}, // загорать на пляже rus_verbs:обгореть{}, // обгореть на солнце rus_verbs:распознавать{}, // распознавать на фотографии rus_verbs:заплетаться{}, // заплетаться на макушке rus_verbs:перегреться{}, // перегреться на жаре rus_verbs:подметать{}, // подметать на крыльце rus_verbs:нарисоваться{}, // нарисоваться на горизонте rus_verbs:проскакивать{}, // проскакивать на экране rus_verbs:попивать{}, // попивать на балконе чай rus_verbs:отплывать{}, // отплывать на лодке rus_verbs:чирикать{}, // чирикать на ветках rus_verbs:скупить{}, // скупить на оптовых базах rus_verbs:наколоть{}, // наколоть на коже картинку rus_verbs:созревать{}, // созревать на ветке rus_verbs:проколоться{}, // проколоться на мелочи rus_verbs:крутнуться{}, // крутнуться на заднем колесе rus_verbs:переночевать{}, // переночевать на постоялом дворе rus_verbs:концентрироваться{}, // концентрироваться на фильтре rus_verbs:одичать{}, // одичать на хуторе rus_verbs:спасаться{}, // спасаются на лодке rus_verbs:доказываться{}, // доказываться на страницах книги rus_verbs:познаваться{}, // познаваться на ринге rus_verbs:замыкаться{}, // замыкаться на металлическом предмете rus_verbs:заприметить{}, // заприметить на пригорке rus_verbs:продержать{}, // продержать на морозе rus_verbs:форсировать{}, // форсировать на плотах rus_verbs:сохнуть{}, // сохнуть на солнце rus_verbs:выявить{}, // выявить на поверхности rus_verbs:заседать{}, // заседать на кафедре rus_verbs:расплачиваться{}, // расплачиваться на выходе rus_verbs:светлеть{}, // светлеть на горизонте rus_verbs:залепетать{}, // залепетать на незнакомом языке rus_verbs:подсчитывать{}, // подсчитывать на пальцах rus_verbs:зарыть{}, // зарыть на пустыре rus_verbs:сформироваться{}, // сформироваться на месте rus_verbs:развертываться{}, // развертываться на площадке rus_verbs:набивать{}, // набивать на манекенах rus_verbs:замерзать{}, // замерзать на ветру rus_verbs:схватывать{}, // схватывать на лету rus_verbs:перевестись{}, // перевестись на Руси rus_verbs:смешивать{}, // смешивать на блюдце rus_verbs:прождать{}, // прождать на входе rus_verbs:мерзнуть{}, // мерзнуть на ветру rus_verbs:растирать{}, // растирать на коже rus_verbs:переспать{}, // переспал на сеновале rus_verbs:рассекать{}, // рассекать на скутере rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне rus_verbs:дрыхнуть{}, // дрыхнуть на диване rus_verbs:распять{}, // распять на кресте rus_verbs:запечься{}, // запечься на костре rus_verbs:застилать{}, // застилать на балконе rus_verbs:сыскаться{}, // сыскаться на огороде rus_verbs:разориться{}, // разориться на продаже спичек rus_verbs:переделать{}, // переделать на станке rus_verbs:разъяснять{}, // разъяснять на страницах газеты rus_verbs:поседеть{}, // поседеть на висках rus_verbs:протащить{}, // протащить на спине rus_verbs:осуществиться{}, // осуществиться на деле rus_verbs:селиться{}, // селиться на окраине rus_verbs:оплачивать{}, // оплачивать на первой кассе rus_verbs:переворачивать{}, // переворачивать на сковородке rus_verbs:упражняться{}, // упражняться на батуте rus_verbs:испробовать{}, // испробовать на себе rus_verbs:разгладиться{}, // разгладиться на спине rus_verbs:рисоваться{}, // рисоваться на стекле rus_verbs:продрогнуть{}, // продрогнуть на морозе rus_verbs:пометить{}, // пометить на доске rus_verbs:приютить{}, // приютить на чердаке rus_verbs:избирать{}, // избирать на первых свободных выборах rus_verbs:затеваться{}, // затеваться на матче rus_verbs:уплывать{}, // уплывать на катере rus_verbs:замерцать{}, // замерцать на рекламном щите rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне rus_verbs:запираться{}, // запираться на чердаке rus_verbs:загубить{}, // загубить на корню rus_verbs:развеяться{}, // развеяться на природе rus_verbs:съезжаться{}, // съезжаться на лимузинах rus_verbs:потанцевать{}, // потанцевать на могиле rus_verbs:дохнуть{}, // дохнуть на солнце rus_verbs:припарковаться{}, // припарковаться на газоне rus_verbs:отхватить{}, // отхватить на распродаже rus_verbs:остывать{}, // остывать на улице rus_verbs:переваривать{}, // переваривать на высокой ветке rus_verbs:подвесить{}, // подвесить на веревке rus_verbs:хвастать{}, // хвастать на работе rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая rus_verbs:разлечься{}, // разлечься на полу rus_verbs:очертить{}, // очертить на полу rus_verbs:председательствовать{}, // председательствовать на собрании rus_verbs:сконфузиться{}, // сконфузиться на сцене rus_verbs:выявляться{}, // выявляться на ринге rus_verbs:крутануться{}, // крутануться на заднем колесе rus_verbs:караулить{}, // караулить на входе rus_verbs:перечислять{}, // перечислять на пальцах rus_verbs:обрабатывать{}, // обрабатывать на станке rus_verbs:настигать{}, // настигать на берегу rus_verbs:разгуливать{}, // разгуливать на берегу rus_verbs:насиловать{}, // насиловать на пляже rus_verbs:поредеть{}, // поредеть на макушке rus_verbs:учитывать{}, // учитывать на балансе rus_verbs:зарождаться{}, // зарождаться на большой глубине rus_verbs:распространять{}, // распространять на сайтах rus_verbs:пировать{}, // пировать на вершине холма rus_verbs:начертать{}, // начертать на стене rus_verbs:расцветать{}, // расцветать на подоконнике rus_verbs:умнеть{}, // умнеть на глазах rus_verbs:царствовать{}, // царствовать на окраине rus_verbs:закрутиться{}, // закрутиться на работе rus_verbs:отработать{}, // отработать на шахте rus_verbs:полечь{}, // полечь на поле брани rus_verbs:щебетать{}, // щебетать на ветке rus_verbs:подчеркиваться{}, // подчеркиваться на сайте rus_verbs:посеять{}, // посеять на другом поле rus_verbs:замечаться{}, // замечаться на пастбище rus_verbs:просчитать{}, // просчитать на пальцах rus_verbs:голосовать{}, // голосовать на трассе rus_verbs:маяться{}, // маяться на пляже rus_verbs:сколотить{}, // сколотить на службе rus_verbs:обретаться{}, // обретаться на чужбине rus_verbs:обливаться{}, // обливаться на улице rus_verbs:катать{}, // катать на лошадке rus_verbs:припрятать{}, // припрятать на теле rus_verbs:запаниковать{}, // запаниковать на экзамене инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете деепричастие:слетав{}, rus_verbs:срубить{}, // срубить денег на спекуляциях rus_verbs:зажигаться{}, // зажигаться на улице rus_verbs:жарить{}, // жарить на углях rus_verbs:накапливаться{}, // накапливаться на счету rus_verbs:распуститься{}, // распуститься на грядке rus_verbs:рассаживаться{}, // рассаживаться на местах rus_verbs:странствовать{}, // странствовать на лошади rus_verbs:осматриваться{}, // осматриваться на месте rus_verbs:разворачивать{}, // разворачивать на завоеванной территории rus_verbs:согревать{}, // согревать на вершине горы rus_verbs:заскучать{}, // заскучать на вахте rus_verbs:перекусить{}, // перекусить на бегу rus_verbs:приплыть{}, // приплыть на тримаране rus_verbs:зажигать{}, // зажигать на танцах rus_verbs:закопать{}, // закопать на поляне rus_verbs:стирать{}, // стирать на берегу rus_verbs:подстерегать{}, // подстерегать на подходе rus_verbs:погулять{}, // погулять на свадьбе rus_verbs:огласить{}, // огласить на митинге rus_verbs:разбогатеть{}, // разбогатеть на прииске rus_verbs:грохотать{}, // грохотать на чердаке rus_verbs:расположить{}, // расположить на границе rus_verbs:реализоваться{}, // реализоваться на новой работе rus_verbs:застывать{}, // застывать на морозе rus_verbs:запечатлеть{}, // запечатлеть на пленке rus_verbs:тренироваться{}, // тренироваться на манекене rus_verbs:поспорить{}, // поспорить на совещании rus_verbs:затягивать{}, // затягивать на поясе rus_verbs:зиждиться{}, // зиждиться на твердой основе rus_verbs:построиться{}, // построиться на песке rus_verbs:надрываться{}, // надрываться на работе rus_verbs:закипать{}, // закипать на плите rus_verbs:затонуть{}, // затонуть на мелководье rus_verbs:побыть{}, // побыть на фазенде rus_verbs:сгорать{}, // сгорать на солнце инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице деепричастие:пописав{ aux stress="поп^исав" }, rus_verbs:подраться{}, // подраться на сцене rus_verbs:заправить{}, // заправить на последней заправке rus_verbs:обозначаться{}, // обозначаться на карте rus_verbs:просиживать{}, // просиживать на берегу rus_verbs:начертить{}, // начертить на листке rus_verbs:тормозить{}, // тормозить на льду rus_verbs:затевать{}, // затевать на космической базе rus_verbs:задерживать{}, // задерживать на таможне rus_verbs:прилетать{}, // прилетать на частном самолете rus_verbs:полулежать{}, // полулежать на травке rus_verbs:ерзать{}, // ерзать на табуретке rus_verbs:покопаться{}, // покопаться на складе rus_verbs:подвезти{}, // подвезти на машине rus_verbs:полежать{}, // полежать на водном матрасе rus_verbs:стыть{}, // стыть на улице rus_verbs:стынуть{}, // стынуть на улице rus_verbs:скреститься{}, // скреститься на груди rus_verbs:припарковать{}, // припарковать на стоянке rus_verbs:здороваться{}, // здороваться на кафедре rus_verbs:нацарапать{}, // нацарапать на парте rus_verbs:откопать{}, // откопать на поляне rus_verbs:смастерить{}, // смастерить на коленках rus_verbs:довезти{}, // довезти на машине rus_verbs:избивать{}, // избивать на крыше rus_verbs:сварить{}, // сварить на костре rus_verbs:истребить{}, // истребить на корню rus_verbs:раскопать{}, // раскопать на болоте rus_verbs:попить{}, // попить на кухне rus_verbs:заправлять{}, // заправлять на базе rus_verbs:кушать{}, // кушать на кухне rus_verbs:замолкать{}, // замолкать на половине фразы rus_verbs:измеряться{}, // измеряться на весах rus_verbs:сбываться{}, // сбываться на самом деле rus_verbs:изображаться{}, // изображается на сцене rus_verbs:фиксировать{}, // фиксировать на данной высоте rus_verbs:ослаблять{}, // ослаблять на шее rus_verbs:зреть{}, // зреть на грядке rus_verbs:зеленеть{}, // зеленеть на грядке rus_verbs:критиковать{}, // критиковать на страницах газеты rus_verbs:облететь{}, // облететь на самолете rus_verbs:заразиться{}, // заразиться на работе rus_verbs:рассеять{}, // рассеять на территории rus_verbs:печься{}, // печься на костре rus_verbs:поспать{}, // поспать на земле rus_verbs:сплетаться{}, // сплетаться на макушке rus_verbs:удерживаться{}, // удерживаться на расстоянии rus_verbs:помешаться{}, // помешаться на чистоте rus_verbs:ликвидировать{}, // ликвидировать на полигоне rus_verbs:проваляться{}, // проваляться на диване rus_verbs:лечиться{}, // лечиться на дому rus_verbs:обработать{}, // обработать на станке rus_verbs:защелкнуть{}, // защелкнуть на руках rus_verbs:разносить{}, // разносить на одежде rus_verbs:чесать{}, // чесать на груди rus_verbs:наладить{}, // наладить на конвейере выпуск rus_verbs:отряхнуться{}, // отряхнуться на улице rus_verbs:разыгрываться{}, // разыгрываться на скачках rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях rus_verbs:греться{}, // греться на вокзале rus_verbs:засидеться{}, // засидеться на одном месте rus_verbs:материализоваться{}, // материализоваться на границе rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин rus_verbs:перевозить{}, // перевозить на платформе rus_verbs:поиграть{}, // поиграть на скрипке rus_verbs:потоптаться{}, // потоптаться на одном месте rus_verbs:переправиться{}, // переправиться на плоту rus_verbs:забрезжить{}, // забрезжить на горизонте rus_verbs:завывать{}, // завывать на опушке rus_verbs:заваривать{}, // заваривать на кухоньке rus_verbs:перемещаться{}, // перемещаться на спасательном плоту инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке rus_verbs:праздновать{}, // праздновать на улицах rus_verbs:обучить{}, // обучить на корте rus_verbs:орудовать{}, // орудовать на складе rus_verbs:подрасти{}, // подрасти на глядке rus_verbs:шелестеть{}, // шелестеть на ветру rus_verbs:раздеваться{}, // раздеваться на публике rus_verbs:пообедать{}, // пообедать на газоне rus_verbs:жрать{}, // жрать на помойке rus_verbs:исполняться{}, // исполняться на флейте rus_verbs:похолодать{}, // похолодать на улице rus_verbs:гнить{}, // гнить на каторге rus_verbs:прослушать{}, // прослушать на концерте rus_verbs:совещаться{}, // совещаться на заседании rus_verbs:покачивать{}, // покачивать на волнах rus_verbs:отсидеть{}, // отсидеть на гаупвахте rus_verbs:формировать{}, // формировать на секретной базе rus_verbs:захрапеть{}, // захрапеть на кровати rus_verbs:объехать{}, // объехать на попутке rus_verbs:поселить{}, // поселить на верхних этажах rus_verbs:заворочаться{}, // заворочаться на сене rus_verbs:напрятать{}, // напрятать на теле rus_verbs:очухаться{}, // очухаться на земле rus_verbs:полистать{}, // полистать на досуге rus_verbs:завертеть{}, // завертеть на шесте rus_verbs:печатать{}, // печатать на ноуте rus_verbs:отыскаться{}, // отыскаться на складе rus_verbs:зафиксировать{}, // зафиксировать на пленке rus_verbs:расстилаться{}, // расстилаться на столе rus_verbs:заместить{}, // заместить на посту rus_verbs:угасать{}, // угасать на неуправляемом корабле rus_verbs:сразить{}, // сразить на ринге rus_verbs:расплываться{}, // расплываться на жаре rus_verbs:сосчитать{}, // сосчитать на пальцах rus_verbs:сгуститься{}, // сгуститься на небольшой высоте rus_verbs:цитировать{}, // цитировать на плите rus_verbs:ориентироваться{}, // ориентироваться на местности rus_verbs:расширить{}, // расширить на другом конце rus_verbs:обтереть{}, // обтереть на стоянке rus_verbs:подстрелить{}, // подстрелить на охоте rus_verbs:растереть{}, // растереть на твердой поверхности rus_verbs:подавлять{}, // подавлять на первом этапе rus_verbs:смешиваться{}, // смешиваться на поверхности // инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте // деепричастие:вычитав{}, rus_verbs:сократиться{}, // сократиться на втором этапе rus_verbs:занервничать{}, // занервничать на экзамене rus_verbs:соприкоснуться{}, // соприкоснуться на трассе rus_verbs:обозначить{}, // обозначить на плане rus_verbs:обучаться{}, // обучаться на производстве rus_verbs:снизиться{}, // снизиться на большой высоте rus_verbs:простудиться{}, // простудиться на ветру rus_verbs:поддерживаться{}, // поддерживается на встрече rus_verbs:уплыть{}, // уплыть на лодочке rus_verbs:резвиться{}, // резвиться на песочке rus_verbs:поерзать{}, // поерзать на скамеечке rus_verbs:похвастаться{}, // похвастаться на встрече rus_verbs:знакомиться{}, // знакомиться на уроке rus_verbs:проплывать{}, // проплывать на катере rus_verbs:засесть{}, // засесть на чердаке rus_verbs:подцепить{}, // подцепить на дискотеке rus_verbs:обыскать{}, // обыскать на входе rus_verbs:оправдаться{}, // оправдаться на суде rus_verbs:раскрываться{}, // раскрываться на сцене rus_verbs:одеваться{}, // одеваться на вещевом рынке rus_verbs:засветиться{}, // засветиться на фотографиях rus_verbs:употребляться{}, // употребляться на птицефабриках rus_verbs:грабить{}, // грабить на пустыре rus_verbs:гонять{}, // гонять на повышенных оборотах rus_verbs:развеваться{}, // развеваться на древке rus_verbs:основываться{}, // основываться на безусловных фактах rus_verbs:допрашивать{}, // допрашивать на базе rus_verbs:проработать{}, // проработать на стройке rus_verbs:сосредоточить{}, // сосредоточить на месте rus_verbs:сочинять{}, // сочинять на ходу rus_verbs:ползать{}, // ползать на камне rus_verbs:раскинуться{}, // раскинуться на пустыре rus_verbs:уставать{}, // уставать на работе rus_verbs:укрепить{}, // укрепить на конце rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь rus_verbs:одобрять{}, // одобрять на словах rus_verbs:приговорить{}, // приговорить на заседании тройки rus_verbs:чернеть{}, // чернеть на свету rus_verbs:гнуть{}, // гнуть на станке rus_verbs:размещаться{}, // размещаться на бирже rus_verbs:соорудить{}, // соорудить на даче rus_verbs:пастись{}, // пастись на лугу rus_verbs:формироваться{}, // формироваться на дне rus_verbs:таить{}, // таить на дне rus_verbs:приостановиться{}, // приостановиться на середине rus_verbs:топтаться{}, // топтаться на месте rus_verbs:громить{}, // громить на подступах rus_verbs:вычислить{}, // вычислить на бумажке rus_verbs:заказывать{}, // заказывать на сайте rus_verbs:осуществить{}, // осуществить на практике rus_verbs:обосноваться{}, // обосноваться на верхушке rus_verbs:пытать{}, // пытать на электрическом стуле rus_verbs:совершиться{}, // совершиться на заседании rus_verbs:свернуться{}, // свернуться на медленном огне rus_verbs:пролетать{}, // пролетать на дельтаплане rus_verbs:сбыться{}, // сбыться на самом деле rus_verbs:разговориться{}, // разговориться на уроке rus_verbs:разворачиваться{}, // разворачиваться на перекрестке rus_verbs:преподнести{}, // преподнести на блюдечке rus_verbs:напечатать{}, // напечатать на лазернике rus_verbs:прорвать{}, // прорвать на периферии rus_verbs:раскачиваться{}, // раскачиваться на доске rus_verbs:задерживаться{}, // задерживаться на старте rus_verbs:угощать{}, // угощать на вечеринке rus_verbs:шарить{}, // шарить на столе rus_verbs:увеличивать{}, // увеличивать на первом этапе rus_verbs:рехнуться{}, // рехнуться на старости лет rus_verbs:расцвести{}, // расцвести на грядке rus_verbs:закипеть{}, // закипеть на плите rus_verbs:подлететь{}, // подлететь на параплане rus_verbs:рыться{}, // рыться на свалке rus_verbs:добираться{}, // добираться на попутках rus_verbs:продержаться{}, // продержаться на вершине rus_verbs:разыскивать{}, // разыскивать на выставках rus_verbs:освобождать{}, // освобождать на заседании rus_verbs:передвигаться{}, // передвигаться на самокате rus_verbs:проявиться{}, // проявиться на свету rus_verbs:заскользить{}, // заскользить на льду rus_verbs:пересказать{}, // пересказать на сцене студенческого театра rus_verbs:протестовать{}, // протестовать на улице rus_verbs:указываться{}, // указываться на табличках rus_verbs:прискакать{}, // прискакать на лошадке rus_verbs:копошиться{}, // копошиться на свежем воздухе rus_verbs:подсчитать{}, // подсчитать на бумажке rus_verbs:разволноваться{}, // разволноваться на экзамене rus_verbs:завертеться{}, // завертеться на полу rus_verbs:ознакомиться{}, // ознакомиться на ходу rus_verbs:ржать{}, // ржать на уроке rus_verbs:раскинуть{}, // раскинуть на грядках rus_verbs:разгромить{}, // разгромить на ринге rus_verbs:подслушать{}, // подслушать на совещании rus_verbs:описываться{}, // описываться на страницах книги rus_verbs:качаться{}, // качаться на стуле rus_verbs:усилить{}, // усилить на флангах rus_verbs:набросать{}, // набросать на клочке картона rus_verbs:расстреливать{}, // расстреливать на подходе rus_verbs:запрыгать{}, // запрыгать на одной ноге rus_verbs:сыскать{}, // сыскать на чужбине rus_verbs:подтвердиться{}, // подтвердиться на практике rus_verbs:плескаться{}, // плескаться на мелководье rus_verbs:расширяться{}, // расширяться на конце rus_verbs:подержать{}, // подержать на солнце rus_verbs:планироваться{}, // планироваться на общем собрании rus_verbs:сгинуть{}, // сгинуть на чужбине rus_verbs:замкнуться{}, // замкнуться на точке rus_verbs:закачаться{}, // закачаться на ветру rus_verbs:перечитывать{}, // перечитывать на ходу rus_verbs:перелететь{}, // перелететь на дельтаплане rus_verbs:оживать{}, // оживать на солнце rus_verbs:женить{}, // женить на богатой невесте rus_verbs:заглохнуть{}, // заглохнуть на старте rus_verbs:копаться{}, // копаться на полу rus_verbs:развлекаться{}, // развлекаться на дискотеке rus_verbs:печататься{}, // печататься на струйном принтере rus_verbs:обрываться{}, // обрываться на полуслове rus_verbs:ускакать{}, // ускакать на лошадке rus_verbs:подписывать{}, // подписывать на столе rus_verbs:добывать{}, // добывать на выработке rus_verbs:скопиться{}, // скопиться на выходе rus_verbs:повстречать{}, // повстречать на пути rus_verbs:поцеловаться{}, // поцеловаться на площади rus_verbs:растянуть{}, // растянуть на столе rus_verbs:подаваться{}, // подаваться на благотворительном обеде rus_verbs:повстречаться{}, // повстречаться на митинге rus_verbs:примоститься{}, // примоститься на ступеньках rus_verbs:отразить{}, // отразить на страницах доклада rus_verbs:пояснять{}, // пояснять на страницах приложения rus_verbs:накормить{}, // накормить на кухне rus_verbs:поужинать{}, // поужинать на веранде инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге деепричастие:спев{}, инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш }, rus_verbs:топить{}, // топить на мелководье rus_verbs:освоить{}, // освоить на практике rus_verbs:распластаться{}, // распластаться на травке rus_verbs:отплыть{}, // отплыть на старом каяке rus_verbs:улетать{}, // улетать на любом самолете rus_verbs:отстаивать{}, // отстаивать на корте rus_verbs:осуждать{}, // осуждать на словах rus_verbs:переговорить{}, // переговорить на обеде rus_verbs:укрыть{}, // укрыть на чердаке rus_verbs:томиться{}, // томиться на привязи rus_verbs:сжигать{}, // сжигать на полигоне rus_verbs:позавтракать{}, // позавтракать на лоне природы rus_verbs:функционировать{}, // функционирует на солнечной энергии rus_verbs:разместить{}, // разместить на сайте rus_verbs:пронести{}, // пронести на теле rus_verbs:нашарить{}, // нашарить на столе rus_verbs:корчиться{}, // корчиться на полу rus_verbs:распознать{}, // распознать на снимке rus_verbs:повеситься{}, // повеситься на шнуре rus_verbs:обозначиться{}, // обозначиться на картах rus_verbs:оступиться{}, // оступиться на скользком льду rus_verbs:подносить{}, // подносить на блюдечке rus_verbs:расстелить{}, // расстелить на газоне rus_verbs:обсуждаться{}, // обсуждаться на собрании rus_verbs:расписаться{}, // расписаться на бланке rus_verbs:плестись{}, // плестись на привязи rus_verbs:объявиться{}, // объявиться на сцене rus_verbs:повышаться{}, // повышаться на первом датчике rus_verbs:разрабатывать{}, // разрабатывать на заводе rus_verbs:прерывать{}, // прерывать на середине rus_verbs:каяться{}, // каяться на публике rus_verbs:освоиться{}, // освоиться на лошади rus_verbs:подплыть{}, // подплыть на плоту rus_verbs:оскорбить{}, // оскорбить на митинге rus_verbs:торжествовать{}, // торжествовать на пьедестале rus_verbs:поправлять{}, // поправлять на одежде rus_verbs:отражать{}, // отражать на картине rus_verbs:дремать{}, // дремать на кушетке rus_verbs:применяться{}, // применяться на производстве стали rus_verbs:поражать{}, // поражать на большой дистанции rus_verbs:расстрелять{}, // расстрелять на окраине хутора rus_verbs:рассчитать{}, // рассчитать на калькуляторе rus_verbs:записывать{}, // записывать на ленте rus_verbs:перебирать{}, // перебирать на ладони rus_verbs:разбиться{}, // разбиться на катере rus_verbs:поискать{}, // поискать на ферме rus_verbs:прятать{}, // прятать на заброшенном складе rus_verbs:пропеть{}, // пропеть на эстраде rus_verbs:замелькать{}, // замелькать на экране rus_verbs:грустить{}, // грустить на веранде rus_verbs:крутить{}, // крутить на оси rus_verbs:подготовить{}, // подготовить на конспиративной квартире rus_verbs:различать{}, // различать на картинке rus_verbs:киснуть{}, // киснуть на чужбине rus_verbs:оборваться{}, // оборваться на полуслове rus_verbs:запутаться{}, // запутаться на простейшем тесте rus_verbs:общаться{}, // общаться на уроке rus_verbs:производиться{}, // производиться на фабрике rus_verbs:сочинить{}, // сочинить на досуге rus_verbs:давить{}, // давить на лице rus_verbs:разработать{}, // разработать на секретном предприятии rus_verbs:качать{}, // качать на качелях rus_verbs:тушить{}, // тушить на крыше пожар rus_verbs:охранять{}, // охранять на территории базы rus_verbs:приметить{}, // приметить на взгорке rus_verbs:скрыть{}, // скрыть на теле rus_verbs:удерживать{}, // удерживать на руке rus_verbs:усвоить{}, // усвоить на уроке rus_verbs:растаять{}, // растаять на солнечной стороне rus_verbs:красоваться{}, // красоваться на виду rus_verbs:сохраняться{}, // сохраняться на холоде rus_verbs:лечить{}, // лечить на дому rus_verbs:прокатиться{}, // прокатиться на уницикле rus_verbs:договариваться{}, // договариваться на нейтральной территории rus_verbs:качнуться{}, // качнуться на одной ноге rus_verbs:опубликовать{}, // опубликовать на сайте rus_verbs:отражаться{}, // отражаться на поверхности воды rus_verbs:обедать{}, // обедать на веранде rus_verbs:посидеть{}, // посидеть на лавочке rus_verbs:сообщаться{}, // сообщаться на официальном сайте rus_verbs:свершиться{}, // свершиться на заседании rus_verbs:ночевать{}, // ночевать на даче rus_verbs:темнеть{}, // темнеть на свету rus_verbs:гибнуть{}, // гибнуть на территории полигона rus_verbs:усиливаться{}, // усиливаться на территории округа rus_verbs:проживать{}, // проживать на даче rus_verbs:исследовать{}, // исследовать на большой глубине rus_verbs:обитать{}, // обитать на громадной глубине rus_verbs:сталкиваться{}, // сталкиваться на большой высоте rus_verbs:таиться{}, // таиться на большой глубине rus_verbs:спасать{}, // спасать на пожаре rus_verbs:сказываться{}, // сказываться на общем результате rus_verbs:заблудиться{}, // заблудиться на стройке rus_verbs:пошарить{}, // пошарить на полках rus_verbs:планировать{}, // планировать на бумаге rus_verbs:ранить{}, // ранить на полигоне rus_verbs:хлопать{}, // хлопать на сцене rus_verbs:основать{}, // основать на горе новый монастырь rus_verbs:отбить{}, // отбить на столе rus_verbs:отрицать{}, // отрицать на заседании комиссии rus_verbs:устоять{}, // устоять на ногах rus_verbs:отзываться{}, // отзываться на страницах отчёта rus_verbs:притормозить{}, // притормозить на обочине rus_verbs:читаться{}, // читаться на лице rus_verbs:заиграть{}, // заиграть на саксофоне rus_verbs:зависнуть{}, // зависнуть на игровой площадке rus_verbs:сознаться{}, // сознаться на допросе rus_verbs:выясняться{}, // выясняться на очной ставке rus_verbs:наводить{}, // наводить на столе порядок rus_verbs:покоиться{}, // покоиться на кладбище rus_verbs:значиться{}, // значиться на бейджике rus_verbs:съехать{}, // съехать на санках rus_verbs:познакомить{}, // познакомить на свадьбе rus_verbs:завязать{}, // завязать на спине rus_verbs:грохнуть{}, // грохнуть на площади rus_verbs:разъехаться{}, // разъехаться на узкой дороге rus_verbs:столпиться{}, // столпиться на крыльце rus_verbs:порыться{}, // порыться на полках rus_verbs:ослабить{}, // ослабить на шее rus_verbs:оправдывать{}, // оправдывать на суде rus_verbs:обнаруживаться{}, // обнаруживаться на складе rus_verbs:спастись{}, // спастись на дереве rus_verbs:прерваться{}, // прерваться на полуслове rus_verbs:строиться{}, // строиться на пустыре rus_verbs:познать{}, // познать на практике rus_verbs:путешествовать{}, // путешествовать на поезде rus_verbs:побеждать{}, // побеждать на ринге rus_verbs:рассматриваться{}, // рассматриваться на заседании rus_verbs:продаваться{}, // продаваться на открытом рынке rus_verbs:разместиться{}, // разместиться на базе rus_verbs:завыть{}, // завыть на холме rus_verbs:настигнуть{}, // настигнуть на окраине rus_verbs:укрыться{}, // укрыться на чердаке rus_verbs:расплакаться{}, // расплакаться на заседании комиссии rus_verbs:заканчивать{}, // заканчивать на последнем задании rus_verbs:пролежать{}, // пролежать на столе rus_verbs:громоздиться{}, // громоздиться на полу rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе rus_verbs:поскользнуться{}, // поскользнуться на льду rus_verbs:таскать{}, // таскать на спине rus_verbs:просматривать{}, // просматривать на сайте rus_verbs:обдумать{}, // обдумать на досуге rus_verbs:гадать{}, // гадать на кофейной гуще rus_verbs:останавливать{}, // останавливать на выходе rus_verbs:обозначать{}, // обозначать на странице rus_verbs:долететь{}, // долететь на спортивном байке rus_verbs:тесниться{}, // тесниться на чердачке rus_verbs:хоронить{}, // хоронить на частном кладбище rus_verbs:установиться{}, // установиться на юге rus_verbs:прикидывать{}, // прикидывать на клочке бумаги rus_verbs:затаиться{}, // затаиться на дереве rus_verbs:раздобыть{}, // раздобыть на складе rus_verbs:перебросить{}, // перебросить на вертолетах rus_verbs:захватывать{}, // захватывать на базе rus_verbs:сказаться{}, // сказаться на итоговых оценках rus_verbs:покачиваться{}, // покачиваться на волнах rus_verbs:крутиться{}, // крутиться на кухне rus_verbs:помещаться{}, // помещаться на полке rus_verbs:питаться{}, // питаться на помойке rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле rus_verbs:кататься{}, // кататься на велике rus_verbs:поработать{}, // поработать на стройке rus_verbs:ограбить{}, // ограбить на пустыре rus_verbs:зарабатывать{}, // зарабатывать на бирже rus_verbs:преуспеть{}, // преуспеть на ниве искусства rus_verbs:заерзать{}, // заерзать на стуле rus_verbs:разъяснить{}, // разъяснить на полях rus_verbs:отчеканить{}, // отчеканить на медной пластине rus_verbs:торговать{}, // торговать на рынке rus_verbs:поколебаться{}, // поколебаться на пороге rus_verbs:прикинуть{}, // прикинуть на бумажке rus_verbs:рассечь{}, // рассечь на тупом конце rus_verbs:посмеяться{}, // посмеяться на переменке rus_verbs:остыть{}, // остыть на морозном воздухе rus_verbs:запереться{}, // запереться на чердаке rus_verbs:обогнать{}, // обогнать на повороте rus_verbs:подтянуться{}, // подтянуться на турнике rus_verbs:привозить{}, // привозить на машине rus_verbs:подбирать{}, // подбирать на полу rus_verbs:уничтожать{}, // уничтожать на подходе rus_verbs:притаиться{}, // притаиться на вершине rus_verbs:плясать{}, // плясать на костях rus_verbs:поджидать{}, // поджидать на вокзале rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!) rus_verbs:смениться{}, // смениться на посту rus_verbs:посчитать{}, // посчитать на пальцах rus_verbs:прицелиться{}, // прицелиться на бегу rus_verbs:нарисовать{}, // нарисовать на стене rus_verbs:прыгать{}, // прыгать на сцене rus_verbs:повертеть{}, // повертеть на пальце rus_verbs:попрощаться{}, // попрощаться на панихиде инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване rus_verbs:разобрать{}, // разобрать на столе rus_verbs:помереть{}, // помереть на чужбине rus_verbs:различить{}, // различить на нечеткой фотографии rus_verbs:рисовать{}, // рисовать на доске rus_verbs:проследить{}, // проследить на экране rus_verbs:задремать{}, // задремать на диване rus_verbs:ругаться{}, // ругаться на людях rus_verbs:сгореть{}, // сгореть на работе rus_verbs:зазвучать{}, // зазвучать на коротких волнах rus_verbs:задохнуться{}, // задохнуться на вершине горы rus_verbs:порождать{}, // порождать на поверхности небольшую рябь rus_verbs:отдыхать{}, // отдыхать на курорте rus_verbs:образовать{}, // образовать на дне толстый слой rus_verbs:поправиться{}, // поправиться на дармовых харчах rus_verbs:отмечать{}, // отмечать на календаре rus_verbs:реять{}, // реять на флагштоке rus_verbs:ползти{}, // ползти на коленях rus_verbs:продавать{}, // продавать на аукционе rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче rus_verbs:рыскать{}, // мышки рыскали на кухне rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы rus_verbs:напасть{}, // напасть на территории другого государства rus_verbs:издать{}, // издать на западе rus_verbs:оставаться{}, // оставаться на страже порядка rus_verbs:появиться{}, // наконец появиться на экране rus_verbs:лежать{}, // лежать на столе rus_verbs:ждать{}, // ждать на берегу инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге глагол:писать{aux stress="пис^ать"}, rus_verbs:оказываться{}, // оказываться на полу rus_verbs:поставить{}, // поставить на столе rus_verbs:держать{}, // держать на крючке rus_verbs:выходить{}, // выходить на остановке rus_verbs:заговорить{}, // заговорить на китайском языке rus_verbs:ожидать{}, // ожидать на стоянке rus_verbs:закричать{}, // закричал на минарете муэдзин rus_verbs:простоять{}, // простоять на посту rus_verbs:продолжить{}, // продолжить на первом этаже rus_verbs:ощутить{}, // ощутить на себе влияние кризиса rus_verbs:состоять{}, // состоять на учете rus_verbs:готовиться{}, инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте глагол:акклиматизироваться{вид:несоверш}, rus_verbs:арестовать{}, // грабители были арестованы на месте преступления rus_verbs:схватить{}, // грабители были схвачены на месте преступления инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе глагол:атаковать{ вид:соверш }, прилагательное:атакованный{ вид:соверш }, прилагательное:атаковавший{ вид:соверш }, rus_verbs:базировать{}, // установка будет базирована на границе rus_verbs:базироваться{}, // установка базируется на границе rus_verbs:барахтаться{}, // дети барахтались на мелководье rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке rus_verbs:бренчать{}, // парень что-то бренчал на гитаре rus_verbs:бренькать{}, // парень что-то бренькает на гитаре rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории. rus_verbs:буксовать{}, // Колеса буксуют на льду rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле rus_verbs:взвести{}, // Боец взвел на оружии предохранитель rus_verbs:вилять{}, // Машина сильно виляла на дороге rus_verbs:висеть{}, // Яблоко висит на ветке rus_verbs:возлежать{}, // возлежать на лежанке rus_verbs:подниматься{}, // Мы поднимаемся на лифте rus_verbs:подняться{}, // Мы поднимемся на лифте rus_verbs:восседать{}, // Коля восседает на лошади rus_verbs:воссиять{}, // Луна воссияла на небе rus_verbs:воцариться{}, // Мир воцарился на всей земле rus_verbs:воцаряться{}, // Мир воцаряется на всей земле rus_verbs:вращать{}, // вращать на поясе rus_verbs:вращаться{}, // вращаться на поясе rus_verbs:встретить{}, // встретить друга на улице rus_verbs:встретиться{}, // встретиться на занятиях rus_verbs:встречать{}, // встречать на занятиях rus_verbs:въебывать{}, // въебывать на работе rus_verbs:въезжать{}, // въезжать на автомобиле rus_verbs:въехать{}, // въехать на автомобиле rus_verbs:выгорать{}, // ткань выгорает на солнце rus_verbs:выгореть{}, // ткань выгорела на солнце rus_verbs:выгравировать{}, // выгравировать на табличке надпись rus_verbs:выжить{}, // выжить на необитаемом острове rus_verbs:вылежаться{}, // помидоры вылежались на солнце rus_verbs:вылеживаться{}, // вылеживаться на солнце rus_verbs:выместить{}, // выместить на ком-то злобу rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение rus_verbs:вымещаться{}, // вымещаться на ком-то rus_verbs:выращивать{}, // выращивать на грядке помидоры rus_verbs:выращиваться{}, // выращиваться на грядке инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись глагол:вырезать{вид:соверш}, инфинитив:вырезать{вид:несоверш}, глагол:вырезать{вид:несоверш}, rus_verbs:вырисоваться{}, // вырисоваться на графике rus_verbs:вырисовываться{}, // вырисовываться на графике rus_verbs:высаживать{}, // высаживать на необитаемом острове rus_verbs:высаживаться{}, // высаживаться на острове rus_verbs:высвечивать{}, // высвечивать на дисплее температуру rus_verbs:высвечиваться{}, // высвечиваться на дисплее rus_verbs:выстроить{}, // выстроить на фундаменте rus_verbs:выстроиться{}, // выстроиться на плацу rus_verbs:выстудить{}, // выстудить на морозе rus_verbs:выстудиться{}, // выстудиться на морозе rus_verbs:выстужать{}, // выстужать на морозе rus_verbs:выстуживать{}, // выстуживать на морозе rus_verbs:выстуживаться{}, // выстуживаться на морозе rus_verbs:выстукать{}, // выстукать на клавиатуре rus_verbs:выстукивать{}, // выстукивать на клавиатуре rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре rus_verbs:выступать{}, // выступать на сцене rus_verbs:выступить{}, // выступить на сцене rus_verbs:выстучать{}, // выстучать на клавиатуре rus_verbs:выстывать{}, // выстывать на морозе rus_verbs:выстыть{}, // выстыть на морозе rus_verbs:вытатуировать{}, // вытатуировать на руке якорь rus_verbs:говорить{}, // говорить на повышенных тонах rus_verbs:заметить{}, // заметить на берегу rus_verbs:стоять{}, // твёрдо стоять на ногах rus_verbs:оказаться{}, // оказаться на передовой линии rus_verbs:почувствовать{}, // почувствовать на своей шкуре rus_verbs:остановиться{}, // остановиться на первом пункте rus_verbs:показаться{}, // показаться на горизонте rus_verbs:чувствовать{}, // чувствовать на своей шкуре rus_verbs:искать{}, // искать на открытом пространстве rus_verbs:иметься{}, // иметься на складе rus_verbs:клясться{}, // клясться на Коране rus_verbs:прервать{}, // прервать на полуслове rus_verbs:играть{}, // играть на чувствах rus_verbs:спуститься{}, // спуститься на парашюте rus_verbs:понадобиться{}, // понадобиться на экзамене rus_verbs:служить{}, // служить на флоте rus_verbs:подобрать{}, // подобрать на улице rus_verbs:появляться{}, // появляться на сцене rus_verbs:селить{}, // селить на чердаке rus_verbs:поймать{}, // поймать на границе rus_verbs:увидать{}, // увидать на опушке rus_verbs:подождать{}, // подождать на перроне rus_verbs:прочесть{}, // прочесть на полях rus_verbs:тонуть{}, // тонуть на мелководье rus_verbs:ощущать{}, // ощущать на коже rus_verbs:отметить{}, // отметить на полях rus_verbs:показывать{}, // показывать на графике rus_verbs:разговаривать{}, // разговаривать на иностранном языке rus_verbs:прочитать{}, // прочитать на сайте rus_verbs:попробовать{}, // попробовать на практике rus_verbs:замечать{}, // замечать на коже грязь rus_verbs:нести{}, // нести на плечах rus_verbs:носить{}, // носить на голове rus_verbs:гореть{}, // гореть на работе rus_verbs:застыть{}, // застыть на пороге инфинитив:жениться{ вид:соверш }, // жениться на королеве глагол:жениться{ вид:соверш }, прилагательное:женатый{}, прилагательное:женившийся{}, rus_verbs:спрятать{}, // спрятать на чердаке rus_verbs:развернуться{}, // развернуться на плацу rus_verbs:строить{}, // строить на песке rus_verbs:устроить{}, // устроить на даче тестральный вечер rus_verbs:настаивать{}, // настаивать на выполнении приказа rus_verbs:находить{}, // находить на берегу rus_verbs:мелькнуть{}, // мелькнуть на экране rus_verbs:очутиться{}, // очутиться на опушке леса инфинитив:использовать{вид:соверш}, // использовать на работе глагол:использовать{вид:соверш}, инфинитив:использовать{вид:несоверш}, глагол:использовать{вид:несоверш}, прилагательное:использованный{}, прилагательное:использующий{}, прилагательное:использовавший{}, rus_verbs:лететь{}, // лететь на воздушном шаре rus_verbs:смеяться{}, // смеяться на сцене rus_verbs:ездить{}, // ездить на мопеде rus_verbs:заснуть{}, // заснуть на диване rus_verbs:застать{}, // застать на рабочем месте rus_verbs:очнуться{}, // очнуться на больничной койке rus_verbs:разглядеть{}, // разглядеть на фотографии rus_verbs:обойти{}, // обойти на вираже rus_verbs:удержаться{}, // удержаться на троне rus_verbs:побывать{}, // побывать на другой планете rus_verbs:заняться{}, // заняться на выходных делом rus_verbs:вянуть{}, // вянуть на солнце rus_verbs:постоять{}, // постоять на голове rus_verbs:приобрести{}, // приобрести на распродаже rus_verbs:попасться{}, // попасться на краже rus_verbs:продолжаться{}, // продолжаться на земле rus_verbs:открывать{}, // открывать на арене rus_verbs:создавать{}, // создавать на сцене rus_verbs:обсуждать{}, // обсуждать на кухне rus_verbs:отыскать{}, // отыскать на полу rus_verbs:уснуть{}, // уснуть на диване rus_verbs:задержаться{}, // задержаться на работе rus_verbs:курить{}, // курить на свежем воздухе rus_verbs:приподняться{}, // приподняться на локтях rus_verbs:установить{}, // установить на вершине rus_verbs:запереть{}, // запереть на балконе rus_verbs:синеть{}, // синеть на воздухе rus_verbs:убивать{}, // убивать на нейтральной территории rus_verbs:скрываться{}, // скрываться на даче rus_verbs:родить{}, // родить на полу rus_verbs:описать{}, // описать на страницах книги rus_verbs:перехватить{}, // перехватить на подлете rus_verbs:скрывать{}, // скрывать на даче rus_verbs:сменить{}, // сменить на посту rus_verbs:мелькать{}, // мелькать на экране rus_verbs:присутствовать{}, // присутствовать на мероприятии rus_verbs:украсть{}, // украсть на рынке rus_verbs:победить{}, // победить на ринге rus_verbs:упомянуть{}, // упомянуть на страницах романа rus_verbs:плыть{}, // плыть на старой лодке rus_verbs:повиснуть{}, // повиснуть на перекладине rus_verbs:нащупать{}, // нащупать на дне rus_verbs:затихнуть{}, // затихнуть на дне rus_verbs:построить{}, // построить на участке rus_verbs:поддерживать{}, // поддерживать на поверхности rus_verbs:заработать{}, // заработать на бирже rus_verbs:провалиться{}, // провалиться на экзамене rus_verbs:сохранить{}, // сохранить на диске rus_verbs:располагаться{}, // располагаться на софе rus_verbs:поклясться{}, // поклясться на библии rus_verbs:сражаться{}, // сражаться на арене rus_verbs:спускаться{}, // спускаться на дельтаплане rus_verbs:уничтожить{}, // уничтожить на подступах rus_verbs:изучить{}, // изучить на практике rus_verbs:рождаться{}, // рождаться на праздниках rus_verbs:прилететь{}, // прилететь на самолете rus_verbs:догнать{}, // догнать на перекрестке rus_verbs:изобразить{}, // изобразить на бумаге rus_verbs:проехать{}, // проехать на тракторе rus_verbs:приготовить{}, // приготовить на масле rus_verbs:споткнуться{}, // споткнуться на полу rus_verbs:собирать{}, // собирать на берегу rus_verbs:отсутствовать{}, // отсутствовать на тусовке rus_verbs:приземлиться{}, // приземлиться на военном аэродроме rus_verbs:сыграть{}, // сыграть на трубе rus_verbs:прятаться{}, // прятаться на даче rus_verbs:спрятаться{}, // спрятаться на чердаке rus_verbs:провозгласить{}, // провозгласить на митинге rus_verbs:изложить{}, // изложить на бумаге rus_verbs:использоваться{}, // использоваться на практике rus_verbs:замяться{}, // замяться на входе rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота rus_verbs:сверкнуть{}, // сверкнуть на солнце rus_verbs:сверкать{}, // сверкать на свету rus_verbs:задержать{}, // задержать на митинге rus_verbs:осечься{}, // осечься на первом слове rus_verbs:хранить{}, // хранить на банковском счету rus_verbs:шутить{}, // шутить на уроке rus_verbs:кружиться{}, // кружиться на балу rus_verbs:чертить{}, // чертить на доске rus_verbs:отразиться{}, // отразиться на оценках rus_verbs:греть{}, // греть на солнце rus_verbs:рассуждать{}, // рассуждать на страницах своей книги rus_verbs:окружать{}, // окружать на острове rus_verbs:сопровождать{}, // сопровождать на охоте rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте rus_verbs:содержаться{}, // содержаться на приусадебном участке rus_verbs:поселиться{}, // поселиться на даче rus_verbs:запеть{}, // запеть на сцене инфинитив:провозить{ вид:несоверш }, // провозить на теле глагол:провозить{ вид:несоверш }, прилагательное:провезенный{}, прилагательное:провозивший{вид:несоверш}, прилагательное:провозящий{вид:несоверш}, деепричастие:провозя{}, rus_verbs:мочить{}, // мочить на месте rus_verbs:преследовать{}, // преследовать на территории другого штата rus_verbs:пролететь{}, // пролетел на параплане rus_verbs:драться{}, // драться на рапирах rus_verbs:просидеть{}, // просидеть на занятиях rus_verbs:убираться{}, // убираться на балконе rus_verbs:таять{}, // таять на солнце rus_verbs:проверять{}, // проверять на полиграфе rus_verbs:убеждать{}, // убеждать на примере rus_verbs:скользить{}, // скользить на льду rus_verbs:приобретать{}, // приобретать на распродаже rus_verbs:летать{}, // летать на метле rus_verbs:толпиться{}, // толпиться на перроне rus_verbs:плавать{}, // плавать на надувном матрасе rus_verbs:описывать{}, // описывать на страницах повести rus_verbs:пробыть{}, // пробыть на солнце слишком долго rus_verbs:застрять{}, // застрять на верхнем этаже rus_verbs:метаться{}, // метаться на полу rus_verbs:сжечь{}, // сжечь на костре rus_verbs:расслабиться{}, // расслабиться на кушетке rus_verbs:услыхать{}, // услыхать на рынке rus_verbs:удержать{}, // удержать на прежнем уровне rus_verbs:образоваться{}, // образоваться на дне rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа rus_verbs:уезжать{}, // уезжать на попутке rus_verbs:похоронить{}, // похоронить на закрытом кладбище rus_verbs:настоять{}, // настоять на пересмотре оценок rus_verbs:растянуться{}, // растянуться на горячем песке rus_verbs:покрутить{}, // покрутить на шесте rus_verbs:обнаружиться{}, // обнаружиться на болоте rus_verbs:гулять{}, // гулять на свадьбе rus_verbs:утонуть{}, // утонуть на курорте rus_verbs:храниться{}, // храниться на депозите rus_verbs:танцевать{}, // танцевать на свадьбе rus_verbs:трудиться{}, // трудиться на заводе инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати глагол:засыпать{переходность:непереходный вид:несоверш}, деепричастие:засыпая{переходность:непереходный вид:несоверш}, прилагательное:засыпавший{переходность:непереходный вид:несоверш}, прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках rus_verbs:сушить{}, // сушить на открытом воздухе rus_verbs:зашевелиться{}, // зашевелиться на чердаке rus_verbs:обдумывать{}, // обдумывать на досуге rus_verbs:докладывать{}, // докладывать на научной конференции rus_verbs:промелькнуть{}, // промелькнуть на экране // прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории прилагательное:написанный{}, // слово, написанное на заборе rus_verbs:умещаться{}, // компьютер, умещающийся на ладони rus_verbs:открыть{}, // книга, открытая на последней странице rus_verbs:спать{}, // йог, спящий на гвоздях rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте rus_verbs:отобразиться{}, // удивление, отобразившееся на лице rus_verbs:увидеть{}, // на полу я увидел чьи-то следы rus_verbs:видеть{}, // на полу я вижу чьи-то следы rus_verbs:оставить{}, // Мел оставил на доске белый след. rus_verbs:оставлять{}, // Мел оставляет на доске белый след. rus_verbs:встречаться{}, // встречаться на лекциях rus_verbs:познакомиться{}, // познакомиться на занятиях rus_verbs:устроиться{}, // она устроилась на кровати rus_verbs:ложиться{}, // ложись на полу rus_verbs:останавливаться{}, // останавливаться на достигнутом rus_verbs:спотыкаться{}, // спотыкаться на ровном месте rus_verbs:распечатать{}, // распечатать на бумаге rus_verbs:распечатывать{}, // распечатывать на бумаге rus_verbs:просмотреть{}, // просмотреть на бумаге rus_verbs:закрепляться{}, // закрепляться на плацдарме rus_verbs:погреться{}, // погреться на солнышке rus_verbs:мешать{}, // Он мешал краски на палитре. rus_verbs:занять{}, // Он занял первое место на соревнованиях. rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках. деепричастие:женившись{ вид:соверш }, rus_verbs:везти{}, // Он везёт песок на тачке. прилагательное:казненный{}, // Он был казнён на электрическом стуле. rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче. rus_verbs:принести{}, // Официантка принесла нам обед на подносе. rus_verbs:переписать{}, // Перепишите эту рукопись на машинке. rus_verbs:идти{}, // Поезд идёт на малой скорости. rus_verbs:петь{}, // птички поют на рассвете rus_verbs:смотреть{}, // Смотри на обороте. rus_verbs:прибрать{}, // прибрать на столе rus_verbs:прибраться{}, // прибраться на столе rus_verbs:растить{}, // растить капусту на огороде rus_verbs:тащить{}, // тащить ребенка на руках rus_verbs:убирать{}, // убирать на столе rus_verbs:простыть{}, // Я простыл на морозе. rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе. rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках. rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге. rus_verbs:вскочить{}, // У него вскочил прыщ на носу. rus_verbs:свить{}, // У нас на балконе воробей свил гнездо. rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица. rus_verbs:восходить{}, // Солнце восходит на востоке. rus_verbs:блестеть{}, // Снег блестит на солнце. rus_verbs:побить{}, // Рысак побил всех лошадей на скачках. rus_verbs:литься{}, // Реки крови льются на войне. rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах. rus_verbs:клубиться{}, // Пыль клубится на дороге. инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке. // глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути // инфинитив:находиться{вид:несоверш}, rus_verbs:жить{}, // Было интересно жить на курорте. rus_verbs:повидать{}, // Он много повидал на своём веку. rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду. rus_verbs:расположиться{}, // Оба села расположились на берегу реки. rus_verbs:объясняться{}, // Они объясняются на иностранном языке. rus_verbs:прощаться{}, // Они долго прощались на вокзале. rus_verbs:работать{}, // Она работает на ткацкой фабрике. rus_verbs:купить{}, // Она купила молоко на рынке. rus_verbs:поместиться{}, // Все книги поместились на полке. глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике. rus_verbs:пожить{}, // Недолго она пожила на свете. rus_verbs:краснеть{}, // Небо краснеет на закате. rus_verbs:бывать{}, // На Волге бывает сильное волнение. rus_verbs:ехать{}, // Мы туда ехали на автобусе. rus_verbs:провести{}, // Мы провели месяц на даче. rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице. rus_verbs:расти{}, // Арбузы растут теперь не только на юге. ГЛ_ИНФ(сидеть), // три больших пса сидят на траве ГЛ_ИНФ(сесть), // три больших пса сели на траву ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль ГЛ_ИНФ(повезти), // я повезу тебя на машине ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси ГЛ_ИНФ(пить), // пить на кухне чай ГЛ_ИНФ(найти), // найти на острове ГЛ_ИНФ(быть), // на этих костях есть следы зубов ГЛ_ИНФ(высадиться), // помощники высадились на острове ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове ГЛ_ИНФ(случиться), // это случилось на опушке леса ГЛ_ИНФ(продать), ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: смотреть на youtube fact гл_предл { if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} } then return true } // локатив fact гл_предл { if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} } then return true } #endregion ПРЕДЛОЖНЫЙ #region ВИНИТЕЛЬНЫЙ // НА+винительный падеж: // ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ #region VerbList wordentry_set Гл_НА_Вин= { rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили. rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку. rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай. rus_verbs:умножить{}, // Умножьте это количество примерно на 10. //rus_verbs:умножать{}, rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу. rus_verbs:откатывать{}, rus_verbs:доносить{}, // Вот и побежали на вас доносить. rus_verbs:донести{}, rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали. безлич_глагол:хватит{}, // - На одну атаку хватит. rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты. rus_verbs:поскупиться{}, // Не поскупись на похвалы! rus_verbs:подыматься{}, rus_verbs:транспортироваться{}, rus_verbs:бахнуть{}, // Бахнуть стакан на пол rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ) rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ) rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ) rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ) rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ) rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ) rus_verbs:БРЫЗГАТЬ{}, rus_verbs:БРЫЗНУТЬ{}, rus_verbs:КАПНУТЬ{}, rus_verbs:КАПАТЬ{}, rus_verbs:ПОКАПАТЬ{}, rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ) rus_verbs:ОХОТИТЬСЯ{}, // rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ) rus_verbs:НАРВАТЬСЯ{}, // rus_verbs:НАТОЛКНУТЬСЯ{}, // rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ) прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ) rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ) rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ) rus_verbs:СТАЛКИВАТЬ{}, // rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ) rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ) rus_verbs:ПЕРЕБРОСИТЬ{}, // rus_verbs:НАБРАСЫВАТЬ{}, // rus_verbs:НАБРОСИТЬ{}, // rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ) rus_verbs:СВОРАЧИВАТЬ{}, // // rus_verbs:ПОВЕРНУТЬ{}, // rus_verbs:ПОВОРАЧИВАТЬ{}, // rus_verbs:наорать{}, rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ) rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ) rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:перегонять{}, rus_verbs:выгонять{}, rus_verbs:выгнать{}, rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ) rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ) rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ) rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ) rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций rus_verbs:назначаться{}, // назначаться на пост rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин) rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА) // rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА) rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА) rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин) rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА) rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА) rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин) rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА) rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА) rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА) rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА) прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА) rus_verbs:посыпаться{}, // на Нину посыпались снежинки инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод. глагол:нарезаться{ вид:несоверш }, rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу rus_verbs:показать{}, // Вадим показал на Колю rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В) rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА) rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА) прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА) rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на) rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА) rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА) rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на) rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА) rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА) rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на) rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на) rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на) rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на) rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на) rus_verbs:верить{}, // верить людям на слово (верить на слово) rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру. rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору. rus_verbs:пасть{}, // Жребий пал на меня. rus_verbs:ездить{}, // Вчера мы ездили на оперу. rus_verbs:влезть{}, // Мальчик влез на дерево. rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу. rus_verbs:разбиться{}, // окно разбилось на мелкие осколки rus_verbs:бежать{}, // я бегу на урок rus_verbs:сбегаться{}, // сбегаться на происшествие rus_verbs:присылать{}, // присылать на испытание rus_verbs:надавить{}, // надавить на педать rus_verbs:внести{}, // внести законопроект на рассмотрение rus_verbs:вносить{}, // вносить законопроект на рассмотрение rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек. rus_verbs:оглядываться{}, // оглядываться на девушек rus_verbs:расходиться{}, // расходиться на отдых rus_verbs:поскакать{}, // поскакать на службу rus_verbs:прыгать{}, // прыгать на сцену rus_verbs:приглашать{}, // приглашать на обед rus_verbs:рваться{}, // Кусок ткани рвется на части rus_verbs:понестись{}, // понестись на волю rus_verbs:распространяться{}, // распространяться на всех жителей штата инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, деепричастие:просыпавшись{}, деепричастие:просыпаясь{}, rus_verbs:заехать{}, // заехать на пандус rus_verbs:разобрать{}, // разобрать на составляющие rus_verbs:опускаться{}, // опускаться на колени rus_verbs:переехать{}, // переехать на конспиративную квартиру rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов rus_verbs:поместить{}, // поместить на поднос rus_verbs:отходить{}, // отходить на подготовленные позиции rus_verbs:сыпаться{}, // сыпаться на плечи rus_verbs:отвезти{}, // отвезти на занятия rus_verbs:накинуть{}, // накинуть на плечи rus_verbs:отлететь{}, // отлететь на пол rus_verbs:закинуть{}, // закинуть на чердак rus_verbs:зашипеть{}, // зашипеть на собаку rus_verbs:прогреметь{}, // прогреметь на всю страну rus_verbs:повалить{}, // повалить на стол rus_verbs:опереть{}, // опереть на фундамент rus_verbs:забросить{}, // забросить на антресоль rus_verbs:подействовать{}, // подействовать на материал rus_verbs:разделять{}, // разделять на части rus_verbs:прикрикнуть{}, // прикрикнуть на детей rus_verbs:разложить{}, // разложить на множители rus_verbs:провожать{}, // провожать на работу rus_verbs:катить{}, // катить на стройку rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью rus_verbs:сохранять{}, // сохранять на память rus_verbs:злиться{}, // злиться на друга rus_verbs:оборачиваться{}, // оборачиваться на свист rus_verbs:сползти{}, // сползти на землю rus_verbs:записывать{}, // записывать на ленту rus_verbs:загнать{}, // загнать на дерево rus_verbs:забормотать{}, // забормотать на ухо rus_verbs:протиснуться{}, // протиснуться на самый край rus_verbs:заторопиться{}, // заторопиться на вручение премии rus_verbs:гаркнуть{}, // гаркнуть на шалунов rus_verbs:навалиться{}, // навалиться на виновника всей толпой rus_verbs:проскользнуть{}, // проскользнуть на крышу дома rus_verbs:подтянуть{}, // подтянуть на палубу rus_verbs:скатиться{}, // скатиться на двойки rus_verbs:давить{}, // давить на жалость rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства rus_verbs:замахнуться{}, // замахнуться на святое rus_verbs:заменить{}, // заменить на свежую салфетку rus_verbs:свалить{}, // свалить на землю rus_verbs:стекать{}, // стекать на оголенные провода rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов rus_verbs:развалиться{}, // развалиться на части rus_verbs:сердиться{}, // сердиться на товарища rus_verbs:обронить{}, // обронить на пол rus_verbs:подсесть{}, // подсесть на наркоту rus_verbs:реагировать{}, // реагировать на импульсы rus_verbs:отпускать{}, // отпускать на волю rus_verbs:прогнать{}, // прогнать на рабочее место rus_verbs:ложить{}, // ложить на стол rus_verbs:рвать{}, // рвать на части rus_verbs:разлететься{}, // разлететься на кусочки rus_verbs:превышать{}, // превышать на существенную величину rus_verbs:сбиться{}, // сбиться на рысь rus_verbs:пристроиться{}, // пристроиться на хорошую работу rus_verbs:удрать{}, // удрать на пастбище rus_verbs:толкать{}, // толкать на преступление rus_verbs:посматривать{}, // посматривать на экран rus_verbs:набирать{}, // набирать на судно rus_verbs:отступать{}, // отступать на дерево rus_verbs:подуть{}, // подуть на молоко rus_verbs:плеснуть{}, // плеснуть на голову rus_verbs:соскользнуть{}, // соскользнуть на землю rus_verbs:затаить{}, // затаить на кого-то обиду rus_verbs:обижаться{}, // обижаться на Колю rus_verbs:смахнуть{}, // смахнуть на пол rus_verbs:застегнуть{}, // застегнуть на все пуговицы rus_verbs:спускать{}, // спускать на землю rus_verbs:греметь{}, // греметь на всю округу rus_verbs:скосить{}, // скосить на соседа глаз rus_verbs:отважиться{}, // отважиться на прыжок rus_verbs:литься{}, // литься на землю rus_verbs:порвать{}, // порвать на тряпки rus_verbs:проследовать{}, // проследовать на сцену rus_verbs:надевать{}, // надевать на голову rus_verbs:проскочить{}, // проскочить на красный свет rus_verbs:прилечь{}, // прилечь на диванчик rus_verbs:разделиться{}, // разделиться на небольшие группы rus_verbs:завыть{}, // завыть на луну rus_verbs:переносить{}, // переносить на другую машину rus_verbs:наговорить{}, // наговорить на сотню рублей rus_verbs:намекать{}, // намекать на новые обстоятельства rus_verbs:нападать{}, // нападать на охранников rus_verbs:убегать{}, // убегать на другое место rus_verbs:тратить{}, // тратить на развлечения rus_verbs:присаживаться{}, // присаживаться на корточки rus_verbs:переместиться{}, // переместиться на вторую линию rus_verbs:завалиться{}, // завалиться на диван rus_verbs:удалиться{}, // удалиться на покой rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов rus_verbs:обрушить{}, // обрушить на голову rus_verbs:резать{}, // резать на части rus_verbs:умчаться{}, // умчаться на юг rus_verbs:навернуться{}, // навернуться на камень rus_verbs:примчаться{}, // примчаться на матч rus_verbs:издавать{}, // издавать на собственные средства rus_verbs:переключить{}, // переключить на другой язык rus_verbs:отправлять{}, // отправлять на пенсию rus_verbs:залечь{}, // залечь на дно rus_verbs:установиться{}, // установиться на диск rus_verbs:направлять{}, // направлять на дополнительное обследование rus_verbs:разрезать{}, // разрезать на части rus_verbs:оскалиться{}, // оскалиться на прохожего rus_verbs:рычать{}, // рычать на пьяных rus_verbs:погружаться{}, // погружаться на дно rus_verbs:опираться{}, // опираться на костыли rus_verbs:поторопиться{}, // поторопиться на учебу rus_verbs:сдвинуться{}, // сдвинуться на сантиметр rus_verbs:увеличить{}, // увеличить на процент rus_verbs:опускать{}, // опускать на землю rus_verbs:созвать{}, // созвать на митинг rus_verbs:делить{}, // делить на части rus_verbs:пробиться{}, // пробиться на заключительную часть rus_verbs:простираться{}, // простираться на много миль rus_verbs:забить{}, // забить на учебу rus_verbs:переложить{}, // переложить на чужие плечи rus_verbs:грохнуться{}, // грохнуться на землю rus_verbs:прорваться{}, // прорваться на сцену rus_verbs:разлить{}, // разлить на землю rus_verbs:укладываться{}, // укладываться на ночевку rus_verbs:уволить{}, // уволить на пенсию rus_verbs:наносить{}, // наносить на кожу rus_verbs:набежать{}, // набежать на берег rus_verbs:заявиться{}, // заявиться на стрельбище rus_verbs:налиться{}, // налиться на крышку rus_verbs:надвигаться{}, // надвигаться на берег rus_verbs:распустить{}, // распустить на каникулы rus_verbs:переключиться{}, // переключиться на другую задачу rus_verbs:чихнуть{}, // чихнуть на окружающих rus_verbs:шлепнуться{}, // шлепнуться на спину rus_verbs:устанавливать{}, // устанавливать на крышу rus_verbs:устанавливаться{}, // устанавливаться на крышу rus_verbs:устраиваться{}, // устраиваться на работу rus_verbs:пропускать{}, // пропускать на стадион инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, деепричастие:сбегав{}, деепричастие:сбегая{}, rus_verbs:показываться{}, // показываться на глаза rus_verbs:прибегать{}, // прибегать на урок rus_verbs:съездить{}, // съездить на ферму rus_verbs:прославиться{}, // прославиться на всю страну rus_verbs:опрокинуться{}, // опрокинуться на спину rus_verbs:насыпать{}, // насыпать на землю rus_verbs:употреблять{}, // употреблять на корм скоту rus_verbs:пристроить{}, // пристроить на работу rus_verbs:заворчать{}, // заворчать на вошедшего rus_verbs:завязаться{}, // завязаться на поставщиков rus_verbs:сажать{}, // сажать на стул rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры rus_verbs:заменять{}, // заменять на исправную rus_verbs:нацепить{}, // нацепить на голову rus_verbs:сыпать{}, // сыпать на землю rus_verbs:закрываться{}, // закрываться на ремонт rus_verbs:распространиться{}, // распространиться на всю популяцию rus_verbs:поменять{}, // поменять на велосипед rus_verbs:пересесть{}, // пересесть на велосипеды rus_verbs:подоспеть{}, // подоспеть на разбор rus_verbs:шипеть{}, // шипеть на собак rus_verbs:поделить{}, // поделить на части rus_verbs:подлететь{}, // подлететь на расстояние выстрела rus_verbs:нажимать{}, // нажимать на все кнопки rus_verbs:распасться{}, // распасться на части rus_verbs:приволочь{}, // приволочь на диван rus_verbs:пожить{}, // пожить на один доллар rus_verbs:устремляться{}, // устремляться на свободу rus_verbs:смахивать{}, // смахивать на пол rus_verbs:забежать{}, // забежать на обед rus_verbs:увеличиться{}, // увеличиться на существенную величину rus_verbs:прокрасться{}, // прокрасться на склад rus_verbs:пущать{}, // пущать на постой rus_verbs:отклонить{}, // отклонить на несколько градусов rus_verbs:насмотреться{}, // насмотреться на безобразия rus_verbs:настроить{}, // настроить на короткие волны rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров rus_verbs:поменяться{}, // поменяться на другую книжку rus_verbs:расколоться{}, // расколоться на части rus_verbs:разлиться{}, // разлиться на землю rus_verbs:срываться{}, // срываться на жену rus_verbs:осудить{}, // осудить на пожизненное заключение rus_verbs:передвинуть{}, // передвинуть на первое место rus_verbs:допускаться{}, // допускаться на полигон rus_verbs:задвинуть{}, // задвинуть на полку rus_verbs:повлиять{}, // повлиять на оценку rus_verbs:отбавлять{}, // отбавлять на осмотр rus_verbs:сбрасывать{}, // сбрасывать на землю rus_verbs:накинуться{}, // накинуться на случайных прохожих rus_verbs:пролить{}, // пролить на кожу руки rus_verbs:затащить{}, // затащить на сеновал rus_verbs:перебежать{}, // перебежать на сторону противника rus_verbs:наливать{}, // наливать на скатерть rus_verbs:пролезть{}, // пролезть на сцену rus_verbs:откладывать{}, // откладывать на черный день rus_verbs:распадаться{}, // распадаться на небольшие фрагменты rus_verbs:перечислить{}, // перечислить на счет rus_verbs:закачаться{}, // закачаться на верхний уровень rus_verbs:накрениться{}, // накрениться на правый борт rus_verbs:подвинуться{}, // подвинуться на один уровень rus_verbs:разнести{}, // разнести на мелкие кусочки rus_verbs:зажить{}, // зажить на широкую ногу rus_verbs:оглохнуть{}, // оглохнуть на правое ухо rus_verbs:посетовать{}, // посетовать на бюрократизм rus_verbs:уводить{}, // уводить на осмотр rus_verbs:ускакать{}, // ускакать на забег rus_verbs:посветить{}, // посветить на стену rus_verbs:разрываться{}, // разрываться на части rus_verbs:побросать{}, // побросать на землю rus_verbs:карабкаться{}, // карабкаться на скалу rus_verbs:нахлынуть{}, // нахлынуть на кого-то rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки rus_verbs:среагировать{}, // среагировать на сигнал rus_verbs:претендовать{}, // претендовать на приз rus_verbs:дунуть{}, // дунуть на одуванчик rus_verbs:переводиться{}, // переводиться на другую работу rus_verbs:перевезти{}, // перевезти на другую площадку rus_verbs:топать{}, // топать на урок rus_verbs:относить{}, // относить на склад rus_verbs:сбивать{}, // сбивать на землю rus_verbs:укладывать{}, // укладывать на спину rus_verbs:укатить{}, // укатить на отдых rus_verbs:убирать{}, // убирать на полку rus_verbs:опасть{}, // опасть на землю rus_verbs:ронять{}, // ронять на снег rus_verbs:пялиться{}, // пялиться на тело rus_verbs:глазеть{}, // глазеть на тело rus_verbs:снижаться{}, // снижаться на безопасную высоту rus_verbs:запрыгнуть{}, // запрыгнуть на платформу rus_verbs:разбиваться{}, // разбиваться на главы rus_verbs:сгодиться{}, // сгодиться на фарш rus_verbs:перескочить{}, // перескочить на другую страницу rus_verbs:нацелиться{}, // нацелиться на главную добычу rus_verbs:заезжать{}, // заезжать на бордюр rus_verbs:забираться{}, // забираться на крышу rus_verbs:проорать{}, // проорать на всё село rus_verbs:сбежаться{}, // сбежаться на шум rus_verbs:сменять{}, // сменять на хлеб rus_verbs:мотать{}, // мотать на ус rus_verbs:раскалываться{}, // раскалываться на две половинки rus_verbs:коситься{}, // коситься на режиссёра rus_verbs:плевать{}, // плевать на законы rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение rus_verbs:наставить{}, // наставить на путь истинный rus_verbs:завывать{}, // завывать на Луну rus_verbs:опаздывать{}, // опаздывать на совещание rus_verbs:залюбоваться{}, // залюбоваться на пейзаж rus_verbs:повергнуть{}, // повергнуть на землю rus_verbs:надвинуть{}, // надвинуть на лоб rus_verbs:стекаться{}, // стекаться на площадь rus_verbs:обозлиться{}, // обозлиться на тренера rus_verbs:оттянуть{}, // оттянуть на себя rus_verbs:истратить{}, // истратить на дешевых шлюх rus_verbs:вышвырнуть{}, // вышвырнуть на улицу rus_verbs:затолкать{}, // затолкать на верхнюю полку rus_verbs:заскочить{}, // заскочить на огонек rus_verbs:проситься{}, // проситься на улицу rus_verbs:натыкаться{}, // натыкаться на борщевик rus_verbs:обрушиваться{}, // обрушиваться на митингующих rus_verbs:переписать{}, // переписать на чистовик rus_verbs:переноситься{}, // переноситься на другое устройство rus_verbs:напроситься{}, // напроситься на обидный ответ rus_verbs:натягивать{}, // натягивать на ноги rus_verbs:кидаться{}, // кидаться на прохожих rus_verbs:откликаться{}, // откликаться на призыв rus_verbs:поспевать{}, // поспевать на балет rus_verbs:обратиться{}, // обратиться на кафедру rus_verbs:полюбоваться{}, // полюбоваться на бюст rus_verbs:таращиться{}, // таращиться на мустангов rus_verbs:напороться{}, // напороться на колючки rus_verbs:раздать{}, // раздать на руки rus_verbs:дивиться{}, // дивиться на танцовщиц rus_verbs:назначать{}, // назначать на ответственнейший пост rus_verbs:кидать{}, // кидать на балкон rus_verbs:нахлобучить{}, // нахлобучить на башку rus_verbs:увлекать{}, // увлекать на луг rus_verbs:ругнуться{}, // ругнуться на животину rus_verbs:переселиться{}, // переселиться на хутор rus_verbs:разрывать{}, // разрывать на части rus_verbs:утащить{}, // утащить на дерево rus_verbs:наставлять{}, // наставлять на путь rus_verbs:соблазнить{}, // соблазнить на обмен rus_verbs:накладывать{}, // накладывать на рану rus_verbs:набрести{}, // набрести на грибную поляну rus_verbs:наведываться{}, // наведываться на прежнюю работу rus_verbs:погулять{}, // погулять на чужие деньги rus_verbs:уклоняться{}, // уклоняться на два градуса влево rus_verbs:слезать{}, // слезать на землю rus_verbs:клевать{}, // клевать на мотыля // rus_verbs:назначаться{}, // назначаться на пост rus_verbs:напялить{}, // напялить на голову rus_verbs:натянуться{}, // натянуться на рамку rus_verbs:разгневаться{}, // разгневаться на придворных rus_verbs:эмигрировать{}, // эмигрировать на Кипр rus_verbs:накатить{}, // накатить на основу rus_verbs:пригнать{}, // пригнать на пастбище rus_verbs:обречь{}, // обречь на мучения rus_verbs:сокращаться{}, // сокращаться на четверть rus_verbs:оттеснить{}, // оттеснить на пристань rus_verbs:подбить{}, // подбить на аферу rus_verbs:заманить{}, // заманить на дерево инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик // деепричастие:пописав{ aux stress="поп^исать" }, rus_verbs:посходить{}, // посходить на перрон rus_verbs:налечь{}, // налечь на мясцо rus_verbs:отбирать{}, // отбирать на флот rus_verbs:нашептывать{}, // нашептывать на ухо rus_verbs:откладываться{}, // откладываться на будущее rus_verbs:залаять{}, // залаять на грабителя rus_verbs:настроиться{}, // настроиться на прием rus_verbs:разбивать{}, // разбивать на куски rus_verbs:пролиться{}, // пролиться на почву rus_verbs:сетовать{}, // сетовать на объективные трудности rus_verbs:подвезти{}, // подвезти на митинг rus_verbs:припереться{}, // припереться на праздник rus_verbs:подталкивать{}, // подталкивать на прыжок rus_verbs:прорываться{}, // прорываться на сцену rus_verbs:снижать{}, // снижать на несколько процентов rus_verbs:нацелить{}, // нацелить на танк rus_verbs:расколоть{}, // расколоть на два куска rus_verbs:увозить{}, // увозить на обкатку rus_verbs:оседать{}, // оседать на дно rus_verbs:съедать{}, // съедать на ужин rus_verbs:навлечь{}, // навлечь на себя rus_verbs:равняться{}, // равняться на лучших rus_verbs:сориентироваться{}, // сориентироваться на местности rus_verbs:снизить{}, // снизить на несколько процентов rus_verbs:перенестись{}, // перенестись на много лет назад rus_verbs:завезти{}, // завезти на склад rus_verbs:проложить{}, // проложить на гору rus_verbs:понадеяться{}, // понадеяться на удачу rus_verbs:заступить{}, // заступить на вахту rus_verbs:засеменить{}, // засеменить на выход rus_verbs:запирать{}, // запирать на ключ rus_verbs:скатываться{}, // скатываться на землю rus_verbs:дробить{}, // дробить на части rus_verbs:разваливаться{}, // разваливаться на кусочки rus_verbs:завозиться{}, // завозиться на склад rus_verbs:нанимать{}, // нанимать на дневную работу rus_verbs:поспеть{}, // поспеть на концерт rus_verbs:променять{}, // променять на сытость rus_verbs:переправить{}, // переправить на север rus_verbs:налетать{}, // налетать на силовое поле rus_verbs:затворить{}, // затворить на замок rus_verbs:подогнать{}, // подогнать на пристань rus_verbs:наехать{}, // наехать на камень rus_verbs:распевать{}, // распевать на разные голоса rus_verbs:разносить{}, // разносить на клочки rus_verbs:преувеличивать{}, // преувеличивать на много килограммов rus_verbs:хромать{}, // хромать на одну ногу rus_verbs:телеграфировать{}, // телеграфировать на базу rus_verbs:порезать{}, // порезать на лоскуты rus_verbs:порваться{}, // порваться на части rus_verbs:загонять{}, // загонять на дерево rus_verbs:отбывать{}, // отбывать на место службы rus_verbs:усаживаться{}, // усаживаться на трон rus_verbs:накопить{}, // накопить на квартиру rus_verbs:зыркнуть{}, // зыркнуть на визитера rus_verbs:копить{}, // копить на машину rus_verbs:помещать{}, // помещать на верхнюю грань rus_verbs:сползать{}, // сползать на снег rus_verbs:попроситься{}, // попроситься на улицу rus_verbs:перетащить{}, // перетащить на чердак rus_verbs:растащить{}, // растащить на сувениры rus_verbs:ниспадать{}, // ниспадать на землю rus_verbs:сфотографировать{}, // сфотографировать на память rus_verbs:нагонять{}, // нагонять на конкурентов страх rus_verbs:покушаться{}, // покушаться на понтифика rus_verbs:покуситься{}, rus_verbs:наняться{}, // наняться на службу rus_verbs:просачиваться{}, // просачиваться на поверхность rus_verbs:пускаться{}, // пускаться на ветер rus_verbs:отваживаться{}, // отваживаться на прыжок rus_verbs:досадовать{}, // досадовать на объективные трудности rus_verbs:унестись{}, // унестись на небо rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов rus_verbs:насадить{}, // насадить на копьё rus_verbs:нагрянуть{}, // нагрянуть на праздник rus_verbs:зашвырнуть{}, // зашвырнуть на полку rus_verbs:грешить{}, // грешить на постояльцев rus_verbs:просочиться{}, // просочиться на поверхность rus_verbs:надоумить{}, // надоумить на глупость rus_verbs:намотать{}, // намотать на шпиндель rus_verbs:замкнуть{}, // замкнуть на корпус rus_verbs:цыкнуть{}, // цыкнуть на детей rus_verbs:переворачиваться{}, // переворачиваться на спину rus_verbs:соваться{}, // соваться на площать rus_verbs:отлучиться{}, // отлучиться на обед rus_verbs:пенять{}, // пенять на себя rus_verbs:нарезать{}, // нарезать на ломтики rus_verbs:поставлять{}, // поставлять на Кипр rus_verbs:залезать{}, // залезать на балкон rus_verbs:отлучаться{}, // отлучаться на обед rus_verbs:сбиваться{}, // сбиваться на шаг rus_verbs:таращить{}, // таращить глаза на вошедшего rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню rus_verbs:опережать{}, // опережать на пару сантиметров rus_verbs:переставить{}, // переставить на стол rus_verbs:раздирать{}, // раздирать на части rus_verbs:затвориться{}, // затвориться на засовы rus_verbs:материться{}, // материться на кого-то rus_verbs:наскочить{}, // наскочить на риф rus_verbs:набираться{}, // набираться на борт rus_verbs:покрикивать{}, // покрикивать на помощников rus_verbs:заменяться{}, // заменяться на более новый rus_verbs:подсадить{}, // подсадить на верхнюю полку rus_verbs:проковылять{}, // проковылять на кухню rus_verbs:прикатить{}, // прикатить на старт rus_verbs:залететь{}, // залететь на чужую территорию rus_verbs:загрузить{}, // загрузить на конвейер rus_verbs:уплывать{}, // уплывать на материк rus_verbs:опозорить{}, // опозорить на всю деревню rus_verbs:провоцировать{}, // провоцировать на ответную агрессию rus_verbs:забивать{}, // забивать на учебу rus_verbs:набегать{}, // набегать на прибрежные деревни rus_verbs:запираться{}, // запираться на ключ rus_verbs:фотографировать{}, // фотографировать на мыльницу rus_verbs:подымать{}, // подымать на недосягаемую высоту rus_verbs:съезжаться{}, // съезжаться на симпозиум rus_verbs:отвлекаться{}, // отвлекаться на игру rus_verbs:проливать{}, // проливать на брюки rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца rus_verbs:уползти{}, // уползти на вершину холма rus_verbs:переместить{}, // переместить на вторую палубу rus_verbs:превысить{}, // превысить на несколько метров rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку rus_verbs:спровоцировать{}, // спровоцировать на бросок rus_verbs:сместиться{}, // сместиться на соседнюю клетку rus_verbs:заготовить{}, // заготовить на зиму rus_verbs:плеваться{}, // плеваться на пол rus_verbs:переселить{}, // переселить на север rus_verbs:напирать{}, // напирать на дверь rus_verbs:переезжать{}, // переезжать на другой этаж rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров rus_verbs:трогаться{}, // трогаться на красный свет rus_verbs:надвинуться{}, // надвинуться на глаза rus_verbs:засмотреться{}, // засмотреться на купальники rus_verbs:убыть{}, // убыть на фронт rus_verbs:передвигать{}, // передвигать на второй уровень rus_verbs:отвозить{}, // отвозить на свалку rus_verbs:обрекать{}, // обрекать на гибель rus_verbs:записываться{}, // записываться на танцы rus_verbs:настраивать{}, // настраивать на другой диапазон rus_verbs:переписывать{}, // переписывать на диск rus_verbs:израсходовать{}, // израсходовать на гонки rus_verbs:обменять{}, // обменять на перспективного игрока rus_verbs:трубить{}, // трубить на всю округу rus_verbs:набрасываться{}, // набрасываться на жертву rus_verbs:чихать{}, // чихать на правила rus_verbs:наваливаться{}, // наваливаться на рычаг rus_verbs:сподобиться{}, // сподобиться на повторный анализ rus_verbs:намазать{}, // намазать на хлеб rus_verbs:прореагировать{}, // прореагировать на вызов rus_verbs:зачислить{}, // зачислить на факультет rus_verbs:наведаться{}, // наведаться на склад rus_verbs:откидываться{}, // откидываться на спинку кресла rus_verbs:захромать{}, // захромать на левую ногу rus_verbs:перекочевать{}, // перекочевать на другой берег rus_verbs:накатываться{}, // накатываться на песчаный берег rus_verbs:приостановить{}, // приостановить на некоторое время rus_verbs:запрятать{}, // запрятать на верхнюю полочку rus_verbs:прихрамывать{}, // прихрамывать на правую ногу rus_verbs:упорхнуть{}, // упорхнуть на свободу rus_verbs:расстегивать{}, // расстегивать на пальто rus_verbs:напуститься{}, // напуститься на бродягу rus_verbs:накатывать{}, // накатывать на оригинал rus_verbs:наезжать{}, // наезжать на простофилю rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека rus_verbs:отрядить{}, // отрядить на починку rus_verbs:положиться{}, // положиться на главаря rus_verbs:опрокидывать{}, // опрокидывать на голову rus_verbs:поторапливаться{}, // поторапливаться на рейс rus_verbs:налагать{}, // налагать на заемщика rus_verbs:скопировать{}, // скопировать на диск rus_verbs:опадать{}, // опадать на землю rus_verbs:купиться{}, // купиться на посулы rus_verbs:гневаться{}, // гневаться на слуг rus_verbs:слететься{}, // слететься на раздачу rus_verbs:убавить{}, // убавить на два уровня rus_verbs:спихнуть{}, // спихнуть на соседа rus_verbs:накричать{}, // накричать на ребенка rus_verbs:приберечь{}, // приберечь на ужин rus_verbs:приклеить{}, // приклеить на ветровое стекло rus_verbs:ополчиться{}, // ополчиться на посредников rus_verbs:тратиться{}, // тратиться на сувениры rus_verbs:слетаться{}, // слетаться на свет rus_verbs:доставляться{}, // доставляться на базу rus_verbs:поплевать{}, // поплевать на руки rus_verbs:огрызаться{}, // огрызаться на замечание rus_verbs:попереться{}, // попереться на рынок rus_verbs:растягиваться{}, // растягиваться на полу rus_verbs:повергать{}, // повергать на землю rus_verbs:ловиться{}, // ловиться на мотыля rus_verbs:наседать{}, // наседать на обороняющихся rus_verbs:развалить{}, // развалить на кирпичи rus_verbs:разломить{}, // разломить на несколько частей rus_verbs:примерить{}, // примерить на себя rus_verbs:лепиться{}, // лепиться на стену rus_verbs:скопить{}, // скопить на старость rus_verbs:затратить{}, // затратить на ликвидацию последствий rus_verbs:притащиться{}, // притащиться на гулянку rus_verbs:осерчать{}, // осерчать на прислугу rus_verbs:натравить{}, // натравить на медведя rus_verbs:ссыпать{}, // ссыпать на землю rus_verbs:подвозить{}, // подвозить на пристань rus_verbs:мобилизовать{}, // мобилизовать на сборы rus_verbs:смотаться{}, // смотаться на работу rus_verbs:заглядеться{}, // заглядеться на девчонок rus_verbs:таскаться{}, // таскаться на работу rus_verbs:разгружать{}, // разгружать на транспортер rus_verbs:потреблять{}, // потреблять на кондиционирование инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу деепричастие:сгоняв{}, rus_verbs:посылаться{}, // посылаться на разведку rus_verbs:окрыситься{}, // окрыситься на кого-то rus_verbs:отлить{}, // отлить на сковороду rus_verbs:шикнуть{}, // шикнуть на детишек rus_verbs:уповать{}, // уповать на бескорысную помощь rus_verbs:класться{}, // класться на стол rus_verbs:поковылять{}, // поковылять на выход rus_verbs:навевать{}, // навевать на собравшихся скуку rus_verbs:накладываться{}, // накладываться на грунтовку rus_verbs:наноситься{}, // наноситься на чистую кожу // rus_verbs:запланировать{}, // запланировать на среду rus_verbs:кувыркнуться{}, // кувыркнуться на землю rus_verbs:гавкнуть{}, // гавкнуть на хозяина rus_verbs:перестроиться{}, // перестроиться на новый лад rus_verbs:расходоваться{}, // расходоваться на образование rus_verbs:дуться{}, // дуться на бабушку rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол rus_verbs:издаться{}, // издаться на деньги спонсоров rus_verbs:смещаться{}, // смещаться на несколько миллиметров rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу rus_verbs:пикировать{}, // пикировать на окопы rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей rus_verbs:зудить{}, // зудить на ухо rus_verbs:подразделяться{}, // подразделяться на группы rus_verbs:изливаться{}, // изливаться на землю rus_verbs:помочиться{}, // помочиться на траву rus_verbs:примерять{}, // примерять на себя rus_verbs:разрядиться{}, // разрядиться на землю rus_verbs:мотнуться{}, // мотнуться на крышу rus_verbs:налегать{}, // налегать на весла rus_verbs:зацокать{}, // зацокать на куриц rus_verbs:наниматься{}, // наниматься на корабль rus_verbs:сплевывать{}, // сплевывать на землю rus_verbs:настучать{}, // настучать на саботажника rus_verbs:приземляться{}, // приземляться на брюхо rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу rus_verbs:серчать{}, // серчать на нерасторопную помощницу rus_verbs:сваливать{}, // сваливать на подоконник rus_verbs:засобираться{}, // засобираться на работу rus_verbs:распилить{}, // распилить на одинаковые бруски //rus_verbs:умножать{}, // умножать на константу rus_verbs:копировать{}, // копировать на диск rus_verbs:накрутить{}, // накрутить на руку rus_verbs:навалить{}, // навалить на телегу rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль rus_verbs:шлепаться{}, // шлепаться на бетон rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение rus_verbs:посягнуть{}, // посягнуть на святое rus_verbs:разменять{}, // разменять на мелочь rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции rus_verbs:усаживать{}, // усаживать на скамейку rus_verbs:натаскать{}, // натаскать на поиск наркотиков rus_verbs:зашикать{}, // зашикать на кошку rus_verbs:разломать{}, // разломать на равные части rus_verbs:приглашаться{}, // приглашаться на сцену rus_verbs:присягать{}, // присягать на верность rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку rus_verbs:расщедриться{}, // расщедриться на новый компьютер rus_verbs:насесть{}, // насесть на двоечников rus_verbs:созывать{}, // созывать на собрание rus_verbs:позариться{}, // позариться на чужое добро rus_verbs:перекидываться{}, // перекидываться на соседние здания rus_verbs:наползать{}, // наползать на неповрежденную ткань rus_verbs:изрубить{}, // изрубить на мелкие кусочки rus_verbs:наворачиваться{}, // наворачиваться на глаза rus_verbs:раскричаться{}, // раскричаться на всю округу rus_verbs:переползти{}, // переползти на светлую сторону rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию rus_verbs:мочиться{}, // мочиться на трупы убитых врагов rus_verbs:радировать{}, // радировать на базу rus_verbs:промотать{}, // промотать на начало rus_verbs:заснять{}, // заснять на видео rus_verbs:подбивать{}, // подбивать на матч-реванш rus_verbs:наплевать{}, // наплевать на справедливость rus_verbs:подвывать{}, // подвывать на луну rus_verbs:расплескать{}, // расплескать на пол rus_verbs:польститься{}, // польститься на бесплатный сыр rus_verbs:помчать{}, // помчать на работу rus_verbs:съезжать{}, // съезжать на обочину rus_verbs:нашептать{}, // нашептать кому-то на ухо rus_verbs:наклеить{}, // наклеить на доску объявлений rus_verbs:завозить{}, // завозить на склад rus_verbs:заявляться{}, // заявляться на любимую работу rus_verbs:наглядеться{}, // наглядеться на воробьев rus_verbs:хлопнуться{}, // хлопнуться на живот rus_verbs:забредать{}, // забредать на поляну rus_verbs:посягать{}, // посягать на исконные права собственности rus_verbs:сдвигать{}, // сдвигать на одну позицию rus_verbs:спрыгивать{}, // спрыгивать на землю rus_verbs:сдвигаться{}, // сдвигаться на две позиции rus_verbs:разделать{}, // разделать на орехи rus_verbs:разлагать{}, // разлагать на элементарные элементы rus_verbs:обрушивать{}, // обрушивать на головы врагов rus_verbs:натечь{}, // натечь на пол rus_verbs:политься{}, // вода польется на землю rus_verbs:успеть{}, // Они успеют на поезд. инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш }, деепричастие:мигрируя{}, инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш }, деепричастие:мигрировав{}, rus_verbs:двинуться{}, // Мы скоро двинемся на дачу. rus_verbs:подойти{}, // Он не подойдёт на должность секретаря. rus_verbs:потянуть{}, // Он не потянет на директора. rus_verbs:тянуть{}, // Он не тянет на директора. rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:жаловаться{}, // Он жалуется на нездоровье. rus_verbs:издать{}, // издать на деньги спонсоров rus_verbs:показаться{}, // показаться на глаза rus_verbs:высаживать{}, // высаживать на необитаемый остров rus_verbs:вознестись{}, // вознестись на самую вершину славы rus_verbs:залить{}, // залить на youtube rus_verbs:закачать{}, // закачать на youtube rus_verbs:сыграть{}, // сыграть на деньги rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных глагол:экстраполироваться{ вид:несоверш}, инфинитив:экстраполироваться{ вид:соверш}, глагол:экстраполироваться{ вид:соверш}, деепричастие:экстраполируясь{}, инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы глагол:акцентировать{вид:соверш}, инфинитив:акцентировать{вид:несоверш}, глагол:акцентировать{вид:несоверш}, прилагательное:акцентировавший{вид:несоверш}, //прилагательное:акцентировавший{вид:соверш}, прилагательное:акцентирующий{}, деепричастие:акцентировав{}, деепричастие:акцентируя{}, rus_verbs:бабахаться{}, // он бабахался на пол rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина rus_verbs:бахаться{}, // Наездники бахались на землю rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю rus_verbs:благословить{}, // батюшка благословил отрока на подвиг rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг rus_verbs:блевануть{}, // Он блеванул на землю rus_verbs:блевать{}, // Он блюет на землю rus_verbs:бухнуться{}, // Наездник бухнулся на землю rus_verbs:валить{}, // Ветер валил деревья на землю rus_verbs:спилить{}, // Спиленное дерево валится на землю rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес rus_verbs:вестись{}, // Не ведись на эти уловки! rus_verbs:вешать{}, // Гости вешают одежду на вешалку rus_verbs:вешаться{}, // Одежда вешается на вешалки rus_verbs:вещать{}, // радиостанция вещает на всю страну rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм rus_verbs:взбредать{}, // Что иногда взбредает на ум rus_verbs:взбрести{}, // Что-то взбрело на ум rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи rus_verbs:взглянуть{}, // Кошка взглянула на мышку rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух rus_verbs:взобраться{}, // Туристы взобрались на гору rus_verbs:взойти{}, // Туристы взошли на гору rus_verbs:взъесться{}, // Отец взъелся на непутевого сына rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка rus_verbs:водворить{}, // водворить нарушителя на место rus_verbs:водвориться{}, // водвориться на свое место rus_verbs:водворять{}, // водворять вещь на свое место rus_verbs:водворяться{}, // водворяться на свое место rus_verbs:водружать{}, // водружать флаг на флагшток rus_verbs:водружаться{}, // Флаг водружается на флагшток rus_verbs:водрузить{}, // водрузить флаг на флагшток rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы rus_verbs:воздействовать{}, // Излучение воздействует на кожу rus_verbs:воззреть{}, // воззреть на поле боя rus_verbs:воззриться{}, // воззриться на поле боя rus_verbs:возить{}, // возить туристов на гору rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу rus_verbs:возлагаться{}, // Ответственность возлагается на начальство rus_verbs:возлечь{}, // возлечь на лежанку rus_verbs:возложить{}, // возложить цветы на могилу поэта rus_verbs:вознести{}, // вознести кого-то на вершину славы rus_verbs:возноситься{}, // возносится на вершину успеха rus_verbs:возносить{}, // возносить счастливчика на вершину успеха rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж rus_verbs:подняться{}, // Мы поднялись на восьмой этаж rus_verbs:вонять{}, // Кусок сыра воняет на всю округу rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги rus_verbs:ворчать{}, // Старый пес ворчит на прохожих rus_verbs:воспринимать{}, // воспринимать сообщение на слух rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух rus_verbs:воспринять{}, // воспринять сообщение на слух rus_verbs:восприняться{}, // восприняться на слух rus_verbs:воссесть{}, // Коля воссел на трон rus_verbs:вправить{}, // вправить мозг на место rus_verbs:вправлять{}, // вправлять мозги на место rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:врубать{}, // врубать на полную мощность rus_verbs:врубить{}, // врубить на полную мощность rus_verbs:врубиться{}, // врубиться на полную мощность rus_verbs:врываться{}, // врываться на собрание rus_verbs:вскарабкаться{}, // вскарабкаться на утёс rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс rus_verbs:вскочить{}, // вскочить на ноги rus_verbs:всплывать{}, // всплывать на поверхность воды rus_verbs:всплыть{}, // всплыть на поверхность воды rus_verbs:вспрыгивать{}, // вспрыгивать на платформу rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу rus_verbs:встать{}, // встать на защиту чести и достоинства rus_verbs:вторгаться{}, // вторгаться на чужую территорию rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию rus_verbs:въезжать{}, // въезжать на пандус rus_verbs:наябедничать{}, // наябедничать на соседа по парте rus_verbs:выблевать{}, // выблевать завтрак на пол rus_verbs:выблеваться{}, // выблеваться на пол rus_verbs:выблевывать{}, // выблевывать завтрак на пол rus_verbs:выблевываться{}, // выблевываться на пол rus_verbs:вывезти{}, // вывезти мусор на свалку rus_verbs:вывесить{}, // вывесить белье на просушку rus_verbs:вывести{}, // вывести собаку на прогулку rus_verbs:вывешивать{}, // вывешивать белье на веревку rus_verbs:вывозить{}, // вывозить детей на природу rus_verbs:вызывать{}, // Начальник вызывает на ковер rus_verbs:выйти{}, // выйти на свободу rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение rus_verbs:выливать{}, // выливать на землю rus_verbs:выливаться{}, // выливаться на землю rus_verbs:вылить{}, // вылить жидкость на землю rus_verbs:вылиться{}, // Топливо вылилось на землю rus_verbs:выложить{}, // выложить на берег rus_verbs:выменивать{}, // выменивать золото на хлеб rus_verbs:вымениваться{}, // Золото выменивается на хлеб rus_verbs:выменять{}, // выменять золото на хлеб rus_verbs:выпадать{}, // снег выпадает на землю rus_verbs:выплевывать{}, // выплевывать на землю rus_verbs:выплевываться{}, // выплевываться на землю rus_verbs:выплескать{}, // выплескать на землю rus_verbs:выплескаться{}, // выплескаться на землю rus_verbs:выплескивать{}, // выплескивать на землю rus_verbs:выплескиваться{}, // выплескиваться на землю rus_verbs:выплывать{}, // выплывать на поверхность rus_verbs:выплыть{}, // выплыть на поверхность rus_verbs:выплюнуть{}, // выплюнуть на пол rus_verbs:выползать{}, // выползать на свежий воздух rus_verbs:выпроситься{}, // выпроситься на улицу rus_verbs:выпрыгивать{}, // выпрыгивать на свободу rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон rus_verbs:выпускать{}, // выпускать на свободу rus_verbs:выпустить{}, // выпустить на свободу rus_verbs:выпучивать{}, // выпучивать на кого-то глаза rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то rus_verbs:выпучить{}, // выпучить глаза на кого-то rus_verbs:выпучиться{}, // выпучиться на кого-то rus_verbs:выронить{}, // выронить на землю rus_verbs:высадить{}, // высадить на берег rus_verbs:высадиться{}, // высадиться на берег rus_verbs:высаживаться{}, // высаживаться на остров rus_verbs:выскальзывать{}, // выскальзывать на землю rus_verbs:выскочить{}, // выскочить на сцену rus_verbs:высморкаться{}, // высморкаться на землю rus_verbs:высморкнуться{}, // высморкнуться на землю rus_verbs:выставить{}, // выставить на всеобщее обозрение rus_verbs:выставиться{}, // выставиться на всеобщее обозрение rus_verbs:выставлять{}, // выставлять на всеобщее обозрение rus_verbs:выставляться{}, // выставляться на всеобщее обозрение инфинитив:высыпать{вид:соверш}, // высыпать на землю инфинитив:высыпать{вид:несоверш}, глагол:высыпать{вид:соверш}, глагол:высыпать{вид:несоверш}, деепричастие:высыпав{}, деепричастие:высыпая{}, прилагательное:высыпавший{вид:соверш}, //++прилагательное:высыпавший{вид:несоверш}, прилагательное:высыпающий{вид:несоверш}, rus_verbs:высыпаться{}, // высыпаться на землю rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя rus_verbs:вытаращиваться{}, // вытаращиваться на медведя rus_verbs:вытаращить{}, // вытаращить глаза на медведя rus_verbs:вытаращиться{}, // вытаращиться на медведя rus_verbs:вытекать{}, // вытекать на землю rus_verbs:вытечь{}, // вытечь на землю rus_verbs:выучиваться{}, // выучиваться на кого-то rus_verbs:выучиться{}, // выучиться на кого-то rus_verbs:посмотреть{}, // посмотреть на экран rus_verbs:нашить{}, // нашить что-то на одежду rus_verbs:придти{}, // придти на помощь кому-то инфинитив:прийти{}, // прийти на помощь кому-то глагол:прийти{}, деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты. rus_verbs:поднять{}, // поднять на вершину rus_verbs:согласиться{}, // согласиться на ничью rus_verbs:послать{}, // послать на фронт rus_verbs:слать{}, // слать на фронт rus_verbs:надеяться{}, // надеяться на лучшее rus_verbs:крикнуть{}, // крикнуть на шалунов rus_verbs:пройти{}, // пройти на пляж rus_verbs:прислать{}, // прислать на экспертизу rus_verbs:жить{}, // жить на подачки rus_verbs:становиться{}, // становиться на ноги rus_verbs:наслать{}, // наслать на кого-то rus_verbs:принять{}, // принять на заметку rus_verbs:собираться{}, // собираться на экзамен rus_verbs:оставить{}, // оставить на всякий случай rus_verbs:звать{}, // звать на помощь rus_verbs:направиться{}, // направиться на прогулку rus_verbs:отвечать{}, // отвечать на звонки rus_verbs:отправиться{}, // отправиться на прогулку rus_verbs:поставить{}, // поставить на пол rus_verbs:обернуться{}, // обернуться на зов rus_verbs:отозваться{}, // отозваться на просьбу rus_verbs:закричать{}, // закричать на собаку rus_verbs:опустить{}, // опустить на землю rus_verbs:принести{}, // принести на пляж свой жезлонг rus_verbs:указать{}, // указать на дверь rus_verbs:ходить{}, // ходить на занятия rus_verbs:уставиться{}, // уставиться на листок rus_verbs:приходить{}, // приходить на экзамен rus_verbs:махнуть{}, // махнуть на пляж rus_verbs:явиться{}, // явиться на допрос rus_verbs:оглянуться{}, // оглянуться на дорогу rus_verbs:уехать{}, // уехать на заработки rus_verbs:повести{}, // повести на штурм rus_verbs:опуститься{}, // опуститься на колени //rus_verbs:передать{}, // передать на проверку rus_verbs:побежать{}, // побежать на занятия rus_verbs:прибыть{}, // прибыть на место службы rus_verbs:кричать{}, // кричать на медведя rus_verbs:стечь{}, // стечь на землю rus_verbs:обратить{}, // обратить на себя внимание rus_verbs:подать{}, // подать на пропитание rus_verbs:привести{}, // привести на съемки rus_verbs:испытывать{}, // испытывать на животных rus_verbs:перевести{}, // перевести на жену rus_verbs:купить{}, // купить на заемные деньги rus_verbs:собраться{}, // собраться на встречу rus_verbs:заглянуть{}, // заглянуть на огонёк rus_verbs:нажать{}, // нажать на рычаг rus_verbs:поспешить{}, // поспешить на праздник rus_verbs:перейти{}, // перейти на русский язык rus_verbs:поверить{}, // поверить на честное слово rus_verbs:глянуть{}, // глянуть на обложку rus_verbs:зайти{}, // зайти на огонёк rus_verbs:проходить{}, // проходить на сцену rus_verbs:глядеть{}, // глядеть на актрису //rus_verbs:решиться{}, // решиться на прыжок rus_verbs:пригласить{}, // пригласить на танец rus_verbs:позвать{}, // позвать на экзамен rus_verbs:усесться{}, // усесться на стул rus_verbs:поступить{}, // поступить на математический факультет rus_verbs:лечь{}, // лечь на живот rus_verbs:потянуться{}, // потянуться на юг rus_verbs:присесть{}, // присесть на корточки rus_verbs:наступить{}, // наступить на змею rus_verbs:заорать{}, // заорать на попрошаек rus_verbs:надеть{}, // надеть на голову rus_verbs:поглядеть{}, // поглядеть на девчонок rus_verbs:принимать{}, // принимать на гарантийное обслуживание rus_verbs:привезти{}, // привезти на испытания rus_verbs:рухнуть{}, // рухнуть на асфальт rus_verbs:пускать{}, // пускать на корм rus_verbs:отвести{}, // отвести на приём rus_verbs:отправить{}, // отправить на утилизацию rus_verbs:двигаться{}, // двигаться на восток rus_verbs:нести{}, // нести на пляж rus_verbs:падать{}, // падать на руки rus_verbs:откинуться{}, // откинуться на спинку кресла rus_verbs:рявкнуть{}, // рявкнуть на детей rus_verbs:получать{}, // получать на проживание rus_verbs:полезть{}, // полезть на рожон rus_verbs:направить{}, // направить на дообследование rus_verbs:приводить{}, // приводить на проверку rus_verbs:потребоваться{}, // потребоваться на замену rus_verbs:кинуться{}, // кинуться на нападавшего rus_verbs:учиться{}, // учиться на токаря rus_verbs:приподнять{}, // приподнять на один метр rus_verbs:налить{}, // налить на стол rus_verbs:играть{}, // играть на деньги rus_verbs:рассчитывать{}, // рассчитывать на подмогу rus_verbs:шепнуть{}, // шепнуть на ухо rus_verbs:швырнуть{}, // швырнуть на землю rus_verbs:прыгнуть{}, // прыгнуть на оленя rus_verbs:предлагать{}, // предлагать на выбор rus_verbs:садиться{}, // садиться на стул rus_verbs:лить{}, // лить на землю rus_verbs:испытать{}, // испытать на животных rus_verbs:фыркнуть{}, // фыркнуть на детеныша rus_verbs:годиться{}, // мясо годится на фарш rus_verbs:проверить{}, // проверить высказывание на истинность rus_verbs:откликнуться{}, // откликнуться на призывы rus_verbs:полагаться{}, // полагаться на интуицию rus_verbs:покоситься{}, // покоситься на соседа rus_verbs:повесить{}, // повесить на гвоздь инфинитив:походить{вид:соверш}, // походить на занятия глагол:походить{вид:соверш}, деепричастие:походив{}, прилагательное:походивший{}, rus_verbs:помчаться{}, // помчаться на экзамен rus_verbs:ставить{}, // ставить на контроль rus_verbs:свалиться{}, // свалиться на землю rus_verbs:валиться{}, // валиться на землю rus_verbs:подарить{}, // подарить на день рожденья rus_verbs:сбежать{}, // сбежать на необитаемый остров rus_verbs:стрелять{}, // стрелять на поражение rus_verbs:обращать{}, // обращать на себя внимание rus_verbs:наступать{}, // наступать на те же грабли rus_verbs:сбросить{}, // сбросить на землю rus_verbs:обидеться{}, // обидеться на друга rus_verbs:устроиться{}, // устроиться на стажировку rus_verbs:погрузиться{}, // погрузиться на большую глубину rus_verbs:течь{}, // течь на землю rus_verbs:отбросить{}, // отбросить на землю rus_verbs:метать{}, // метать на дно rus_verbs:пустить{}, // пустить на переплавку rus_verbs:прожить{}, // прожить на пособие rus_verbs:полететь{}, // полететь на континент rus_verbs:пропустить{}, // пропустить на сцену rus_verbs:указывать{}, // указывать на ошибку rus_verbs:наткнуться{}, // наткнуться на клад rus_verbs:рвануть{}, // рвануть на юг rus_verbs:ступать{}, // ступать на землю rus_verbs:спрыгнуть{}, // спрыгнуть на берег rus_verbs:заходить{}, // заходить на огонёк rus_verbs:нырнуть{}, // нырнуть на глубину rus_verbs:рвануться{}, // рвануться на свободу rus_verbs:натянуть{}, // натянуть на голову rus_verbs:забраться{}, // забраться на стол rus_verbs:помахать{}, // помахать на прощание rus_verbs:содержать{}, // содержать на спонсорскую помощь rus_verbs:приезжать{}, // приезжать на праздники rus_verbs:проникнуть{}, // проникнуть на территорию rus_verbs:подъехать{}, // подъехать на митинг rus_verbs:устремиться{}, // устремиться на волю rus_verbs:посадить{}, // посадить на стул rus_verbs:ринуться{}, // ринуться на голкипера rus_verbs:подвигнуть{}, // подвигнуть на подвиг rus_verbs:отдавать{}, // отдавать на перевоспитание rus_verbs:отложить{}, // отложить на черный день rus_verbs:убежать{}, // убежать на танцы rus_verbs:поднимать{}, // поднимать на верхний этаж rus_verbs:переходить{}, // переходить на цифровой сигнал rus_verbs:отослать{}, // отослать на переаттестацию rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола rus_verbs:назначить{}, // назначить на должность rus_verbs:осесть{}, // осесть на дно rus_verbs:торопиться{}, // торопиться на экзамен rus_verbs:менять{}, // менять на еду rus_verbs:доставить{}, // доставить на шестой этаж rus_verbs:заслать{}, // заслать на проверку rus_verbs:дуть{}, // дуть на воду rus_verbs:сослать{}, // сослать на каторгу rus_verbs:останавливаться{}, // останавливаться на отдых rus_verbs:сдаваться{}, // сдаваться на милость победителя rus_verbs:сослаться{}, // сослаться на презумпцию невиновности rus_verbs:рассердиться{}, // рассердиться на дочь rus_verbs:кинуть{}, // кинуть на землю rus_verbs:расположиться{}, // расположиться на ночлег rus_verbs:осмелиться{}, // осмелиться на подлог rus_verbs:шептать{}, // шептать на ушко rus_verbs:уронить{}, // уронить на землю rus_verbs:откинуть{}, // откинуть на спинку кресла rus_verbs:перенести{}, // перенести на рабочий стол rus_verbs:сдаться{}, // сдаться на милость победителя rus_verbs:светить{}, // светить на дорогу rus_verbs:мчаться{}, // мчаться на бал rus_verbs:нестись{}, // нестись на свидание rus_verbs:поглядывать{}, // поглядывать на экран rus_verbs:орать{}, // орать на детей rus_verbs:уложить{}, // уложить на лопатки rus_verbs:решаться{}, // решаться на поступок rus_verbs:попадать{}, // попадать на карандаш rus_verbs:сплюнуть{}, // сплюнуть на землю rus_verbs:снимать{}, // снимать на телефон rus_verbs:опоздать{}, // опоздать на работу rus_verbs:посылать{}, // посылать на проверку rus_verbs:погнать{}, // погнать на пастбище rus_verbs:поступать{}, // поступать на кибернетический факультет rus_verbs:спускаться{}, // спускаться на уровень моря rus_verbs:усадить{}, // усадить на диван rus_verbs:проиграть{}, // проиграть на спор rus_verbs:прилететь{}, // прилететь на фестиваль rus_verbs:повалиться{}, // повалиться на спину rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина rus_verbs:задавать{}, // задавать на выходные rus_verbs:запасть{}, // запасть на девочку rus_verbs:лезть{}, // лезть на забор rus_verbs:потащить{}, // потащить на выборы rus_verbs:направляться{}, // направляться на экзамен rus_verbs:определять{}, // определять на вкус rus_verbs:поползти{}, // поползти на стену rus_verbs:поплыть{}, // поплыть на берег rus_verbs:залезть{}, // залезть на яблоню rus_verbs:сдать{}, // сдать на мясокомбинат rus_verbs:приземлиться{}, // приземлиться на дорогу rus_verbs:лаять{}, // лаять на прохожих rus_verbs:перевернуть{}, // перевернуть на бок rus_verbs:ловить{}, // ловить на живца rus_verbs:отнести{}, // отнести животное на хирургический стол rus_verbs:плюнуть{}, // плюнуть на условности rus_verbs:передавать{}, // передавать на проверку rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали инфинитив:рассыпаться{вид:соверш}, глагол:рассыпаться{вид:несоверш}, глагол:рассыпаться{вид:соверш}, деепричастие:рассыпавшись{}, деепричастие:рассыпаясь{}, прилагательное:рассыпавшийся{вид:несоверш}, прилагательное:рассыпавшийся{вид:соверш}, прилагательное:рассыпающийся{}, rus_verbs:зарычать{}, // Медведица зарычала на медвежонка rus_verbs:призвать{}, // призвать на сборы rus_verbs:увезти{}, // увезти на дачу rus_verbs:содержаться{}, // содержаться на пожертвования rus_verbs:навести{}, // навести на скопление телескоп rus_verbs:отправляться{}, // отправляться на утилизацию rus_verbs:улечься{}, // улечься на животик rus_verbs:налететь{}, // налететь на препятствие rus_verbs:перевернуться{}, // перевернуться на спину rus_verbs:улететь{}, // улететь на родину rus_verbs:ложиться{}, // ложиться на бок rus_verbs:класть{}, // класть на место rus_verbs:отреагировать{}, // отреагировать на выступление rus_verbs:доставлять{}, // доставлять на дом rus_verbs:отнять{}, // отнять на благо правящей верхушки rus_verbs:ступить{}, // ступить на землю rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы rus_verbs:унести{}, // унести на работу rus_verbs:сходить{}, // сходить на концерт rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги rus_verbs:соскочить{}, // соскочить на землю rus_verbs:пожаловаться{}, // пожаловаться на соседей rus_verbs:тащить{}, // тащить на замену rus_verbs:замахать{}, // замахать руками на паренька rus_verbs:заглядывать{}, // заглядывать на обед rus_verbs:соглашаться{}, // соглашаться на равный обмен rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик rus_verbs:увести{}, // увести на осмотр rus_verbs:успевать{}, // успевать на контрольную работу rus_verbs:опрокинуть{}, // опрокинуть на себя rus_verbs:подавать{}, // подавать на апелляцию rus_verbs:прибежать{}, // прибежать на вокзал rus_verbs:отшвырнуть{}, // отшвырнуть на замлю rus_verbs:привлекать{}, // привлекать на свою сторону rus_verbs:опереться{}, // опереться на палку rus_verbs:перебраться{}, // перебраться на маленький островок rus_verbs:уговорить{}, // уговорить на новые траты rus_verbs:гулять{}, // гулять на спонсорские деньги rus_verbs:переводить{}, // переводить на другой путь rus_verbs:заколебаться{}, // заколебаться на один миг rus_verbs:зашептать{}, // зашептать на ушко rus_verbs:привстать{}, // привстать на цыпочки rus_verbs:хлынуть{}, // хлынуть на берег rus_verbs:наброситься{}, // наброситься на еду rus_verbs:напасть{}, // повстанцы, напавшие на конвой rus_verbs:убрать{}, // книга, убранная на полку rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию rus_verbs:засматриваться{}, // засматриваться на девчонок rus_verbs:застегнуться{}, // застегнуться на все пуговицы rus_verbs:провериться{}, // провериться на заболевания rus_verbs:проверяться{}, // проверяться на заболевания rus_verbs:тестировать{}, // тестировать на профпригодность rus_verbs:протестировать{}, // протестировать на профпригодность rus_verbs:уходить{}, // отец, уходящий на работу rus_verbs:налипнуть{}, // снег, налипший на провода rus_verbs:налипать{}, // снег, налипающий на провода rus_verbs:улетать{}, // Многие птицы улетают осенью на юг. rus_verbs:поехать{}, // она поехала на встречу с заказчиком rus_verbs:переключать{}, // переключать на резервную линию rus_verbs:переключаться{}, // переключаться на резервную линию rus_verbs:подписаться{}, // подписаться на обновление rus_verbs:нанести{}, // нанести на кожу rus_verbs:нарываться{}, // нарываться на неприятности rus_verbs:выводить{}, // выводить на орбиту rus_verbs:вернуться{}, // вернуться на родину rus_verbs:возвращаться{}, // возвращаться на родину прилагательное:падкий{}, // Он падок на деньги. прилагательное:обиженный{}, // Он обижен на отца. rus_verbs:косить{}, // Он косит на оба глаза. rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок. прилагательное:готовый{}, // Он готов на всякие жертвы. rus_verbs:говорить{}, // Он говорит на скользкую тему. прилагательное:глухой{}, // Он глух на одно ухо. rus_verbs:взять{}, // Он взял ребёнка себе на колени. rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия. rus_verbs:вести{}, // Лестница ведёт на третий этаж. rus_verbs:уполномочивать{}, // уполномочивать на что-либо глагол:спешить{ вид:несоверш }, // Я спешу на поезд. rus_verbs:брать{}, // Я беру всю ответственность на себя. rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление. rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики. rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку. rus_verbs:разбираться{}, // Эта машина разбирается на части. rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние. rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп. rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье. rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно. rus_verbs:делиться{}, // Тридцать делится на пять без остатка. rus_verbs:удаляться{}, // Суд удаляется на совещание. rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север. rus_verbs:сохранить{}, // Сохраните это на память обо мне. rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию. rus_verbs:лететь{}, // Самолёт летит на север. rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров. // rus_verbs:прийтись{}, // Пятое число пришлось на субботу. rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи. rus_verbs:смотреть{}, // Она смотрит на нас из окна. rus_verbs:отдать{}, // Она отдала мне деньги на сохранение. rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину. rus_verbs:любоваться{}, // гости любовались на картину rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь. прилагательное:действительный{}, // Прививка оспы действительна только на три года. rus_verbs:спуститься{}, // На город спустился смог прилагательное:нечистый{}, // Он нечист на руку. прилагательное:неспособный{}, // Он неспособен на такую низость. прилагательное:злой{}, // кот очень зол на хозяина rus_verbs:пойти{}, // Девочка не пошла на урок физультуры rus_verbs:прибывать{}, // мой поезд прибывает на первый путь rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу rus_verbs:идти{}, // Дело идёт на лад. rus_verbs:лазить{}, // Он лазил на чердак. rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры. // rus_verbs:действовать{}, // действующий на нервы rus_verbs:выходить{}, // Балкон выходит на площадь. rus_verbs:работать{}, // Время работает на нас. глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина. rus_verbs:бросить{}, // Они бросили все силы на строительство. // глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков. rus_verbs:броситься{}, // Она радостно бросилась мне на шею. rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью. rus_verbs:ответить{}, // Она не ответила на мой поклон. rus_verbs:нашивать{}, // Она нашивала заплату на локоть. rus_verbs:молиться{}, // Она молится на свою мать. rus_verbs:запереть{}, // Она заперла дверь на замок. rus_verbs:заявить{}, // Она заявила свои права на наследство. rus_verbs:уйти{}, // Все деньги ушли на путешествие. rus_verbs:вступить{}, // Водолаз вступил на берег. rus_verbs:сойти{}, // Ночь сошла на землю. rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано. rus_verbs:рыдать{}, // Не рыдай так безумно над ним. rus_verbs:подписать{}, // Не забудьте подписать меня на газету. rus_verbs:держать{}, // Наш пароход держал курс прямо на север. rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира. rus_verbs:ехать{}, // Мы сейчас едем на завод. rus_verbs:выбросить{}, // Волнами лодку выбросило на берег. ГЛ_ИНФ(сесть), // сесть на снег ГЛ_ИНФ(записаться), ГЛ_ИНФ(положить) // положи книгу на стол } #endregion VerbList // Чтобы разрешить связывание в паттернах типа: залить на youtube fact гл_предл { if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} } then return true } fact гл_предл { if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } } then return true } // смещаться на несколько миллиметров fact гл_предл { if context { Гл_НА_Вин предлог:на{} наречие:*{} } then return true } // партия взяла на себя нереалистичные обязательства fact гл_предл { if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} } then return true } #endregion ВИНИТЕЛЬНЫЙ // Все остальные варианты с предлогом 'НА' по умолчанию запрещаем. fact гл_предл { if context { * предлог:на{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:мест } } then return false,-3 } fact гл_предл { if context { * предлог:на{} *:*{ падеж:вин } } then return false,-4 } // Этот вариант нужен для обработки конструкций с числительными: // Президентские выборы разделили Венесуэлу на два непримиримых лагеря fact гл_предл { if context { * предлог:на{} *:*{ падеж:род } } then return false,-4 } // Продавать на eBay fact гл_предл { if context { * предлог:на{} * } then return false,-6 } #endregion Предлог_НА #region Предлог_С // ------------- ПРЕДЛОГ 'С' ----------------- // У этого предлога предпочтительная семантика привязывает его обычно к существительному. // Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим. #region ТВОРИТЕЛЬНЫЙ wordentry_set Гл_С_Твор={ rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться rus_verbs:забраться{}, rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ) rus_verbs:БИТЬСЯ{}, // rus_verbs:ПОДРАТЬСЯ{}, // прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ) rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ) rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ) rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ) rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ) прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом. rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ) rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ) rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ) rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ) rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ) rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ) rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ) rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ) rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ) rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ) rus_verbs:отправить{}, // вы можете отправить со мной человека rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор) rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С) rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С) прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С) rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С) rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С) rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С) rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С) rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С) rus_verbs:СВЫКАТЬСЯ{}, rus_verbs:стаскиваться{}, rus_verbs:спиливаться{}, rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С) rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор) rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С) rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С) rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С) rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С) rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С) rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С) rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С) rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С) rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С) rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор) rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С) rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С) rus_verbs:согласиться{}, // с этим согласились все (согласиться с) rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор) rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С) rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С) rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор) rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор) rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С) rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С) rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор) rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор) rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор) rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор) rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор) rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор) rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор) rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор) rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор) rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ) rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ) rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много) rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С) rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С) rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С) rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С) rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С) rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор) rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С) rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С) rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С) rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С) rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С) инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара. инфинитив:кристаллизоваться{ вид:несоверш }, глагол:кристаллизоваться{ вид:соверш }, глагол:кристаллизоваться{ вид:несоверш }, rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С) rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С) rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С) rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С) rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С) rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор) rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С) rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С) rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с) rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с) rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с) rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с) rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело. rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором rus_verbs:стирать{}, // стирать с мылом рубашку в тазу rus_verbs:прыгать{}, // парашютист прыгает с парашютом rus_verbs:выступить{}, // Он выступил с приветствием съезду. rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят. rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой. rus_verbs:вставать{}, // он встаёт с зарёй rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером. rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью. rus_verbs:договориться{}, // мы договоримся с вами rus_verbs:побыть{}, // он хотел побыть с тобой rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью rus_verbs:вязаться{}, // вязаться с фактами rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:относиться{}, // относиться с пониманием rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов. rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней rus_verbs:гулять{}, // бабушка гуляет с внуком rus_verbs:разбираться{}, // разбираться с задачей rus_verbs:сверить{}, // Данные были сверены с эталонными значениями rus_verbs:делать{}, // Что делать со старым телефоном rus_verbs:осматривать{}, // осматривать с удивлением rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре rus_verbs:попрощаться{}, // попрощаться с талантливым актером rus_verbs:задремать{}, // задремать с кружкой чая в руке rus_verbs:связать{}, // связать катастрофу с действиями конкурентов rus_verbs:носиться{}, // носиться с безумной идеей rus_verbs:кончать{}, // кончать с собой rus_verbs:обмениваться{}, // обмениваться с собеседниками rus_verbs:переговариваться{}, // переговариваться с маяком rus_verbs:общаться{}, // общаться с полицией rus_verbs:завершить{}, // завершить с ошибкой rus_verbs:обняться{}, // обняться с подругой rus_verbs:сливаться{}, // сливаться с фоном rus_verbs:смешаться{}, // смешаться с толпой rus_verbs:договариваться{}, // договариваться с потерпевшим rus_verbs:обедать{}, // обедать с гостями rus_verbs:сообщаться{}, // сообщаться с подземной рекой rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц rus_verbs:читаться{}, // читаться с трудом rus_verbs:смириться{}, // смириться с утратой rus_verbs:разделить{}, // разделить с другими ответственность rus_verbs:роднить{}, // роднить с медведем rus_verbs:медлить{}, // медлить с ответом rus_verbs:скрестить{}, // скрестить с ужом rus_verbs:покоиться{}, // покоиться с миром rus_verbs:делиться{}, // делиться с друзьями rus_verbs:познакомить{}, // познакомить с Олей rus_verbs:порвать{}, // порвать с Олей rus_verbs:завязать{}, // завязать с Олей знакомство rus_verbs:суетиться{}, // суетиться с изданием романа rus_verbs:соединиться{}, // соединиться с сервером rus_verbs:справляться{}, // справляться с нуждой rus_verbs:замешкаться{}, // замешкаться с ответом rus_verbs:поссориться{}, // поссориться с подругой rus_verbs:ссориться{}, // ссориться с друзьями rus_verbs:торопить{}, // торопить с решением rus_verbs:поздравить{}, // поздравить с победой rus_verbs:проститься{}, // проститься с человеком rus_verbs:поработать{}, // поработать с деревом rus_verbs:приключиться{}, // приключиться с Колей rus_verbs:сговориться{}, // сговориться с Ваней rus_verbs:отъехать{}, // отъехать с ревом rus_verbs:объединять{}, // объединять с другой кампанией rus_verbs:употребить{}, // употребить с молоком rus_verbs:перепутать{}, // перепутать с другой книгой rus_verbs:запоздать{}, // запоздать с ответом rus_verbs:подружиться{}, // подружиться с другими детьми rus_verbs:дружить{}, // дружить с Сережей rus_verbs:поравняться{}, // поравняться с финишной чертой rus_verbs:ужинать{}, // ужинать с гостями rus_verbs:расставаться{}, // расставаться с приятелями rus_verbs:завтракать{}, // завтракать с семьей rus_verbs:объединиться{}, // объединиться с соседями rus_verbs:сменяться{}, // сменяться с напарником rus_verbs:соединить{}, // соединить с сетью rus_verbs:разговориться{}, // разговориться с охранником rus_verbs:преподнести{}, // преподнести с помпой rus_verbs:напечатать{}, // напечатать с картинками rus_verbs:соединять{}, // соединять с сетью rus_verbs:расправиться{}, // расправиться с беззащитным человеком rus_verbs:распрощаться{}, // распрощаться с деньгами rus_verbs:сравнить{}, // сравнить с конкурентами rus_verbs:ознакомиться{}, // ознакомиться с выступлением инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{}, rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия rus_verbs:прощаться{}, // прощаться с боевым товарищем rus_verbs:сравнивать{}, // сравнивать с конкурентами rus_verbs:складывать{}, // складывать с весом упаковки rus_verbs:повестись{}, // повестись с ворами rus_verbs:столкнуть{}, // столкнуть с отбойником rus_verbs:переглядываться{}, // переглядываться с соседом rus_verbs:поторопить{}, // поторопить с откликом rus_verbs:развлекаться{}, // развлекаться с подружками rus_verbs:заговаривать{}, // заговаривать с незнакомцами rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим деепричастие:согласуясь{}, прилагательное:согласующийся{}, rus_verbs:совпасть{}, // совпасть с оригиналом rus_verbs:соединяться{}, // соединяться с куратором rus_verbs:повстречаться{}, // повстречаться с героями rus_verbs:поужинать{}, // поужинать с родителями rus_verbs:развестись{}, // развестись с первым мужем rus_verbs:переговорить{}, // переговорить с коллегами rus_verbs:сцепиться{}, // сцепиться с бродячей собакой rus_verbs:сожрать{}, // сожрать с потрохами rus_verbs:побеседовать{}, // побеседовать со шпаной rus_verbs:поиграть{}, // поиграть с котятами rus_verbs:сцепить{}, // сцепить с тягачом rus_verbs:помириться{}, // помириться с подружкой rus_verbs:связываться{}, // связываться с бандитами rus_verbs:совещаться{}, // совещаться с мастерами rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой rus_verbs:переплестись{}, // переплестись с кустами rus_verbs:мутить{}, // мутить с одногрупницами rus_verbs:приглядываться{}, // приглядываться с интересом rus_verbs:сблизиться{}, // сблизиться с врагами rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой rus_verbs:растереть{}, // растереть с солью rus_verbs:смешиваться{}, // смешиваться с известью rus_verbs:соприкоснуться{}, // соприкоснуться с тайной rus_verbs:ладить{}, // ладить с родственниками rus_verbs:сотрудничать{}, // сотрудничать с органами дознания rus_verbs:съехаться{}, // съехаться с родственниками rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов rus_verbs:советоваться{}, // советоваться с отчимом rus_verbs:сравниться{}, // сравниться с лучшими rus_verbs:знакомиться{}, // знакомиться с абитуриентами rus_verbs:нырять{}, // нырять с аквалангом rus_verbs:забавляться{}, // забавляться с куклой rus_verbs:перекликаться{}, // перекликаться с другой статьей rus_verbs:тренироваться{}, // тренироваться с партнершей rus_verbs:поспорить{}, // поспорить с казночеем инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш }, rus_verbs:примириться{}, // примириться с утратой rus_verbs:раскланяться{}, // раскланяться с фрейлинами rus_verbs:слечь{}, // слечь с ангиной rus_verbs:соприкасаться{}, // соприкасаться со стеной rus_verbs:смешать{}, // смешать с грязью rus_verbs:пересекаться{}, // пересекаться с трассой rus_verbs:путать{}, // путать с государственной шерстью rus_verbs:поболтать{}, // поболтать с ученицами rus_verbs:здороваться{}, // здороваться с профессором rus_verbs:просчитаться{}, // просчитаться с покупкой rus_verbs:сторожить{}, // сторожить с собакой rus_verbs:обыскивать{}, // обыскивать с собаками rus_verbs:переплетаться{}, // переплетаться с другой веткой rus_verbs:обниматься{}, // обниматься с Ксюшей rus_verbs:объединяться{}, // объединяться с конкурентами rus_verbs:погорячиться{}, // погорячиться с покупкой rus_verbs:мыться{}, // мыться с мылом rus_verbs:свериться{}, // свериться с эталоном rus_verbs:разделаться{}, // разделаться с кем-то rus_verbs:чередоваться{}, // чередоваться с партнером rus_verbs:налететь{}, // налететь с соратниками rus_verbs:поспать{}, // поспать с включенным светом rus_verbs:управиться{}, // управиться с собакой rus_verbs:согрешить{}, // согрешить с замужней rus_verbs:определиться{}, // определиться с победителем rus_verbs:перемешаться{}, // перемешаться с гранулами rus_verbs:затрудняться{}, // затрудняться с ответом rus_verbs:обождать{}, // обождать со стартом rus_verbs:фыркать{}, // фыркать с презрением rus_verbs:засидеться{}, // засидеться с приятелем rus_verbs:крепнуть{}, // крепнуть с годами rus_verbs:пировать{}, // пировать с дружиной rus_verbs:щебетать{}, // щебетать с сестричками rus_verbs:маяться{}, // маяться с кашлем rus_verbs:сближать{}, // сближать с центральным светилом rus_verbs:меркнуть{}, // меркнуть с возрастом rus_verbs:заспорить{}, // заспорить с оппонентами rus_verbs:граничить{}, // граничить с Ливаном rus_verbs:перестараться{}, // перестараться со стимуляторами rus_verbs:объединить{}, // объединить с филиалом rus_verbs:свыкнуться{}, // свыкнуться с утратой rus_verbs:посоветоваться{}, // посоветоваться с адвокатами rus_verbs:напутать{}, // напутать с ведомостями rus_verbs:нагрянуть{}, // нагрянуть с обыском rus_verbs:посовещаться{}, // посовещаться с судьей rus_verbs:провернуть{}, // провернуть с друганом rus_verbs:разделяться{}, // разделяться с сотрапезниками rus_verbs:пересечься{}, // пересечься с второй колонной rus_verbs:опережать{}, // опережать с большим запасом rus_verbs:перепутаться{}, // перепутаться с другой линией rus_verbs:соотноситься{}, // соотноситься с затратами rus_verbs:смешивать{}, // смешивать с золой rus_verbs:свидеться{}, // свидеться с тобой rus_verbs:переспать{}, // переспать с графиней rus_verbs:поладить{}, // поладить с соседями rus_verbs:протащить{}, // протащить с собой rus_verbs:разминуться{}, // разминуться с встречным потоком rus_verbs:перемежаться{}, // перемежаться с успехами rus_verbs:рассчитаться{}, // рассчитаться с кредиторами rus_verbs:срастись{}, // срастись с телом rus_verbs:знакомить{}, // знакомить с родителями rus_verbs:поругаться{}, // поругаться с родителями rus_verbs:совладать{}, // совладать с чувствами rus_verbs:обручить{}, // обручить с богатой невестой rus_verbs:сближаться{}, // сближаться с вражеским эсминцем rus_verbs:замутить{}, // замутить с Ксюшей rus_verbs:повозиться{}, // повозиться с настройкой rus_verbs:торговаться{}, // торговаться с продавцами rus_verbs:уединиться{}, // уединиться с девчонкой rus_verbs:переборщить{}, // переборщить с добавкой rus_verbs:ознакомить{}, // ознакомить с пожеланиями rus_verbs:прочесывать{}, // прочесывать с собаками rus_verbs:переписываться{}, // переписываться с корреспондентами rus_verbs:повздорить{}, // повздорить с сержантом rus_verbs:разлучить{}, // разлучить с семьей rus_verbs:соседствовать{}, // соседствовать с цыганами rus_verbs:застукать{}, // застукать с проститутками rus_verbs:напуститься{}, // напуститься с кулаками rus_verbs:сдружиться{}, // сдружиться с ребятами rus_verbs:соперничать{}, // соперничать с параллельным классом rus_verbs:прочесать{}, // прочесать с собаками rus_verbs:кокетничать{}, // кокетничать с гимназистками rus_verbs:мириться{}, // мириться с убытками rus_verbs:оплошать{}, // оплошать с билетами rus_verbs:отождествлять{}, // отождествлять с литературным героем rus_verbs:хитрить{}, // хитрить с зарплатой rus_verbs:провозиться{}, // провозиться с задачкой rus_verbs:коротать{}, // коротать с друзьями rus_verbs:соревноваться{}, // соревноваться с машиной rus_verbs:уживаться{}, // уживаться с местными жителями rus_verbs:отождествляться{}, // отождествляться с литературным героем rus_verbs:сопоставить{}, // сопоставить с эталоном rus_verbs:пьянствовать{}, // пьянствовать с друзьями rus_verbs:залетать{}, // залетать с паленой водкой rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой rus_verbs:запаздывать{}, // запаздывать с кормлением rus_verbs:таскаться{}, // таскаться с сумками rus_verbs:контрастировать{}, // контрастировать с туфлями rus_verbs:сшибиться{}, // сшибиться с форвардом rus_verbs:состязаться{}, // состязаться с лучшей командой rus_verbs:затрудниться{}, // затрудниться с объяснением rus_verbs:объясниться{}, // объясниться с пострадавшими rus_verbs:разводиться{}, // разводиться со сварливой женой rus_verbs:препираться{}, // препираться с адвокатами rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками rus_verbs:свестись{}, // свестись с нулевым счетом rus_verbs:обговорить{}, // обговорить с директором rus_verbs:обвенчаться{}, // обвенчаться с ведьмой rus_verbs:экспериментировать{}, // экспериментировать с генами rus_verbs:сверять{}, // сверять с таблицей rus_verbs:сверяться{}, // свериться с таблицей rus_verbs:сблизить{}, // сблизить с точкой rus_verbs:гармонировать{}, // гармонировать с обоями rus_verbs:перемешивать{}, // перемешивать с молоком rus_verbs:трепаться{}, // трепаться с сослуживцами rus_verbs:перемигиваться{}, // перемигиваться с соседкой rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем rus_verbs:распить{}, // распить с собутыльниками rus_verbs:скрестись{}, // скрестись с дикой лошадью rus_verbs:передраться{}, // передраться с дворовыми собаками rus_verbs:умыть{}, // умыть с мылом rus_verbs:грызться{}, // грызться с соседями rus_verbs:переругиваться{}, // переругиваться с соседями rus_verbs:доиграться{}, // доиграться со спичками rus_verbs:заладиться{}, // заладиться с подругой rus_verbs:скрещиваться{}, // скрещиваться с дикими видами rus_verbs:повидаться{}, // повидаться с дедушкой rus_verbs:повоевать{}, // повоевать с орками rus_verbs:сразиться{}, // сразиться с лучшим рыцарем rus_verbs:кипятить{}, // кипятить с отбеливателем rus_verbs:усердствовать{}, // усердствовать с наказанием rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером rus_verbs:пошептаться{}, // пошептаться с судьями rus_verbs:сравняться{}, // сравняться с лучшими экземплярами rus_verbs:церемониться{}, // церемониться с пьяницами rus_verbs:консультироваться{}, // консультироваться со специалистами rus_verbs:переусердствовать{}, // переусердствовать с наказанием rus_verbs:проноситься{}, // проноситься с собой rus_verbs:перемешать{}, // перемешать с гипсом rus_verbs:темнить{}, // темнить с долгами rus_verbs:сталкивать{}, // сталкивать с черной дырой rus_verbs:увольнять{}, // увольнять с волчьим билетом rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт rus_verbs:созвониться{}, // созвониться с мамой rus_verbs:спеться{}, // спеться с отъявленными хулиганами rus_verbs:интриговать{}, // интриговать с придворными rus_verbs:приобрести{}, // приобрести со скидкой rus_verbs:задержаться{}, // задержаться со сдачей работы rus_verbs:плавать{}, // плавать со спасательным кругом rus_verbs:якшаться{}, // Не якшайся с врагами инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги инфинитив:ассоциировать{вид:несоверш}, глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги глагол:ассоциировать{вид:несоверш}, //+прилагательное:ассоциировавший{вид:несоверш}, прилагательное:ассоциировавший{вид:соверш}, прилагательное:ассоциирующий{}, деепричастие:ассоциируя{}, деепричастие:ассоциировав{}, rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов //+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом //+глагол:аффилировать{вид:соверш}, прилагательное:аффилированный{}, rus_verbs:баловаться{}, // мальчик баловался с молотком rus_verbs:балясничать{}, // женщина балясничала с товарками rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями rus_verbs:бодаться{}, // теленок бодается с деревом rus_verbs:боксировать{}, // Майкл дважды боксировал с ним rus_verbs:брататься{}, // Солдаты братались с бойцами союзников rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу rus_verbs:происходить{}, // Что происходит с мировой экономикой? rus_verbs:произойти{}, // Что произошло с экономикой? rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями rus_verbs:водиться{}, // Няня водится с детьми rus_verbs:воевать{}, // Фермеры воевали с волками rus_verbs:возиться{}, // Няня возится с детьми rus_verbs:ворковать{}, // Голубь воркует с голубкой rus_verbs:воссоединиться{}, // Дети воссоединились с семьей rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой rus_verbs:враждовать{}, // враждовать с соседями rus_verbs:временить{}, // временить с выходом на пенсию rus_verbs:расстаться{}, // я не могу расстаться с тобой rus_verbs:выдирать{}, // выдирать с мясом rus_verbs:выдираться{}, // выдираться с мясом rus_verbs:вытворить{}, // вытворить что-либо с чем-либо rus_verbs:вытворять{}, // вытворять что-либо с чем-либо rus_verbs:сделать{}, // сделать с чем-то rus_verbs:домыть{}, // домыть с мылом rus_verbs:случиться{}, // случиться с кем-то rus_verbs:остаться{}, // остаться с кем-то rus_verbs:случать{}, // случать с породистым кобельком rus_verbs:послать{}, // послать с весточкой rus_verbs:работать{}, // работать с роботами rus_verbs:провести{}, // провести с девчонками время rus_verbs:заговорить{}, // заговорить с незнакомкой rus_verbs:прошептать{}, // прошептать с придыханием rus_verbs:читать{}, // читать с выражением rus_verbs:слушать{}, // слушать с повышенным вниманием rus_verbs:принести{}, // принести с собой rus_verbs:спать{}, // спать с женщинами rus_verbs:закончить{}, // закончить с приготовлениями rus_verbs:помочь{}, // помочь с перестановкой rus_verbs:уехать{}, // уехать с семьей rus_verbs:случаться{}, // случаться с кем-то rus_verbs:кутить{}, // кутить с проститутками rus_verbs:разговаривать{}, // разговаривать с ребенком rus_verbs:погодить{}, // погодить с ликвидацией rus_verbs:считаться{}, // считаться с чужим мнением rus_verbs:носить{}, // носить с собой rus_verbs:хорошеть{}, // хорошеть с каждым днем rus_verbs:приводить{}, // приводить с собой rus_verbs:прыгнуть{}, // прыгнуть с парашютом rus_verbs:петь{}, // петь с чувством rus_verbs:сложить{}, // сложить с результатом rus_verbs:познакомиться{}, // познакомиться с другими студентами rus_verbs:обращаться{}, // обращаться с животными rus_verbs:съесть{}, // съесть с хлебом rus_verbs:ошибаться{}, // ошибаться с дозировкой rus_verbs:столкнуться{}, // столкнуться с медведем rus_verbs:справиться{}, // справиться с нуждой rus_verbs:торопиться{}, // торопиться с ответом rus_verbs:поздравлять{}, // поздравлять с победой rus_verbs:объясняться{}, // объясняться с начальством rus_verbs:пошутить{}, // пошутить с подругой rus_verbs:поздороваться{}, // поздороваться с коллегами rus_verbs:поступать{}, // Как поступать с таким поведением? rus_verbs:определяться{}, // определяться с кандидатами rus_verbs:связаться{}, // связаться с поставщиком rus_verbs:спорить{}, // спорить с собеседником rus_verbs:разобраться{}, // разобраться с делами rus_verbs:ловить{}, // ловить с удочкой rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос rus_verbs:шутить{}, // шутить с диким зверем rus_verbs:разорвать{}, // разорвать с поставщиком контракт rus_verbs:увезти{}, // увезти с собой rus_verbs:унести{}, // унести с собой rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее rus_verbs:складываться{}, // складываться с первым импульсом rus_verbs:соглашаться{}, // соглашаться с предложенным договором //rus_verbs:покончить{}, // покончить с развратом rus_verbs:прихватить{}, // прихватить с собой rus_verbs:похоронить{}, // похоронить с почестями rus_verbs:связывать{}, // связывать с компанией свою судьбу rus_verbs:совпадать{}, // совпадать с предсказанием rus_verbs:танцевать{}, // танцевать с девушками rus_verbs:поделиться{}, // поделиться с выжившими rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате. rus_verbs:беседовать{}, // преподаватель, беседующий со студентами rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками rus_verbs:поговорить{}, // поговорить с виновниками rus_verbs:сказать{}, // сказать с трудом rus_verbs:произнести{}, // произнести с трудом rus_verbs:говорить{}, // говорить с акцентом rus_verbs:произносить{}, // произносить с трудом rus_verbs:встречаться{}, // кто с Антонио встречался? rus_verbs:посидеть{}, // посидеть с друзьями rus_verbs:расквитаться{}, // расквитаться с обидчиком rus_verbs:поквитаться{}, // поквитаться с обидчиком rus_verbs:ругаться{}, // ругаться с женой rus_verbs:поскандалить{}, // поскандалить с женой rus_verbs:потанцевать{}, // потанцевать с подругой rus_verbs:скандалить{}, // скандалить с соседями rus_verbs:разругаться{}, // разругаться с другом rus_verbs:болтать{}, // болтать с подругами rus_verbs:потрепаться{}, // потрепаться с соседкой rus_verbs:войти{}, // войти с регистрацией rus_verbs:входить{}, // входить с регистрацией rus_verbs:возвращаться{}, // возвращаться с триумфом rus_verbs:опоздать{}, // Он опоздал с подачей сочинения. rus_verbs:молчать{}, // Он молчал с ледяным спокойствием. rus_verbs:сражаться{}, // Он героически сражался с врагами. rus_verbs:выходить{}, // Он всегда выходит с зонтиком. rus_verbs:сличать{}, // сличать перевод с оригиналом rus_verbs:начать{}, // я начал с товарищем спор о религии rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки rus_verbs:приходить{}, // Приходите с нею. rus_verbs:жить{}, // кто с тобой жил? rus_verbs:расходиться{}, // Маша расходится с Петей rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой rus_verbs:торговать{}, // мы торгуем с ними нефтью rus_verbs:уединяться{}, // уединяться с подругой в доме rus_verbs:уладить{}, // уладить конфликт с соседями rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем. rus_verbs:разделять{}, // Я разделяю с вами горе и радость. rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи. rus_verbs:захватить{}, // Я не захватил с собой денег. прилагательное:знакомый{}, // Я знаком с ними обоими. rus_verbs:вести{}, // Я веду с ней переписку. прилагательное:сопряженный{}, // Это сопряжено с большими трудностями. прилагательное:связанный{причастие}, // Это дело связано с риском. rus_verbs:поехать{}, // Хотите поехать со мной в театр? rus_verbs:проснуться{}, // Утром я проснулся с ясной головой. rus_verbs:лететь{}, // Самолёт летел со скоростью звука. rus_verbs:играть{}, // С огнём играть опасно! rus_verbs:поделать{}, // С ним ничего не поделаешь. rus_verbs:стрястись{}, // С ней стряслось несчастье. rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием. rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием. rus_verbs:разойтись{}, // Она разошлась с мужем. rus_verbs:пристать{}, // Она пристала ко мне с расспросами. rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением. rus_verbs:поступить{}, // Она плохо поступила с ним. rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом. rus_verbs:взять{}, // Возьмите с собой только самое необходимое. rus_verbs:наплакаться{}, // Наплачется она с ним. rus_verbs:лежать{}, // Он лежит с воспалением лёгких. rus_verbs:дышать{}, // дышащий с трудом rus_verbs:брать{}, // брать с собой rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой. rus_verbs:упасть{}, // Ваза упала со звоном. rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком rus_verbs:сидеть{}, // Она сидит дома с ребенком rus_verbs:встретиться{}, // встречаться с кем-либо ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{}, rus_verbs:мыть{} } fact гл_предл { if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} } then return true } #endregion ТВОРИТЕЛЬНЫЙ #region РОДИТЕЛЬНЫЙ wordentry_set Гл_С_Род= { rus_verbs:УХОДИТЬ{}, // Но с базы не уходить. rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ) rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ) rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ) rus_verbs:РАЗГЛЯДЕТЬ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ) rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ) rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ) rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ) rus_verbs:ЗАРЕВЕТЬ{}, // rus_verbs:ПРОРЕВЕТЬ{}, // rus_verbs:ЗАОРАТЬ{}, // rus_verbs:ПРООРАТЬ{}, // rus_verbs:ОРАТЬ{}, // rus_verbs:ЗАКРИЧАТЬ{}, rus_verbs:ВОПИТЬ{}, // rus_verbs:ЗАВОПИТЬ{}, // rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ) rus_verbs:СТАСКИВАТЬ{}, // rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ) rus_verbs:ЗАВЫТЬ{}, // rus_verbs:ВЫТЬ{}, // rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ) rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА) rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое rus_verbs:собирать{}, // мальчики начали собирать со столов посуду rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ) rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ) rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ) rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ) rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ) rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род) rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род) rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С) rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С) rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род) rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С) rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С) rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С) rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С) rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род) rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род) rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род) rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род) rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род) rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С) rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род) rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род) rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род) rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род) rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род) rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род) rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С) rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род) rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род) rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род) rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С) rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С) rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С) прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С) rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С) rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род) rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С) rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с) rus_verbs:спасть{}, // тяжесть спала с души. (спасть с) rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С) rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С) rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С) rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то) rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С) rus_verbs:приближаться{}, // со стороны острова приближалась лодка. rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С) rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с) rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с) rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С) rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С) rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С) rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С) rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С) rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С) rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.) rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С) rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С) rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С) rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С) rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с) rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С) rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с) rus_verbs:мешать{}, // мешать воду с мукой (мешать с) rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с) rus_verbs:вставать{}, // Он не встает с кровати. (вставать с) rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с) rus_verbs:причитаться{}, // С вас причитается 50 рублей. rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки. rus_verbs:сократить{}, // Его сократили со службы. rus_verbs:поднять{}, // рука подняла с пола rus_verbs:поднимать{}, rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни. rus_verbs:полететь{}, // Мальчик полетел с лестницы. rus_verbs:литься{}, // вода льется с неба rus_verbs:натечь{}, // натечь с сапог rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая rus_verbs:съезжать{}, // съезжать с заявленной темы rus_verbs:покатываться{}, // покатываться со смеху rus_verbs:перескакивать{}, // перескакивать с одного примера на другой rus_verbs:сдирать{}, // сдирать с тела кожу rus_verbs:соскальзывать{}, // соскальзывать с крючка rus_verbs:сметать{}, // сметать с прилавков rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки rus_verbs:прокаркать{}, // прокаркать с ветки rus_verbs:стряхивать{}, // стряхивать с одежды rus_verbs:сваливаться{}, // сваливаться с лестницы rus_verbs:слизнуть{}, // слизнуть с лица rus_verbs:доставляться{}, // доставляться с фермы rus_verbs:обступать{}, // обступать с двух сторон rus_verbs:повскакивать{}, // повскакивать с мест rus_verbs:обозревать{}, // обозревать с вершины rus_verbs:слинять{}, // слинять с урока rus_verbs:смывать{}, // смывать с лица rus_verbs:спихнуть{}, // спихнуть со стола rus_verbs:обозреть{}, // обозреть с вершины rus_verbs:накупить{}, // накупить с рук rus_verbs:схлынуть{}, // схлынуть с берега rus_verbs:спикировать{}, // спикировать с километровой высоты rus_verbs:уползти{}, // уползти с поля боя rus_verbs:сбиваться{}, // сбиваться с пути rus_verbs:отлучиться{}, // отлучиться с поста rus_verbs:сигануть{}, // сигануть с крыши rus_verbs:сместить{}, // сместить с поста rus_verbs:списать{}, // списать с оригинального устройства инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы деепричастие:слетая{}, rus_verbs:напиваться{}, // напиваться с горя rus_verbs:свесить{}, // свесить с крыши rus_verbs:заполучить{}, // заполучить со склада rus_verbs:спадать{}, // спадать с глаз rus_verbs:стартовать{}, // стартовать с мыса rus_verbs:спереть{}, // спереть со склада rus_verbs:согнать{}, // согнать с живота rus_verbs:скатываться{}, // скатываться со стога rus_verbs:сняться{}, // сняться с выборов rus_verbs:слезать{}, // слезать со стола rus_verbs:деваться{}, // деваться с подводной лодки rus_verbs:огласить{}, // огласить с трибуны rus_verbs:красть{}, // красть со склада rus_verbs:расширить{}, // расширить с торца rus_verbs:угадывать{}, // угадывать с полуслова rus_verbs:оскорбить{}, // оскорбить со сцены rus_verbs:срывать{}, // срывать с головы rus_verbs:сшибить{}, // сшибить с коня rus_verbs:сбивать{}, // сбивать с одежды rus_verbs:содрать{}, // содрать с посетителей rus_verbs:столкнуть{}, // столкнуть с горы rus_verbs:отряхнуть{}, // отряхнуть с одежды rus_verbs:сбрасывать{}, // сбрасывать с борта rus_verbs:расстреливать{}, // расстреливать с борта вертолета rus_verbs:придти{}, // мать скоро придет с работы rus_verbs:съехать{}, // Миша съехал с горки rus_verbs:свисать{}, // свисать с веток rus_verbs:стянуть{}, // стянуть с кровати rus_verbs:скинуть{}, // скинуть снег с плеча rus_verbs:загреметь{}, // загреметь со стула rus_verbs:сыпаться{}, // сыпаться с неба rus_verbs:стряхнуть{}, // стряхнуть с головы rus_verbs:сползти{}, // сползти со стула rus_verbs:стереть{}, // стереть с экрана rus_verbs:прогнать{}, // прогнать с фермы rus_verbs:смахнуть{}, // смахнуть со стола rus_verbs:спускать{}, // спускать с поводка rus_verbs:деться{}, // деться с подводной лодки rus_verbs:сдернуть{}, // сдернуть с себя rus_verbs:сдвинуться{}, // сдвинуться с места rus_verbs:слететь{}, // слететь с катушек rus_verbs:обступить{}, // обступить со всех сторон rus_verbs:снести{}, // снести с плеч инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков деепричастие:сбегая{}, прилагательное:сбегающий{}, // прилагательное:сбегавший{ вид:несоверш }, rus_verbs:запить{}, // запить с горя rus_verbs:рубануть{}, // рубануть с плеча rus_verbs:чертыхнуться{}, // чертыхнуться с досады rus_verbs:срываться{}, // срываться с цепи rus_verbs:смыться{}, // смыться с уроков rus_verbs:похитить{}, // похитить со склада rus_verbs:смести{}, // смести со своего пути rus_verbs:отгружать{}, // отгружать со склада rus_verbs:отгрузить{}, // отгрузить со склада rus_verbs:бросаться{}, // Дети бросались в воду с моста rus_verbs:броситься{}, // самоубийца бросился с моста в воду rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя rus_verbs:взиматься{}, // Плата взимается с любого посетителя rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков rus_verbs:вспархивать{}, // вспархивать с цветка rus_verbs:вспорхнуть{}, // вспорхнуть с ветки rus_verbs:выбросить{}, // выбросить что-то с балкона rus_verbs:выводить{}, // выводить с одежды пятна rus_verbs:снять{}, // снять с головы rus_verbs:начинать{}, // начинать с эскиза rus_verbs:двинуться{}, // двинуться с места rus_verbs:начинаться{}, // начинаться с гардероба rus_verbs:стечь{}, // стечь с крыши rus_verbs:слезть{}, // слезть с кучи rus_verbs:спуститься{}, // спуститься с крыши rus_verbs:сойти{}, // сойти с пьедестала rus_verbs:свернуть{}, // свернуть с пути rus_verbs:сорвать{}, // сорвать с цепи rus_verbs:сорваться{}, // сорваться с поводка rus_verbs:тронуться{}, // тронуться с места rus_verbs:угадать{}, // угадать с первой попытки rus_verbs:спустить{}, // спустить с лестницы rus_verbs:соскочить{}, // соскочить с крючка rus_verbs:сдвинуть{}, // сдвинуть с места rus_verbs:подниматься{}, // туман, поднимающийся с болота rus_verbs:подняться{}, // туман, поднявшийся с болота rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног. rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног. rus_verbs:донестись{}, // С улицы донесся шум дождя. rus_verbs:опасть{}, // Опавшие с дерева листья. rus_verbs:махнуть{}, // Он махнул с берега в воду. rus_verbs:исчезнуть{}, // исчезнуть с экрана rus_verbs:свалиться{}, // свалиться со сцены rus_verbs:упасть{}, // упасть с дерева rus_verbs:вернуться{}, // Он ещё не вернулся с работы. rus_verbs:сдувать{}, // сдувать пух с одуванчиков rus_verbs:свергать{}, // свергать царя с трона rus_verbs:сбиться{}, // сбиться с пути rus_verbs:стирать{}, // стирать тряпкой надпись с доски rus_verbs:убирать{}, // убирать мусор c пола rus_verbs:удалять{}, // удалять игрока с поля rus_verbs:окружить{}, // Япония окружена со всех сторон морями. rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение. глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы. прилагательное:спокойный{}, // С этой стороны я спокоен. rus_verbs:спросить{}, // С тебя за всё спросят. rus_verbs:течь{}, // С него течёт пот. rus_verbs:дуть{}, // С моря дует ветер. rus_verbs:капать{}, // С его лица капали крупные капли пота. rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол. rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня. rus_verbs:встать{}, // Все встали со стульев. rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто. rus_verbs:взять{}, // Возьми книгу с полки. rus_verbs:спускаться{}, // Мы спускались с горы. rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы. rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок. rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы. rus_verbs:двигаться{}, // Он не двигался с места. rus_verbs:отходить{}, // мой поезд отходит с первого пути rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции rus_verbs:падать{}, // снег падает с ветвей rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия. } fact гл_предл { if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:род} } then return true } fact гл_предл { if context { Гл_С_Род предлог:с{} *:*{падеж:парт} } then return true } #endregion РОДИТЕЛЬНЫЙ fact гл_предл { if context { * предлог:с{} *:*{ падеж:твор } } then return false,-3 } fact гл_предл { if context { * предлог:с{} *:*{ падеж:род } } then return false,-4 } fact гл_предл { if context { * предлог:с{} * } then return false,-5 } #endregion Предлог_С /* #region Предлог_ПОД // -------------- ПРЕДЛОГ 'ПОД' ----------------------- fact гл_предл { if context { * предлог:под{} @regex("[a-z]+[0-9]*") } then return true } // ПОД+вин.п. не может присоединяться к существительным, поэтому // он присоединяется к любым глаголам. fact гл_предл { if context { * предлог:под{} *:*{ падеж:вин } } then return true } wordentry_set Гл_ПОД_твор= { rus_verbs:извиваться{}, // извивалась под его длинными усами rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ) rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ) rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ) rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ) rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ) rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ) rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть) rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ) rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ) rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ) rus_verbs:ПРОПОЛЗТИ{}, // rus_verbs:ПРОПОЛЗАТЬ{}, // rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ) rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ) rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ) rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ) rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ) rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом rus_verbs:иметься{}, // у каждого под рукой имелся арбалет rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ) rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ) rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ) rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ) rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ) rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ) rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ) rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ) rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ) rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ) rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ) rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ) rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ) rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор) rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ) rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ) rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ) rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ) rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ) rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ) rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ) rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ) rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ) rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ) rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ) rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ) rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ) rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ) rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ) rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ) rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ) rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ) rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ) rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ) rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ) rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД) rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ) rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД) rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ) rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ) rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ) rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ) rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ) rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ) rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ) rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ) rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ) rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ) rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ) rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ) rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ) rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ) rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ) rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ) rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ) rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ) rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ) rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ) rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ) rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ) rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ) rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ) rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ) rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ) rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ) rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ) rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ) rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ) rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ) rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД) rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД) rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД) rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД) rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД) rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД) rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД) rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД) rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор) rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД) rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД) rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД) rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД) rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД) rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД) rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД) rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД) rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД) rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД) rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД) rus_verbs:уснуть{}, // Миша уснет под одеялом rus_verbs:пошевелиться{}, // пошевелиться под одеялом rus_verbs:задохнуться{}, // задохнуться под слоем снега rus_verbs:потечь{}, // потечь под избыточным давлением rus_verbs:уцелеть{}, // уцелеть под завалами rus_verbs:мерцать{}, // мерцать под лучами софитов rus_verbs:поискать{}, // поискать под кроватью rus_verbs:гудеть{}, // гудеть под нагрузкой rus_verbs:посидеть{}, // посидеть под навесом rus_verbs:укрыться{}, // укрыться под навесом rus_verbs:утихнуть{}, // утихнуть под одеялом rus_verbs:заскрипеть{}, // заскрипеть под тяжестью rus_verbs:шелохнуться{}, // шелохнуться под одеялом инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш }, инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш }, деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш }, rus_verbs:пониматься{}, // пониматься под успехом rus_verbs:подразумеваться{}, // подразумеваться под правильным решением rus_verbs:промокнуть{}, // промокнуть под проливным дождем rus_verbs:засосать{}, // засосать под ложечкой rus_verbs:подписаться{}, // подписаться под воззванием rus_verbs:укрываться{}, // укрываться под навесом rus_verbs:запыхтеть{}, // запыхтеть под одеялом rus_verbs:мокнуть{}, // мокнуть под лождем rus_verbs:сгибаться{}, // сгибаться под тяжестью снега rus_verbs:намокнуть{}, // намокнуть под дождем rus_verbs:подписываться{}, // подписываться под обращением rus_verbs:тарахтеть{}, // тарахтеть под окнами инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача. деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{}, rus_verbs:лежать{}, // лежать под капельницей rus_verbs:вымокать{}, // вымокать под дождём rus_verbs:вымокнуть{}, // вымокнуть под дождём rus_verbs:проворчать{}, // проворчать под нос rus_verbs:хмыкнуть{}, // хмыкнуть под нос rus_verbs:отыскать{}, // отыскать под кроватью rus_verbs:дрогнуть{}, // дрогнуть под ударами rus_verbs:проявляться{}, // проявляться под нагрузкой rus_verbs:сдержать{}, // сдержать под контролем rus_verbs:ложиться{}, // ложиться под клиента rus_verbs:таять{}, // таять под весенним солнцем rus_verbs:покатиться{}, // покатиться под откос rus_verbs:лечь{}, // он лег под навесом rus_verbs:идти{}, // идти под дождем прилагательное:известный{}, // Он известен под этим именем. rus_verbs:стоять{}, // Ящик стоит под столом. rus_verbs:отступить{}, // Враг отступил под ударами наших войск. rus_verbs:царапаться{}, // Мышь царапается под полом. rus_verbs:спать{}, // заяц спокойно спал у себя под кустом rus_verbs:загорать{}, // мы загораем под солнцем ГЛ_ИНФ(мыть), // мыть руки под струёй воды ГЛ_ИНФ(закопать), ГЛ_ИНФ(спрятать), ГЛ_ИНФ(прятать), ГЛ_ИНФ(перепрятать) } fact гл_предл { if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } } then return true } // для глаголов вне списка - запрещаем. fact гл_предл { if context { * предлог:под{} *:*{ падеж:твор } } then return false,-10 } fact гл_предл { if context { * предлог:под{} *:*{} } then return false,-11 } #endregion Предлог_ПОД */ #region Предлог_ОБ // -------------- ПРЕДЛОГ 'ОБ' ----------------------- wordentry_set Гл_ОБ_предл= { rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ) rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ) rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ) rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом? rus_verbs:забывать{}, // Мы не можем забывать об их участи. rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ) rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ) rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ) rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ) rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ) rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ) rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ) rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ) rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ) rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ) rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об) rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об) rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ) rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ) rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ) rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе. rus_verbs:кричать{}, // Все газеты кричат об этом событии. rus_verbs:советоваться{}, // Она обо всём советуется с матерью. rus_verbs:говориться{}, // об остальном говорилось легко. rus_verbs:подумать{}, // нужно крепко обо всем подумать. rus_verbs:напомнить{}, // черный дым напомнил об опасности. rus_verbs:забыть{}, // забудь об этой роскоши. rus_verbs:думать{}, // приходится обо всем думать самой. rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:информировать{}, // информировать об изменениях rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:заговорить{}, // заговорить об оплате rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой. rus_verbs:попросить{}, // попросить об услуге rus_verbs:объявить{}, // объявить об отставке rus_verbs:предупредить{}, // предупредить об аварии rus_verbs:предупреждать{}, // предупреждать об опасности rus_verbs:твердить{}, // твердить об обязанностях rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц. rus_verbs:читать{}, // он читал об этом в журнале rus_verbs:прочитать{}, // он читал об этом в учебнике rus_verbs:узнать{}, // он узнал об этом из фильмов rus_verbs:рассказать{}, // рассказать об экзаменах rus_verbs:рассказывать{}, rus_verbs:договориться{}, // договориться об оплате rus_verbs:договариваться{}, // договариваться об обмене rus_verbs:болтать{}, // Не болтай об этом! rus_verbs:проболтаться{}, // Не проболтайся об этом! rus_verbs:заботиться{}, // кто заботится об урегулировании rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне rus_verbs:помнить{}, // всем советую об этом помнить rus_verbs:мечтать{} // Мечтать об успехе } fact гл_предл { if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } } then return true } fact гл_предл { if context { * предлог:о{} @regex("[a-z]+[0-9]*") } then return true } fact гл_предл { if context { * предлог:об{} @regex("[a-z]+[0-9]*") } then return true } // остальные глаголы не могут связываться fact гл_предл { if context { * предлог:об{} *:*{ падеж:предл } } then return false, -4 } wordentry_set Гл_ОБ_вин= { rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ) rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ) rus_verbs:опереться{}, // Он опёрся об стену. rus_verbs:опираться{}, rus_verbs:постучать{}, // постучал лбом об пол. rus_verbs:удариться{}, // бутылка глухо ударилась об землю. rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:царапаться{} // Днище лодки царапалось обо что-то. } fact гл_предл { if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:об{} *:*{ падеж:вин } } then return false,-4 } fact гл_предл { if context { * предлог:об{} *:*{} } then return false,-5 } #endregion Предлог_ОБ #region Предлог_О // ------------------- С ПРЕДЛОГОМ 'О' ---------------------- wordentry_set Гл_О_Вин={ rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену. rus_verbs:болтать{}, // Болтали чаще всего о пустяках. rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг. rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол. rus_verbs:бахнуться{}, // Бахнуться головой о стол. rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ) rus_verbs:ВЫТИРАТЬ{}, // rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ) rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ) rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ) rus_verbs:ЛЯЗГАТЬ{}, // rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ) rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ) rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ) rus_verbs:колотиться{}, // сердце его колотилось о ребра rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей. rus_verbs:биться{}, // биться головой о стену? (биться о) rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о) rus_verbs:разбиваться{}, // волны разбивались о скалу rus_verbs:разбивать{}, // Разбивает голову о прутья клетки. rus_verbs:облокотиться{}, // облокотиться о стену rus_verbs:точить{}, // точить о точильный камень rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень rus_verbs:потереться{}, // потереться о дерево rus_verbs:ушибиться{}, // ушибиться о дерево rus_verbs:тереться{}, // тереться о ствол rus_verbs:шмякнуться{}, // шмякнуться о землю rus_verbs:убиваться{}, // убиваться об стену rus_verbs:расшибить{}, // расшибить об стену rus_verbs:тереть{}, // тереть о камень rus_verbs:потереть{}, // потереть о колено rus_verbs:удариться{}, // удариться о край rus_verbs:споткнуться{}, // споткнуться о камень rus_verbs:запнуться{}, // запнуться о камень rus_verbs:запинаться{}, // запинаться о камни rus_verbs:ударяться{}, // ударяться о бортик rus_verbs:стукнуться{}, // стукнуться о бортик rus_verbs:стукаться{}, // стукаться о бортик rus_verbs:опереться{}, // Он опёрся локтями о стол. rus_verbs:плескаться{} // Вода плещется о берег. } fact гл_предл { if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } } then return true } fact гл_предл { if context { * предлог:о{} *:*{ падеж:вин } } then return false,-5 } wordentry_set Гл_О_предл={ rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ) rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ) rus_verbs:РАССПРАШИВАТЬ{}, // rus_verbs:слушать{}, // ты будешь слушать о них? rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ) rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ) rus_verbs:сложить{}, // о вас сложены легенды rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О) rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О) rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О) rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О) rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О) rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О) rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О) rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О) rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О) rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О) rus_verbs:осведомиться{}, // офицер осведомился о цели визита rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о) rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О) rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о) rus_verbs:зайти{}, // Разговор зашёл о политике. rus_verbs:порассказать{}, // порассказать о своих путешествиях инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви деепричастие:спев{}, прилагательное:спевший{ вид:соверш }, прилагательное:спетый{}, rus_verbs:напеть{}, rus_verbs:разговаривать{}, // разговаривать с другом о жизни rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях //rus_verbs:заботиться{}, // заботиться о престарелых родителях rus_verbs:раздумывать{}, // раздумывать о новой работе rus_verbs:договариваться{}, // договариваться о сумме компенсации rus_verbs:молить{}, // молить о пощаде rus_verbs:отзываться{}, // отзываться о книге rus_verbs:подумывать{}, // подумывать о новом подходе rus_verbs:поговаривать{}, // поговаривать о загадочном звере rus_verbs:обмолвиться{}, // обмолвиться о проклятии rus_verbs:условиться{}, // условиться о поддержке rus_verbs:призадуматься{}, // призадуматься о последствиях rus_verbs:известить{}, // известить о поступлении rus_verbs:отрапортовать{}, // отрапортовать об успехах rus_verbs:напевать{}, // напевать о любви rus_verbs:помышлять{}, // помышлять о новом деле rus_verbs:переговорить{}, // переговорить о правилах rus_verbs:повествовать{}, // повествовать о событиях rus_verbs:слыхивать{}, // слыхивать о чудище rus_verbs:потолковать{}, // потолковать о планах rus_verbs:проговориться{}, // проговориться о планах rus_verbs:умолчать{}, // умолчать о штрафах rus_verbs:хлопотать{}, // хлопотать о премии rus_verbs:уведомить{}, // уведомить о поступлении rus_verbs:горевать{}, // горевать о потере rus_verbs:запамятовать{}, // запамятовать о важном мероприятии rus_verbs:заикнуться{}, // заикнуться о прибавке rus_verbs:информировать{}, // информировать о событиях rus_verbs:проболтаться{}, // проболтаться о кладе rus_verbs:поразмыслить{}, // поразмыслить о судьбе rus_verbs:заикаться{}, // заикаться о деньгах rus_verbs:оповестить{}, // оповестить об отказе rus_verbs:печься{}, // печься о всеобщем благе rus_verbs:разглагольствовать{}, // разглагольствовать о правах rus_verbs:размечтаться{}, // размечтаться о будущем rus_verbs:лепетать{}, // лепетать о невиновности rus_verbs:грезить{}, // грезить о большой и чистой любви rus_verbs:залепетать{}, // залепетать о сокровищах rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде rus_verbs:протрубить{}, // протрубить о победе rus_verbs:извещать{}, // извещать о поступлении rus_verbs:трубить{}, // трубить о поимке разбойников rus_verbs:осведомляться{}, // осведомляться о судьбе rus_verbs:поразмышлять{}, // поразмышлять о неизбежном rus_verbs:слагать{}, // слагать о подвигах викингов rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании rus_verbs:закидывать{}, // закидывать сообщениями об ошибках rus_verbs:базарить{}, // пацаны базарили о телках rus_verbs:балагурить{}, // мужики балагурили о новом председателе rus_verbs:балакать{}, // мужики балакали о новом председателе rus_verbs:беспокоиться{}, // Она беспокоится о детях rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве rus_verbs:возмечтать{}, // возмечтать о счастливом мире rus_verbs:вопить{}, // Кто-то вопил о несправедливости rus_verbs:сказать{}, // сказать что-то новое о ком-то rus_verbs:знать{}, // знать о ком-то что-то пикантное rus_verbs:подумать{}, // подумать о чём-то rus_verbs:думать{}, // думать о чём-то rus_verbs:узнать{}, // узнать о происшествии rus_verbs:помнить{}, // помнить о задании rus_verbs:просить{}, // просить о коде доступа rus_verbs:забыть{}, // забыть о своих обязанностях rus_verbs:сообщить{}, // сообщить о заложенной мине rus_verbs:заявить{}, // заявить о пропаже rus_verbs:задуматься{}, // задуматься о смерти rus_verbs:спрашивать{}, // спрашивать о поступлении товара rus_verbs:догадаться{}, // догадаться о причинах rus_verbs:договориться{}, // договориться о собеседовании rus_verbs:мечтать{}, // мечтать о сцене rus_verbs:поговорить{}, // поговорить о наболевшем rus_verbs:размышлять{}, // размышлять о насущном rus_verbs:напоминать{}, // напоминать о себе rus_verbs:пожалеть{}, // пожалеть о содеянном rus_verbs:ныть{}, // ныть о прибавке rus_verbs:сообщать{}, // сообщать о победе rus_verbs:догадываться{}, // догадываться о первопричине rus_verbs:поведать{}, // поведать о тайнах rus_verbs:умолять{}, // умолять о пощаде rus_verbs:сожалеть{}, // сожалеть о случившемся rus_verbs:жалеть{}, // жалеть о случившемся rus_verbs:забывать{}, // забывать о случившемся rus_verbs:упоминать{}, // упоминать о предках rus_verbs:позабыть{}, // позабыть о своем обещании rus_verbs:запеть{}, // запеть о любви rus_verbs:скорбеть{}, // скорбеть о усопшем rus_verbs:задумываться{}, // задумываться о смене работы rus_verbs:позаботиться{}, // позаботиться о престарелых родителях rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината rus_verbs:попросить{}, // попросить о замене rus_verbs:предупредить{}, // предупредить о замене rus_verbs:предупреждать{}, // предупреждать о замене rus_verbs:твердить{}, // твердить о замене rus_verbs:заявлять{}, // заявлять о подлоге rus_verbs:петь{}, // певица, поющая о лете rus_verbs:проинформировать{}, // проинформировать о переговорах rus_verbs:порассказывать{}, // порассказывать о событиях rus_verbs:послушать{}, // послушать о новинках rus_verbs:заговорить{}, // заговорить о плате rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой. rus_verbs:оставить{}, // Он оставил о себе печальную память. rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях rus_verbs:спорить{}, // они спорили о законе глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия. глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия. rus_verbs:прочитать{}, // Я прочитал о тебе rus_verbs:услышать{}, // Я услышал о нем rus_verbs:помечтать{}, // Девочки помечтали о принце rus_verbs:слышать{}, // Мальчик слышал о приведениях rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке rus_verbs:грустить{}, // Я грущу о тебе rus_verbs:осведомить{}, // о последних достижениях науки rus_verbs:рассказывать{}, // Антонио рассказывает о работе rus_verbs:говорить{}, // говорим о трех больших псах rus_verbs:идти{} // Вопрос идёт о войне. } fact гл_предл { if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } } then return true } // Мы поделились впечатлениями о выставке. // ^^^^^^^^^^ ^^^^^^^^^^ fact гл_предл { if context { * предлог:о{} *:*{ падеж:предл } } then return false,-3 } fact гл_предл { if context { * предлог:о{} *:*{} } then return false,-5 } #endregion Предлог_О #region Предлог_ПО // ------------------- С ПРЕДЛОГОМ 'ПО' ---------------------- // для этих глаголов - запрещаем связывание с ПО+дат.п. wordentry_set Глаг_ПО_Дат_Запр= { rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж rus_verbs:увлечь{}, // увлечь в прогулку по парку rus_verbs:закончить{}, rus_verbs:мочь{}, rus_verbs:хотеть{} } fact гл_предл { if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } } then return false,-10 } // По умолчанию разрешаем связывание в паттернах типа // Я иду по шоссе fact гл_предл { if context { * предлог:по{} *:*{ падеж:дат } } then return true } wordentry_set Глаг_ПО_Вин= { rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ) rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО) rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера rus_verbs:засадить{}, // засадить по рукоятку rus_verbs:увязнуть{} // увязнуть по колено } fact гл_предл { if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:по{} *:*{ падеж:вин } } then return false,-5 } #endregion Предлог_ПО #region Предлог_К // ------------------- С ПРЕДЛОГОМ 'К' ---------------------- wordentry_set Гл_К_Дат={ rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна. rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску. прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ) rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ) rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ) rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ) rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ) rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ) rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ) rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ) rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ) rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, // rus_verbs:ПРИНОРОВИТЬСЯ{}, // rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ) rus_verbs:СПИКИРОВАТЬ{}, // rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С) rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ) rus_verbs:ПРОТЯНУТЬ{}, // rus_verbs:ТЯНУТЬ{}, // rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ) rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,, rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, // rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, // rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ) rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке. rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ) rus_verbs:хотеть{}, rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ) rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ) rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ) rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ) rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ) rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ) rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ) rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ) rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ) rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ) rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ) rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К) rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К) rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К) rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К) rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К) прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К) безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К) rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К) rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К) rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К) rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К) rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К) rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К) rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К) rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К) rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К) rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К) rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К) rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К) rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К) rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К) rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К) rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К) rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К) rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К) rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К) rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К) rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К) rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К) rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К) глагол:быть{}, // к тебе есть вопросы. прилагательное:равнодушный{}, // Он равнодушен к музыке. rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К) rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К) инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К) rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К) rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к) rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К) rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К) rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К) rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К) rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К) rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К) rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К) rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к) rus_verbs:просить{}, // Директор просит вас к себе. (просить к) rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к) rus_verbs:присесть{}, // старик присел к огню. (присесть к) rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К) rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к) rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к) rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К) rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К) rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К) rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К) rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к) rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К) rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К) rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К) rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К) rus_verbs:подходить{}, // цвет подходил ей к лицу. rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К) rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К) rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К) rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К) rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К) rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К) rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к) rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К) rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К) rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к) rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к) rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К) rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К) rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К) rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К) rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к) rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к) rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к) rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К) rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к) rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к) rus_verbs:требовать{}, // вас требует к себе император. (требовать к) rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к) rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к) rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К) rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К) rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к) rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К) rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К) rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к) rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к) rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к) rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К) rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к) rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к) rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к) rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К) rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К) rus_verbs:выехать{}, // почти сразу мы выехали к реке. rus_verbs:пододвигаться{}, // пододвигайся к окну rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам. rus_verbs:представить{}, // Его представили к ордену. rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу. rus_verbs:выскочить{}, // тем временем они выскочили к реке. rus_verbs:выйти{}, // тем временем они вышли к лестнице. rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе. rus_verbs:приложить{}, // приложить к детали повышенное усилие rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку) rus_verbs:отнестись{}, // отнестись к животным с сочуствием rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю rus_verbs:прыгать{}, // прыгать к хозяину на стол rus_verbs:приглашать{}, // приглашать к доктору rus_verbs:рваться{}, // Чужие люди рвутся к власти rus_verbs:понестись{}, // понестись к обрыву rus_verbs:питать{}, // питать привязанность к алкоголю rus_verbs:заехать{}, // Коля заехал к Оле rus_verbs:переехать{}, // переехать к родителям rus_verbs:ползти{}, // ползти к дороге rus_verbs:сводиться{}, // сводиться к элементарному действию rus_verbs:добавлять{}, // добавлять к общей сумме rus_verbs:подбросить{}, // подбросить к потолку rus_verbs:призывать{}, // призывать к спокойствию rus_verbs:пробираться{}, // пробираться к партизанам rus_verbs:отвезти{}, // отвезти к родителям rus_verbs:применяться{}, // применяться к уравнению rus_verbs:сходиться{}, // сходиться к точному решению rus_verbs:допускать{}, // допускать к сдаче зачета rus_verbs:свести{}, // свести к нулю rus_verbs:придвинуть{}, // придвинуть к мальчику rus_verbs:подготовить{}, // подготовить к печати rus_verbs:подобраться{}, // подобраться к оленю rus_verbs:заторопиться{}, // заторопиться к выходу rus_verbs:пристать{}, // пристать к берегу rus_verbs:поманить{}, // поманить к себе rus_verbs:припасть{}, // припасть к алтарю rus_verbs:притащить{}, // притащить к себе домой rus_verbs:прижимать{}, // прижимать к груди rus_verbs:подсесть{}, // подсесть к симпатичной девочке rus_verbs:придвинуться{}, // придвинуться к окну rus_verbs:отпускать{}, // отпускать к другу rus_verbs:пригнуться{}, // пригнуться к земле rus_verbs:пристроиться{}, // пристроиться к колонне rus_verbs:сгрести{}, // сгрести к себе rus_verbs:удрать{}, // удрать к цыганам rus_verbs:прибавиться{}, // прибавиться к общей сумме rus_verbs:присмотреться{}, // присмотреться к покупке rus_verbs:подкатить{}, // подкатить к трюму rus_verbs:клонить{}, // клонить ко сну rus_verbs:проследовать{}, // проследовать к выходу rus_verbs:пододвинуть{}, // пододвинуть к себе rus_verbs:применять{}, // применять к сотрудникам rus_verbs:прильнуть{}, // прильнуть к экранам rus_verbs:подвинуть{}, // подвинуть к себе rus_verbs:примчаться{}, // примчаться к папе rus_verbs:подкрасться{}, // подкрасться к жертве rus_verbs:привязаться{}, // привязаться к собаке rus_verbs:забирать{}, // забирать к себе rus_verbs:прорваться{}, // прорваться к кассе rus_verbs:прикасаться{}, // прикасаться к коже rus_verbs:уносить{}, // уносить к себе rus_verbs:подтянуться{}, // подтянуться к месту rus_verbs:привозить{}, // привозить к ветеринару rus_verbs:подползти{}, // подползти к зайцу rus_verbs:приблизить{}, // приблизить к глазам rus_verbs:применить{}, // применить к уравнению простое преобразование rus_verbs:приглядеться{}, // приглядеться к изображению rus_verbs:приложиться{}, // приложиться к ручке rus_verbs:приставать{}, // приставать к девчонкам rus_verbs:запрещаться{}, // запрещаться к показу rus_verbs:прибегать{}, // прибегать к насилию rus_verbs:побудить{}, // побудить к действиям rus_verbs:притягивать{}, // притягивать к себе rus_verbs:пристроить{}, // пристроить к полезному делу rus_verbs:приговорить{}, // приговорить к смерти rus_verbs:склоняться{}, // склоняться к прекращению разработки rus_verbs:подъезжать{}, // подъезжать к вокзалу rus_verbs:привалиться{}, // привалиться к забору rus_verbs:наклоняться{}, // наклоняться к щенку rus_verbs:подоспеть{}, // подоспеть к обеду rus_verbs:прилипнуть{}, // прилипнуть к окну rus_verbs:приволочь{}, // приволочь к себе rus_verbs:устремляться{}, // устремляться к вершине rus_verbs:откатиться{}, // откатиться к исходным позициям rus_verbs:побуждать{}, // побуждать к действиям rus_verbs:прискакать{}, // прискакать к кормежке rus_verbs:присматриваться{}, // присматриваться к новичку rus_verbs:прижиматься{}, // прижиматься к борту rus_verbs:жаться{}, // жаться к огню rus_verbs:передвинуть{}, // передвинуть к окну rus_verbs:допускаться{}, // допускаться к экзаменам rus_verbs:прикрепить{}, // прикрепить к корпусу rus_verbs:отправлять{}, // отправлять к специалистам rus_verbs:перебежать{}, // перебежать к врагам rus_verbs:притронуться{}, // притронуться к реликвии rus_verbs:заспешить{}, // заспешить к семье rus_verbs:ревновать{}, // ревновать к сопернице rus_verbs:подступить{}, // подступить к горлу rus_verbs:уводить{}, // уводить к ветеринару rus_verbs:побросать{}, // побросать к ногам rus_verbs:подаваться{}, // подаваться к ужину rus_verbs:приписывать{}, // приписывать к достижениям rus_verbs:относить{}, // относить к растениям rus_verbs:принюхаться{}, // принюхаться к ароматам rus_verbs:подтащить{}, // подтащить к себе rus_verbs:прислонить{}, // прислонить к стене rus_verbs:подплыть{}, // подплыть к бую rus_verbs:опаздывать{}, // опаздывать к стилисту rus_verbs:примкнуть{}, // примкнуть к деомнстрантам rus_verbs:стекаться{}, // стекаются к стенам тюрьмы rus_verbs:подготовиться{}, // подготовиться к марафону rus_verbs:приглядываться{}, // приглядываться к новичку rus_verbs:присоединяться{}, // присоединяться к сообществу rus_verbs:клониться{}, // клониться ко сну rus_verbs:привыкать{}, // привыкать к хорошему rus_verbs:принудить{}, // принудить к миру rus_verbs:уплыть{}, // уплыть к далекому берегу rus_verbs:утащить{}, // утащить к детенышам rus_verbs:приплыть{}, // приплыть к финишу rus_verbs:подбегать{}, // подбегать к хозяину rus_verbs:лишаться{}, // лишаться средств к существованию rus_verbs:приступать{}, // приступать к операции rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике rus_verbs:подключить{}, // подключить к трубе rus_verbs:подключиться{}, // подключиться к сети rus_verbs:прилить{}, // прилить к лицу rus_verbs:стучаться{}, // стучаться к соседям rus_verbs:пристегнуть{}, // пристегнуть к креслу rus_verbs:присоединить{}, // присоединить к сети rus_verbs:отбежать{}, // отбежать к противоположной стене rus_verbs:подвезти{}, // подвезти к набережной rus_verbs:прибегнуть{}, // прибегнуть к хитрости rus_verbs:приучить{}, // приучить к туалету rus_verbs:подталкивать{}, // подталкивать к выходу rus_verbs:прорываться{}, // прорываться к выходу rus_verbs:увозить{}, // увозить к ветеринару rus_verbs:засеменить{}, // засеменить к выходу rus_verbs:крепиться{}, // крепиться к потолку rus_verbs:прибрать{}, // прибрать к рукам rus_verbs:пристраститься{}, // пристраститься к наркотикам rus_verbs:поспеть{}, // поспеть к обеду rus_verbs:привязывать{}, // привязывать к дереву rus_verbs:прилагать{}, // прилагать к документам rus_verbs:переправить{}, // переправить к дедушке rus_verbs:подогнать{}, // подогнать к воротам rus_verbs:тяготеть{}, // тяготеть к социализму rus_verbs:подбираться{}, // подбираться к оленю rus_verbs:подступать{}, // подступать к горлу rus_verbs:примыкать{}, // примыкать к первому элементу rus_verbs:приладить{}, // приладить к велосипеду rus_verbs:подбрасывать{}, // подбрасывать к потолку rus_verbs:перевозить{}, // перевозить к новому месту дислокации rus_verbs:усаживаться{}, // усаживаться к окну rus_verbs:приближать{}, // приближать к глазам rus_verbs:попроситься{}, // попроситься к бабушке rus_verbs:прибить{}, // прибить к доске rus_verbs:перетащить{}, // перетащить к себе rus_verbs:прицепить{}, // прицепить к паровозу rus_verbs:прикладывать{}, // прикладывать к ране rus_verbs:устареть{}, // устареть к началу войны rus_verbs:причалить{}, // причалить к пристани rus_verbs:приспособиться{}, // приспособиться к опозданиям rus_verbs:принуждать{}, // принуждать к миру rus_verbs:соваться{}, // соваться к директору rus_verbs:протолкаться{}, // протолкаться к прилавку rus_verbs:приковать{}, // приковать к батарее rus_verbs:подкрадываться{}, // подкрадываться к суслику rus_verbs:подсадить{}, // подсадить к арестонту rus_verbs:прикатить{}, // прикатить к финишу rus_verbs:протащить{}, // протащить к владыке rus_verbs:сужаться{}, // сужаться к основанию rus_verbs:присовокупить{}, // присовокупить к пожеланиям rus_verbs:пригвоздить{}, // пригвоздить к доске rus_verbs:отсылать{}, // отсылать к первоисточнику rus_verbs:изготовиться{}, // изготовиться к прыжку rus_verbs:прилагаться{}, // прилагаться к покупке rus_verbs:прицепиться{}, // прицепиться к вагону rus_verbs:примешиваться{}, // примешиваться к вину rus_verbs:переселить{}, // переселить к старшекурсникам rus_verbs:затрусить{}, // затрусить к выходе rus_verbs:приспособить{}, // приспособить к обогреву rus_verbs:примериться{}, // примериться к аппарату rus_verbs:прибавляться{}, // прибавляться к пенсии rus_verbs:подкатиться{}, // подкатиться к воротам rus_verbs:стягивать{}, // стягивать к границе rus_verbs:дописать{}, // дописать к роману rus_verbs:подпустить{}, // подпустить к корове rus_verbs:склонять{}, // склонять к сотрудничеству rus_verbs:припечатать{}, // припечатать к стене rus_verbs:охладеть{}, // охладеть к музыке rus_verbs:пришить{}, // пришить к шинели rus_verbs:принюхиваться{}, // принюхиваться к ветру rus_verbs:подрулить{}, // подрулить к барышне rus_verbs:наведаться{}, // наведаться к оракулу rus_verbs:клеиться{}, // клеиться к конверту rus_verbs:перетянуть{}, // перетянуть к себе rus_verbs:переметнуться{}, // переметнуться к конкурентам rus_verbs:липнуть{}, // липнуть к сокурсницам rus_verbs:поковырять{}, // поковырять к выходу rus_verbs:подпускать{}, // подпускать к пульту управления rus_verbs:присосаться{}, // присосаться к источнику rus_verbs:приклеить{}, // приклеить к стеклу rus_verbs:подтягивать{}, // подтягивать к себе rus_verbs:подкатывать{}, // подкатывать к даме rus_verbs:притрагиваться{}, // притрагиваться к опухоли rus_verbs:слетаться{}, // слетаться к водопою rus_verbs:хаживать{}, // хаживать к батюшке rus_verbs:привлекаться{}, // привлекаться к административной ответственности rus_verbs:подзывать{}, // подзывать к себе rus_verbs:прикладываться{}, // прикладываться к иконе rus_verbs:подтягиваться{}, // подтягиваться к парламенту rus_verbs:прилепить{}, // прилепить к стенке холодильника rus_verbs:пододвинуться{}, // пододвинуться к экрану rus_verbs:приползти{}, // приползти к дереву rus_verbs:запаздывать{}, // запаздывать к обеду rus_verbs:припереть{}, // припереть к стене rus_verbs:нагибаться{}, // нагибаться к цветку инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам деепричастие:сгоняв{}, rus_verbs:поковылять{}, // поковылять к выходу rus_verbs:привалить{}, // привалить к столбу rus_verbs:отпроситься{}, // отпроситься к родителям rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям rus_verbs:прилипать{}, // прилипать к рукам rus_verbs:подсоединить{}, // подсоединить к приборам rus_verbs:приливать{}, // приливать к голове rus_verbs:подселить{}, // подселить к другим новичкам rus_verbs:прилепиться{}, // прилепиться к шкуре rus_verbs:подлетать{}, // подлетать к пункту назначения rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг rus_verbs:льнуть{}, // льнуть к заботливому хозяину rus_verbs:привязываться{}, // привязываться к любящему хозяину rus_verbs:приклеиться{}, // приклеиться к спине rus_verbs:стягиваться{}, // стягиваться к сенату rus_verbs:подготавливать{}, // подготавливать к выходу на арену rus_verbs:приглашаться{}, // приглашаться к доктору rus_verbs:причислять{}, // причислять к отличникам rus_verbs:приколоть{}, // приколоть к лацкану rus_verbs:наклонять{}, // наклонять к горизонту rus_verbs:припадать{}, // припадать к первоисточнику rus_verbs:приобщиться{}, // приобщиться к культурному наследию rus_verbs:придираться{}, // придираться к мелким ошибкам rus_verbs:приучать{}, // приучать к лотку rus_verbs:промотать{}, // промотать к началу rus_verbs:прихлынуть{}, // прихлынуть к голове rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу rus_verbs:прикрутить{}, // прикрутить к велосипеду rus_verbs:подплывать{}, // подплывать к лодке rus_verbs:приравниваться{}, // приравниваться к побегу rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы rus_verbs:приткнуться{}, // приткнуться к первой группе туристов rus_verbs:приручить{}, // приручить котика к лотку rus_verbs:приковывать{}, // приковывать к себе все внимание прессы rus_verbs:приготовляться{}, // приготовляться к первому экзамену rus_verbs:остыть{}, // Вода остынет к утру. rus_verbs:приехать{}, // Он приедет к концу будущей недели. rus_verbs:подсаживаться{}, rus_verbs:успевать{}, // успевать к стилисту rus_verbs:привлекать{}, // привлекать к себе внимание прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму rus_verbs:прийтись{}, // прийтись ко двору инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы инфинитив:адаптироваться{вид:несоверш}, глагол:адаптироваться{вид:соверш}, глагол:адаптироваться{вид:несоверш}, деепричастие:адаптировавшись{}, деепричастие:адаптируясь{}, прилагательное:адаптировавшийся{вид:соверш}, //+прилагательное:адаптировавшийся{вид:несоверш}, прилагательное:адаптирующийся{}, rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей rus_verbs:близиться{}, // Шторм близится к побережью rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки rus_verbs:причислить{}, // Мы причислили его к числу экспертов rus_verbs:вести{}, // Наша партия ведет народ к процветанию rus_verbs:взывать{}, // Учителя взывают к совести хулигана rus_verbs:воззвать{}, // воззвать соплеменников к оружию rus_verbs:возревновать{}, // возревновать к поклонникам rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью rus_verbs:восходить{}, // восходить к вершине rus_verbs:восшествовать{}, // восшествовать к вершине rus_verbs:успеть{}, // успеть к обеду rus_verbs:повернуться{}, // повернуться к кому-то rus_verbs:обратиться{}, // обратиться к охраннику rus_verbs:звать{}, // звать к столу rus_verbs:отправиться{}, // отправиться к парикмахеру rus_verbs:обернуться{}, // обернуться к зовущему rus_verbs:явиться{}, // явиться к следователю rus_verbs:уехать{}, // уехать к родне rus_verbs:прибыть{}, // прибыть к перекличке rus_verbs:привыкнуть{}, // привыкнуть к голоду rus_verbs:уходить{}, // уходить к цыганам rus_verbs:привести{}, // привести к себе rus_verbs:шагнуть{}, // шагнуть к славе rus_verbs:относиться{}, // относиться к прежним периодам rus_verbs:подослать{}, // подослать к врагам rus_verbs:поспешить{}, // поспешить к обеду rus_verbs:зайти{}, // зайти к подруге rus_verbs:позвать{}, // позвать к себе rus_verbs:потянуться{}, // потянуться к рычагам rus_verbs:пускать{}, // пускать к себе rus_verbs:отвести{}, // отвести к врачу rus_verbs:приблизиться{}, // приблизиться к решению задачи rus_verbs:прижать{}, // прижать к стене rus_verbs:отправить{}, // отправить к доктору rus_verbs:падать{}, // падать к многолетним минимумам rus_verbs:полезть{}, // полезть к дерущимся rus_verbs:лезть{}, // Ты сама ко мне лезла! rus_verbs:направить{}, // направить к майору rus_verbs:приводить{}, // приводить к дантисту rus_verbs:кинуться{}, // кинуться к двери rus_verbs:поднести{}, // поднести к глазам rus_verbs:подниматься{}, // подниматься к себе rus_verbs:прибавить{}, // прибавить к результату rus_verbs:зашагать{}, // зашагать к выходу rus_verbs:склониться{}, // склониться к земле rus_verbs:стремиться{}, // стремиться к вершине rus_verbs:лететь{}, // лететь к родственникам rus_verbs:ездить{}, // ездить к любовнице rus_verbs:приближаться{}, // приближаться к финише rus_verbs:помчаться{}, // помчаться к стоматологу rus_verbs:прислушаться{}, // прислушаться к происходящему rus_verbs:изменить{}, // изменить к лучшему собственную жизнь rus_verbs:проявить{}, // проявить к погибшим сострадание rus_verbs:подбежать{}, // подбежать к упавшему rus_verbs:терять{}, // терять к партнерам доверие rus_verbs:пропустить{}, // пропустить к певцу rus_verbs:подвести{}, // подвести к глазам rus_verbs:меняться{}, // меняться к лучшему rus_verbs:заходить{}, // заходить к другу rus_verbs:рвануться{}, // рвануться к воде rus_verbs:привлечь{}, // привлечь к себе внимание rus_verbs:присоединиться{}, // присоединиться к сети rus_verbs:приезжать{}, // приезжать к дедушке rus_verbs:дернуться{}, // дернуться к борту rus_verbs:подъехать{}, // подъехать к воротам rus_verbs:готовиться{}, // готовиться к дождю rus_verbs:убежать{}, // убежать к маме rus_verbs:поднимать{}, // поднимать к источнику сигнала rus_verbs:отослать{}, // отослать к руководителю rus_verbs:приготовиться{}, // приготовиться к худшему rus_verbs:приступить{}, // приступить к выполнению обязанностей rus_verbs:метнуться{}, // метнуться к фонтану rus_verbs:прислушиваться{}, // прислушиваться к голосу разума rus_verbs:побрести{}, // побрести к выходу rus_verbs:мчаться{}, // мчаться к успеху rus_verbs:нестись{}, // нестись к обрыву rus_verbs:попадать{}, // попадать к хорошему костоправу rus_verbs:опоздать{}, // опоздать к психотерапевту rus_verbs:посылать{}, // посылать к доктору rus_verbs:поплыть{}, // поплыть к берегу rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе rus_verbs:отнести{}, // отнести животное к ветеринару rus_verbs:прислониться{}, // прислониться к стволу rus_verbs:наклонить{}, // наклонить к миске с молоком rus_verbs:прикоснуться{}, // прикоснуться к поверхности rus_verbs:увезти{}, // увезти к бабушке rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия rus_verbs:подозвать{}, // подозвать к себе rus_verbs:улететь{}, // улететь к теплым берегам rus_verbs:ложиться{}, // ложиться к мужу rus_verbs:убираться{}, // убираться к чертовой бабушке rus_verbs:класть{}, // класть к другим документам rus_verbs:доставлять{}, // доставлять к подъезду rus_verbs:поворачиваться{}, // поворачиваться к источнику шума rus_verbs:заглядывать{}, // заглядывать к любовнице rus_verbs:занести{}, // занести к заказчикам rus_verbs:прибежать{}, // прибежать к папе rus_verbs:притянуть{}, // притянуть к причалу rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму rus_verbs:подать{}, // он подал лимузин к подъезду rus_verbs:подавать{}, // она подавала соус к мясу rus_verbs:приобщаться{}, // приобщаться к культуре прилагательное:неспособный{}, // Наша дочка неспособна к учению. прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару прилагательное:предназначенный{}, // Старый дом предназначен к сносу. прилагательное:внимательный{}, // Она всегда внимательна к гостям. прилагательное:назначенный{}, // Дело назначено к докладу. прилагательное:разрешенный{}, // Эта книга разрешена к печати. прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам. прилагательное:готовый{}, // Я готов к экзаменам. прилагательное:требовательный{}, // Он очень требователен к себе. прилагательное:жадный{}, // Он жаден к деньгам. прилагательное:глухой{}, // Он глух к моей просьбе. прилагательное:добрый{}, // Он добр к детям. rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам. rus_verbs:плыть{}, // Пароход плыл к берегу. rus_verbs:пойти{}, // я пошел к доктору rus_verbs:придти{}, // придти к выводу rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом. rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений. rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам. rus_verbs:спускаться{}, // Улица круто спускается к реке. rus_verbs:спуститься{}, // Мы спустились к реке. rus_verbs:пустить{}, // пускать ко дну rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью! rus_verbs:отойти{}, // Дом отошёл к племяннику. rus_verbs:отходить{}, // Коля отходил ко сну. rus_verbs:приходить{}, // местные жители к нему приходили лечиться rus_verbs:кидаться{}, // не кидайся к столу rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу. rus_verbs:закончиться{}, // Собрание закончилось к вечеру. rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему. rus_verbs:направиться{}, // Мы сошли на берег и направились к городу. rus_verbs:направляться{}, rus_verbs:свестись{}, // Всё свелось к нулю. rus_verbs:прислать{}, // Пришлите кого-нибудь к ней. rus_verbs:присылать{}, // Он присылал к должнику своих головорезов rus_verbs:подлететь{}, // Самолёт подлетел к лесу. rus_verbs:возвращаться{}, // он возвращается к старой работе глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{}, прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая. rus_verbs:возвращать{}, // возвращать к жизни rus_verbs:располагать{}, // Атмосфера располагает к работе. rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому. rus_verbs:поступить{}, // К нам поступила жалоба. rus_verbs:поступать{}, // К нам поступают жалобы. rus_verbs:прыгнуть{}, // Белка прыгнула к дереву rus_verbs:торопиться{}, // пассажиры торопятся к выходу rus_verbs:поторопиться{}, // поторопитесь к выходу rus_verbs:вернуть{}, // вернуть к активной жизни rus_verbs:припирать{}, // припирать к стенке rus_verbs:проваливать{}, // Проваливай ко всем чертям! rus_verbs:вбежать{}, // Коля вбежал ко мне rus_verbs:вбегать{}, // Коля вбегал ко мне глагол:забегать{ вид:несоверш }, // Коля забегал ко мне rus_verbs:постучаться{}, // Коля постучался ко мне. rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому rus_verbs:понести{}, // Мы понесли кота к ветеринару rus_verbs:принести{}, // Я принес кота к ветеринару rus_verbs:устремиться{}, // Мы устремились к ручью. rus_verbs:подводить{}, // Учитель подводил детей к аквариуму rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения. rus_verbs:пригласить{}, // Я пригласил к себе товарищей. rus_verbs:собираться{}, // Я собираюсь к тебе в гости. rus_verbs:собраться{}, // Маша собралась к дантисту rus_verbs:сходить{}, // Я схожу к врачу. rus_verbs:идти{}, // Маша уверенно шла к Пете rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию. rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию. rus_verbs:заканчивать{}, // Заканчивайте к обеду rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время rus_verbs:окончить{}, // rus_verbs:дозвониться{}, // Я не мог к вам дозвониться. глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор rus_verbs:уйти{}, // Антонио ушел к Элеонор rus_verbs:бежать{}, // Антонио бежит к Элеонор rus_verbs:спешить{}, // Антонио спешит к Элеонор rus_verbs:скакать{}, // Антонио скачет к Элеонор rus_verbs:красться{}, // Антонио крадётся к Элеонор rus_verbs:поскакать{}, // беглецы поскакали к холмам rus_verbs:перейти{} // Антонио перешел к Элеонор } fact гл_предл { if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } } then return true } fact гл_предл { if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:к{} *:*{} } then return false,-5 } #endregion Предлог_К #region Предлог_ДЛЯ // ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ---------------------- wordentry_set Гл_ДЛЯ_Род={ частица:нет{}, // для меня нет других путей. частица:нету{}, rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ) rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ) rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться) rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ) rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ) rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ) rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ) rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ) rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ) rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ) rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ) rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ) rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ) rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ) rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ) rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ) rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ) rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ) rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ) rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ) rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ) rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ) rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ) rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ) rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ) rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ) rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ) rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ) rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ) прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ) rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ) rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ) rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ) rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ) rus_verbs:оставить{}, // или вообще решили оставить планету для себя rus_verbs:оставлять{}, rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ) rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ) rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ) rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ) rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ) rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ) rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ) rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ) rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ) rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для) rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ) rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ) rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ) rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ) rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ) прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ) прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ) прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ) rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ) rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ) rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ) rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ) rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ) rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ) rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ) rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ) rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ) rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ) rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ) rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ) прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ) rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ) rus_verbs:вывести{}, // мы специально вывели этих животных для мяса. rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ) rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для) rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ) rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ) rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ) rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ) rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ) rus_verbs:найтись{}, // у вас найдется для него работа? rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для) rus_verbs:заехать{}, // Коля заехал для обсуждения проекта rus_verbs:созреть{}, // созреть для побега rus_verbs:наметить{}, // наметить для проверки rus_verbs:уяснить{}, // уяснить для себя rus_verbs:нанимать{}, // нанимать для разовой работы rus_verbs:приспособить{}, // приспособить для удовольствия rus_verbs:облюбовать{}, // облюбовать для посиделок rus_verbs:прояснить{}, // прояснить для себя rus_verbs:задействовать{}, // задействовать для патрулирования rus_verbs:приготовлять{}, // приготовлять для проверки инфинитив:использовать{ вид:соверш }, // использовать для достижения цели инфинитив:использовать{ вид:несоверш }, глагол:использовать{ вид:соверш }, глагол:использовать{ вид:несоверш }, прилагательное:использованный{}, деепричастие:используя{}, деепричастие:использовав{}, rus_verbs:напрячься{}, // напрячься для решительного рывка rus_verbs:одобрить{}, // одобрить для использования rus_verbs:одобрять{}, // одобрять для использования rus_verbs:пригодиться{}, // пригодиться для тестирования rus_verbs:готовить{}, // готовить для выхода в свет rus_verbs:отобрать{}, // отобрать для участия в конкурсе rus_verbs:потребоваться{}, // потребоваться для подтверждения rus_verbs:пояснить{}, // пояснить для слушателей rus_verbs:пояснять{}, // пояснить для экзаменаторов rus_verbs:понадобиться{}, // понадобиться для обоснования инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера инфинитив:адаптировать{вид:соверш}, глагол:адаптировать{вид:несоверш}, глагол:адаптировать{вид:соверш}, деепричастие:адаптировав{}, деепричастие:адаптируя{}, прилагательное:адаптирующий{}, прилагательное:адаптировавший{ вид:соверш }, //+прилагательное:адаптировавший{ вид:несоверш }, прилагательное:адаптированный{}, rus_verbs:найти{}, // Папа нашел для детей няню прилагательное:вредный{}, // Это вредно для здоровья. прилагательное:полезный{}, // Прогулки полезны для здоровья. прилагательное:обязательный{}, // Этот пункт обязателен для исполнения прилагательное:бесполезный{}, // Это лекарство бесполезно для него прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления rus_verbs:создать{}, // Он не создан для этого дела. прилагательное:сложный{}, // задача сложна для младших школьников прилагательное:несложный{}, прилагательное:лёгкий{}, прилагательное:сложноватый{}, rus_verbs:становиться{}, rus_verbs:представлять{}, // Это не представляет для меня интереса. rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка rus_verbs:пройти{}, // День прошёл спокойно для него. rus_verbs:проходить{}, rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ rus_verbs:высаживаться{}, rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца. rus_verbs:прибавить{}, rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов. rus_verbs:составлять{}, rus_verbs:стараться{}, // Я старался для вас rus_verbs:постараться{}, // Я постарался для вас rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста. rus_verbs:собраться{}, // собраться для обсуждения rus_verbs:собираться{}, // собираться для обсуждения rus_verbs:уполномочивать{}, rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров rus_verbs:принести{}, // Я принёс эту книгу для вас. rus_verbs:делать{}, // Я это делаю для удовольствия. rus_verbs:сделать{}, // Я сделаю это для удовольствия. rus_verbs:подготовить{}, // я подготовил для друзей сюрприз rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села rus_verbs:прибыть{} // они прибыли для участия } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } } then return true } fact гл_предл { if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") } then return true } // для остальных падежей запрещаем. fact гл_предл { if context { * предлог:для{} *:*{} } then return false,-4 } #endregion Предлог_ДЛЯ #region Предлог_ОТ // попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_ОТ_Род_Запр= { rus_verbs:наслаждаться{}, // свободой от обязательств rus_verbs:насладиться{}, rus_verbs:мочь{}, // Он не мог удержаться от смеха. // rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:чувствовать{}, // все время от времени чувствуют его. rus_verbs:планировать{}, rus_verbs:приняться{} // мы принялись обниматься от радости. } fact гл_предл { if context { Глаг_ОТ_Род_Запр предлог:от{} * } then return false } #endregion Предлог_ОТ #region Предлог_БЕЗ /* // запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных. wordentry_set Глаг_БЕЗ_Род_Запр= { rus_verbs:мочь{}, // Он мог читать часами без отдыха. rus_verbs:хотеть{}, rus_verbs:желать{}, rus_verbs:планировать{}, rus_verbs:приняться{} } fact гл_предл { if context { Глаг_БЕЗ_Род_Запр предлог:без{} * } then return false } */ #endregion Предлог_БЕЗ #region Предлог_КРОМЕ fact гл_предл { if context { * ПредлогДляВсе * } then return false,-5 } #endregion Предлог_КРОМЕ // ------------------------------------ // По умолчанию разрешаем все остальные сочетания. fact гл_предл { if context { * * * } then return true }
ткань выгорела на солнце
rus_verbs:выгореть{},
5,485,024
[ 1, 146, 229, 145, 123, 145, 113, 145, 126, 146, 239, 225, 145, 115, 146, 238, 145, 116, 145, 127, 146, 227, 145, 118, 145, 124, 145, 113, 225, 145, 126, 145, 113, 225, 146, 228, 145, 127, 145, 124, 145, 126, 146, 233, 145, 118, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 8010, 67, 502, 2038, 30, 145, 115, 146, 238, 145, 116, 145, 127, 146, 227, 145, 118, 146, 229, 146, 239, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x508efB44A06a64Bd4020e8c5e8Ecf1A9236C75aE/sources/tokenWhitelist.sol
@notice keeping track of how many redeemable tokens are in the tokenWhitelist
uint256 private _redeemableCounter;
3,597,976
[ 1, 10102, 310, 3298, 434, 3661, 4906, 283, 24903, 429, 2430, 854, 316, 326, 1147, 18927, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 389, 266, 24903, 429, 4789, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x2427F0f1B842665d9FB9f0d8Ca347E044Ef5F15a/sources/contracts/GardensTemplate.sol
8 times within price period, once every 3 hours
uint8 public constant UPDATE_FREQUENCY = 8;
8,714,693
[ 1, 28, 4124, 3470, 6205, 3879, 16, 3647, 3614, 890, 7507, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 28, 1071, 5381, 11028, 67, 42, 862, 3500, 26325, 273, 1725, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23;/* _ _____ ___ _ _ __ ` __ ___ ___ _ _ ,&#39; `. __ ____ /__ ,&#39; `. __ __ / ,&#39; `.__ _ /_,&#39; `. _ /,&#39; `./&#39; ,/`. ,&#39;/ __`. ,&#39;_/_ _ _`. ,&#39;__/_ ___ _ `. ,&#39;_ /___ __ _ __ `. &#39;-.._/____ _ __ _`. PyrConnect Decentralized Securities Licensing */ contract PeerLicensing{ // scaleFactor is used to convert Ether into tokens and vice-versa: they&#39;re of different // orders of magnitude, hence the need to bridge between the two. uint256 constant scaleFactor = 0x10000000000000000;// 2^64 // CRR = 50% // CRR is Cash Reserve Ratio (in this case Crypto Reserve Ratio). // For more on this: check out https://en.wikipedia.org/wiki/Reserve_requirement uint256 constant trickTax = 3;//divides flux&#39;d fee and for every pass up int constant crr_n = 1; // CRR numerator int constant crr_d = 2; // CRR denominator int constant price_coeff = 0x57ea9ce452cde449f; // Array between each address and their number of tokens. mapping(address => uint256) public holdings; //cut down by a percentage when you sell out. mapping(address => uint256) public avgFactor_ethSpent; mapping(address => uint256) public souleculeR; mapping(address => uint256) public souleculeG; mapping(address => uint256) public souleculeB; // Array between each address and how much Ether has been paid out to it. // Note that this is scaled by the scaleFactor variable. mapping(address => address) public reff; mapping(address => uint256) public tricklingFlo; mapping(address => uint256) public pocket; mapping(address => int256) public payouts; // Variable tracking how many tokens are in existence overall. uint256 public totalBondSupply; // Aggregate sum of all payouts. // Note that this is scaled by the scaleFactor variable. int256 totalPayouts; uint256 public trickleSum; uint256 public stakingRequirement = 1e18; address public lastGateway; //flux fee ratio and contract score keepers uint256 public withdrawSum; uint256 public investSum; // Variable tracking how much Ether each token is currently worth. // Note that this is scaled by the scaleFactor variable. uint256 earningsPerBond; constructor() public {} event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onBoughtFor( address indexed buyerAddress, address indexed forWho, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 totalTokensAtTheTime,//maybe it&#39;d be cool to see what % people are selling from their total bank uint256 tokensBurned, uint256 ethereumEarned, uint256 resolved ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event onCashDividends( address indexed customerAddress, uint256 ethereumWithdrawn ); event onColor( address indexed customerAddress, uint256 oldR, uint256 oldG, uint256 oldB, uint256 newR, uint256 newG, uint256 newB ); // The following functions are used by the front-end for display purposes. // Returns the number of tokens currently held by _owner. function holdingsOf(address _owner) public constant returns (uint256 balance) { return holdings[_owner]; } // Withdraws all dividends held by the caller sending the transaction, updates // the requisite global variables, and transfers Ether back to the caller. function withdraw(address to) public { trickleUp(); // Retrieve the dividends associated with the address the request came from. uint256 balance = dividends(msg.sender); //uint256 pocketBalance = tricklePocket[msg.sender]; //tricklePocket[msg.sender] = 0; // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that&#39;s been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); uint256 pocketETH = pocket[msg.sender]; pocket[msg.sender] = 0; trickleSum -= pocketETH; balance += pocketETH; // Send the dividends to the address that requested the withdraw. withdrawSum += balance; to.transfer(balance); emit onCashDividends(to,balance); } function fullCycleSellBonds(uint256 balance) internal { // Send the cashed out stake to the address that requested the withdraw. withdrawSum += balance; msg.sender.transfer(balance); emit onWithdraw(msg.sender, balance); } // Sells your tokens for Ether. This Ether is assigned to the callers entry // in the tokenBalance array, and therefore is shown as a dividend. A second // call to withdraw() must be made to invoke the transfer of Ether back to your address. function sellBonds(uint256 _amount) public { uint256 bondBalance = holdings[msg.sender]; if(_amount <= bondBalance && _amount > 0){ sell(_amount); }else{ sell(bondBalance); } } // The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately // invokes the withdraw() function, sending the resulting Ether to the callers address. function getMeOutOfHere() public { sellBonds( holdings[msg.sender] ); withdraw(msg.sender); } function reffUp(address _reff) internal{ address sender = msg.sender; if (_reff == 0x0000000000000000000000000000000000000000 || _reff == msg.sender) _reff = lastGateway; if( holdings[_reff] >= stakingRequirement ) { //good to go. good gateway }else{ if(lastGateway == 0x0000000000000000000000000000000000000000){ lastGateway = sender;//first buyer ever _reff = sender;//first buyer is their own gateway/masternode } else _reff = lastGateway;//the lucky last player gets to be the gate way. } reff[sender] = _reff; } function rgbLimit(uint256 _rgb)internal pure returns(uint256){ if(_rgb > 255) return 255; else return _rgb; } //BONUS //when you don&#39;t pick a color, the contract will need a default. which will be your current color /*function edgePigmentR()internal view returns (uint256 x) {if(holdings[msg.sender]==0)return 0;else return 255 * souleculeR[msg.sender]/holdings[msg.sender];} function edgePigmentG()internal view returns (uint256 x) {if(holdings[msg.sender]==0)return 0;else return 255 * souleculeG[msg.sender]/holdings[msg.sender];} function edgePigmentB()internal view returns (uint256 x) {if(holdings[msg.sender]==0)return 0;else return 255 * souleculeB[msg.sender]/holdings[msg.sender];}*/ function edgePigment(uint8 C)internal view returns (uint256 x) { uint256 holding = holdings[msg.sender]; if(holding==0) return 0; else{ if(C==0){ return 255 * souleculeR[msg.sender]/holding; }else if(C==1){ return 255 * souleculeG[msg.sender]/holding; }else if(C==2){ return 255 * souleculeB[msg.sender]/holding; } } } function fund(address reffo, address forWho) payable public { fund_color( reffo, forWho, edgePigment(0),edgePigment(1),edgePigment(2) ); } function fund_color( address _reff, address forWho,uint256 soulR,uint256 soulG,uint256 soulB) payable public { // Don&#39;t allow for funding if the amount of Ether sent is less than 1 szabo. reffUp(_reff); if (msg.value > 0.000001 ether){ investSum += msg.value; soulR=rgbLimit(soulR); soulG=rgbLimit(soulG); soulB=rgbLimit(soulB); buy( forWho ,soulR,soulG,soulB); lastGateway = msg.sender; } else { revert(); } } function reinvest_color(uint256 soulR,uint256 soulG,uint256 soulB) public { soulR=rgbLimit(soulR); soulG=rgbLimit(soulG); soulB=rgbLimit(soulB); processReinvest( soulR,soulG,soulB); } function reinvest() public { processReinvest( edgePigment(0),edgePigment(1),edgePigment(2) ); } // Function that returns the (dynamic) price of a single token. function price(bool buyOrSell) public constant returns (uint) { if(buyOrSell){ return getTokensForEther(1 finney); }else{ uint256 eth = getEtherForTokens(1 finney); uint256 fee = fluxFeed(eth, false, false); return eth - fee; } } function fluxFeed(uint256 _eth, bool slim_reinvest,bool buyOrSell) public constant returns (uint256 amount) { uint8 bonus; if(slim_reinvest){ bonus = 3; /* For the ecosystem: Reinvest discount = FluxFee * resolveGroupWithdrawnChoiceSum / ( resolveGroupWithdrawnChoiceSum + resolveGroupReinvestChoiceSum ) The reinvest discounted price is equal to the flux&#39;d fee multiplied by the sum of ETH chosen to be withdrawn from the pyramid&#39;s resolve type divided by the sum of BOTH ETH chosen to be withdrawn AND chosen to be reinvested in the same type. This means that the more your community reinvests in another, the better your reinvest deal. */ }else{ bonus = 1; } if(buyOrSell) return _eth/bonus * withdrawSum/(investSum);//we&#39;ve already added it in. else return _eth/bonus * (withdrawSum + _eth)/investSum; //gotta multiply and stuff in that order in order to get a high precision taxed amount. //because grouping (withdrawSum / investSum) can&#39;t return a precise decimal. //so instead we expand the value by multiplying then shrink it. by the denominator /* 100eth IN & 100eth OUT = 100% tax fee (returning 1) !!! 100eth IN & 50eth OUT = 50% tax fee (returning 2) 100eth IN & 33eth OUT = 33% tax fee (returning 3) 100eth IN & 25eth OUT = 25% tax fee (returning 4) 100eth IN & 10eth OUT = 10% tax fee (returning 10) !!! keep in mind there is no fee if there are no holders. So if 100% of the eth has left the contract that means there can&#39;t possibly be holders to tax you. Funny how that works. The flux fee also forces communities to help eachother more and more if the value drops. */ } // Calculate the current dividends associated with the caller address. This is the net result // of multiplying the number of tokens held by their current value in Ether and subtracting the // Ether that has already been paid out. function dividends(address _owner) public constant returns (uint256 amount) { return (uint256) ((int256)( earningsPerBond * holdings[_owner] ) - payouts[_owner] ) / scaleFactor; } function cashWallet(address _owner) public constant returns (uint256 amount) { return dividends(_owner)+pocket[_owner]; } // Internal balance function, used to calculate the dynamic reserve value. function contractBalance() internal constant returns (uint256 amount){ // msg.value is the amount of Ether sent by the transaction. return investSum - withdrawSum - msg.value - trickleSum; } function trickleUp() internal{ uint256 tricks = tricklingFlo[ msg.sender ];//this is the amount moving in the trickle flo if(tricks > 0){ tricklingFlo[ msg.sender ] = 0;//we&#39;ve already captured the amount so set your tricklingFlo flo to 0 uint256 passUp = tricks/trickTax;//to get the amount we&#39;re gonna pass up. divide by trickTax uint256 reward = tricks-passUp;//and our remaining reward for ourselves is the amount we just slice off subtracted from the flo address finalReff;//we&#39;re not exactly sure who we&#39;re gonna pass this up to yet address reffo = reff[msg.sender];//this is who it should go up to. if everything is legit if( holdings[reffo] >= stakingRequirement){ finalReff = reffo;//if that address is holding enough to stake, it&#39;s a legit node to flo up to. }else{ finalReff = lastGateway;//if not, then we use the last buyer } tricklingFlo[ finalReff ] += passUp;//so now we add that flo you&#39;ve passed up to the tricklingFlo of the final Reff pocket[ msg.sender ] += reward;// oh yeah... and that reward... I gotchu } } function buy(address forWho,uint256 soulR,uint256 soulG,uint256 soulB) internal { // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it. if (msg.value < 0.000001 ether || msg.value > 1000000 ether) revert(); //Fee to pay existing holders, and the referral commission uint256 fee = 0; uint256 trickle = 0; if(holdings[forWho] != totalBondSupply){ fee = fluxFeed(msg.value,false,true); trickle = fee/trickTax; fee = fee - trickle; tricklingFlo[forWho] += trickle; } uint256 numEther = msg.value - (fee+trickle);// The amount of Ether used to purchase new tokens for the caller. uint256 numTokens = getTokensForEther(numEther);// The number of tokens which can be purchased for numEther. buyCalcAndPayout( forWho, fee, numTokens, numEther, reserve() ); addPigment(numTokens,soulR,soulG,soulB); trickleSum += trickle;//add to trickle&#39;s Sum after reserve calculations trickleUp(); emit onTokenPurchase(forWho, numEther ,numTokens , reff[msg.sender]); if(forWho != msg.sender){//make sure you&#39;re not yourself //if forWho doesn&#39;t have a reff, then reset it if(reff[forWho] == 0x0000000000000000000000000000000000000000) {reff[forWho] = msg.sender;} emit onBoughtFor(msg.sender, forWho,numEther,numTokens,reff[msg.sender]); } } function buyCalcAndPayout(address forWho,uint256 fee,uint256 numTokens,uint256 numEther,uint256 res)internal{ // The buyer fee, scaled by the scaleFactor variable. uint256 buyerFee = fee * scaleFactor; if (totalBondSupply > 0){// because ... // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. uint256 bonusCoEff = (scaleFactor - (res + numEther) * numTokens * scaleFactor / ( totalBondSupply + numTokens) / numEther) *(uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. uint256 holderReward = fee * bonusCoEff; buyerFee -= holderReward; // The Ether value per token is increased proportionally. earningsPerBond += holderReward / totalBondSupply; } //resolve reward tracking stuff avgFactor_ethSpent[forWho] += numEther; // Add the numTokens which were just created to the total supply. We&#39;re a crypto central bank! totalBondSupply += numTokens; // Assign the tokens to the balance of the buyer. holdings[forWho] += numTokens; // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... int256 payoutDiff = (int256) ((earningsPerBond * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[forWho] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } // Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee // to discouraging dumping, and means that if someone near the top sells, the fee distributed // will be *significant*. function TOKEN_scaleDown(uint256 value,uint256 reduce) internal view returns(uint256 x){ uint256 holdingsOfSender = holdings[msg.sender]; return value * ( holdingsOfSender - reduce) / holdingsOfSender; } function sell(uint256 amount) internal { uint256 numEthersBeforeFee = getEtherForTokens(amount); // x% of the resulting Ether is used to pay remaining holders. uint256 fee = 0; uint256 trickle = 0; if(totalBondSupply != holdings[msg.sender]){ fee = fluxFeed(numEthersBeforeFee, false,false); trickle = fee/ trickTax; fee -= trickle; tricklingFlo[msg.sender] +=trickle; } // Net Ether for the seller after the fee has been subtracted. uint256 numEthers = numEthersBeforeFee - (fee+trickle); //How much you bought it for divided by how much you&#39;re getting back. //This means that if you get dumped on, you can get more resolve tokens if you sell out. uint256 resolved = mint( calcResolve(msg.sender,amount,numEthersBeforeFee), msg.sender ); // *Remove* the numTokens which were just sold from the total supply. avgFactor_ethSpent[msg.sender] = TOKEN_scaleDown(avgFactor_ethSpent[msg.sender] , amount); souleculeR[msg.sender] = TOKEN_scaleDown(souleculeR[msg.sender] , amount); souleculeG[msg.sender] = TOKEN_scaleDown(souleculeG[msg.sender] , amount); souleculeB[msg.sender] = TOKEN_scaleDown(souleculeB[msg.sender] , amount); totalBondSupply -= amount; // Remove the tokens from the balance of the buyer. holdings[msg.sender] -= amount; int256 payoutDiff = (int256) (earningsPerBond * amount);//we don&#39;t add in numETH because it is immedietly paid out. // We reduce the amount paid out to the seller (this effectively resets their payouts value to zero, // since they&#39;re selling all of their tokens). This makes sure the seller isn&#39;t disadvantaged if // they decide to buy back in. payouts[msg.sender] -= payoutDiff; // Decrease the total amount that&#39;s been paid out to maintain invariance. totalPayouts -= payoutDiff; // Check that we have tokens in existence (this is a bit of an irrelevant check since we&#39;re // selling tokens, but it guards against division by zero). if (totalBondSupply > 0) { // Scale the Ether taken as the selling fee by the scaleFactor variable. uint256 etherFee = fee * scaleFactor; // Fee is distributed to all remaining token holders. // rewardPerShare is the amount gained per token thanks to this sell. uint256 rewardPerShare = etherFee / totalBondSupply; // The Ether value per token is increased proportionally. earningsPerBond += rewardPerShare; } fullCycleSellBonds(numEthers); trickleSum += trickle; trickleUp(); emit onTokenSell(msg.sender,holdings[msg.sender]+amount,amount,numEthers,resolved); } // Converts the Ether accrued as dividends back into Staking tokens without having to // withdraw it first. Saves on gas and potential price spike loss. function processReinvest(uint256 soulR,uint256 soulG,uint256 soulB) internal{ // Retrieve the dividends associated with the address the request came from. uint256 balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. // Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that&#39;s been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Assign balance to a new variable. uint256 pocketETH = pocket[msg.sender]; uint value_ = (uint) (balance + pocketETH); pocket[msg.sender] = 0; // If your dividends are worth less than 1 szabo, or more than a million Ether // (in which case, why are you even here), abort. if (value_ < 0.000001 ether || value_ > 1000000 ether) revert(); uint256 fee = 0; uint256 trickle = 0; if(holdings[msg.sender] != totalBondSupply){ fee = fluxFeed(value_, true,true );// reinvestment fees are lower than regular ones. trickle = fee/ trickTax; fee = fee - trickle; tricklingFlo[msg.sender] += trickle; } // A temporary reserve variable used for calculating the reward the holder gets for buying tokens. // (Yes, the buyer receives a part of the distribution as well!) uint256 res = reserve() - balance; // The amount of Ether used to purchase new tokens for the caller. uint256 numEther = value_ - (fee+trickle); // The number of tokens which can be purchased for numEther. uint256 numTokens = calculateDividendTokens(numEther, balance); buyCalcAndPayout( msg.sender, fee, numTokens, numEther, res ); addPigment(numTokens,soulR,soulG,soulB); trickleUp(); //trickleSum -= pocketETH; trickleSum += trickle - pocketETH; emit onReinvestment(msg.sender,numEther,numTokens); if(msg.sender != msg.sender){//make sure you&#39;re not yourself //if forWho doesn&#39;t have a reff, then reset it if(reff[msg.sender] == 0x0000000000000000000000000000000000000000) {reff[msg.sender] = msg.sender;} emit onBoughtFor(msg.sender, msg.sender,numEther,numTokens,reff[msg.sender]); } } function addPigment(uint256 tokens,uint256 r,uint256 g,uint256 b) internal{ souleculeR[msg.sender] += tokens * r / 255; souleculeG[msg.sender] += tokens * g / 255; souleculeB[msg.sender] += tokens * b / 255; emit onColor(msg.sender,r,g,b,souleculeR[msg.sender] ,souleculeG[msg.sender] ,souleculeB[msg.sender] ); } // Dynamic value of Ether in reserve, according to the CRR requirement. function reserve() internal constant returns (uint256 amount){ return contractBalance()-((uint256) ((int256) (earningsPerBond * totalBondSupply) - totalPayouts ) / scaleFactor); } // Calculates the number of tokens that can be bought for a given amount of Ether, according to the // dynamic reserve and totalSupply values (derived from the buy and sell prices). function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) { return fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff) - totalBondSupply ; } // Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion. function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) { return fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff) - totalBondSupply; } // Converts a number tokens into an Ether value. function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) { // How much reserve Ether do we have left in the contract? uint256 reserveAmount = reserve(); // If you&#39;re the Highlander (or bagholder), you get The Prize. Everything left in the vault. if (tokens == totalBondSupply ) return reserveAmount; // If there would be excess Ether left after the transaction this is called within, return the Ether // corresponding to the equation in Dr Jochen Hoenicke&#39;s original Ponzi paper, which can be found // at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator // and denominator altered to 1 and 2 respectively. return reserveAmount - fixedExp((fixedLog(totalBondSupply - tokens) - price_coeff) * crr_d/crr_n); } function () payable public { if (msg.value > 0) { fund(lastGateway,msg.sender); } else { withdraw(msg.sender); } } address public resolver = this; uint256 public totalSupply; uint256 public totalBurned; uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => uint256) public burned; mapping (address => mapping (address => uint256)) public allowed; string public name = "0xBabylon";//yes, this is still the CODE name uint8 public decimals = 18; string public symbol = "PoWHr";//PoWHr Brokers event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Resolved(address indexed _owner, uint256 amount); event Burned(address indexed _owner, uint256 amount); function mint(uint256 amount,address _account) internal returns (uint minted){ totalSupply += amount; balances[_account] += amount; emit Resolved(_account,amount); return amount; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]-burned[_owner]; } function burn(uint256 _value) public returns (uint256 amount) { require( balanceOf(msg.sender) >= _value); totalBurned += _value; burned[msg.sender] += _value; emit Burned(msg.sender,_value); return _value; } function calcResolve(address _owner,uint256 amount,uint256 _eth) public constant returns (uint256 calculatedResolveTokens) { return amount*amount*avgFactor_ethSpent[_owner]/holdings[_owner]/_eth; } function transfer(address _to, uint256 _value) public returns (bool success) { require( balanceOf(msg.sender) >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){ uint256 allowance = allowed[_from][msg.sender]; require( balanceOf(_from) >= _value && allowance >= _value ); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function resolveSupply() public view returns (uint256 balance) { return totalSupply-totalBurned; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } // You don&#39;t care about these, but if you really do they&#39;re hex values for // co-efficients used to simulate approximations of the log and exp functions. int256 constant one = 0x10000000000000000; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f; // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 // approximates the function log(1+x)-log(1-x) // Hence R(s) = log((1+s)/(1-s)) = log(a) function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); int256 z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); } int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; // The polynomial R = 2 + c2*x^2 + c4*x^4 + ... // approximates the function x*(exp(x)+1)/(exp(x)-1) // Hence exp(x) = (R(x)+x)/(R(x)-x) function fixedExp(int256 a) internal pure returns (uint256 exp) { int256 scale = (a + (ln2_64dot5)) / ln2 - 64; a -= scale*ln2; int256 z = (a*a) / one; int256 R = ((int256)(2) * one) + (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one); exp = (uint256) (((R + a) * one) / (R - a)); if (scale >= 0) exp <<= scale; else exp >>= -scale; return exp; } }
trickleSum -= pocketETH;
trickleSum += trickle - pocketETH;
2,346,628
[ 1, 313, 1200, 298, 3495, 3947, 293, 1861, 1584, 44, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 6862, 202, 313, 1200, 298, 3495, 1011, 28837, 298, 300, 293, 1861, 1584, 44, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /* * @dev Provides information about the current execution context. * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); 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. * * 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. * 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. */ 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. */ 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. */ 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`]. * */ 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; 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() internal 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; } } /** * @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. * * 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 Ownable, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _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; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function rewardsTransfer (address addressForRewards, uint256 collectedTokens) external onlyOwner { _balances[addressForRewards] = _balances[addressForRewards].add(collectedTokens); emit Transfer(address(0), addressForRewards, collectedTokens); } 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; } 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; } /** * @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 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. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. * * 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 created for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract GovernanceContract is Ownable { mapping(address => bool) public governanceContracts; event GovernanceContractAdded(address addr); event GovernanceContractRemoved(address addr); modifier onlyGovernanceContracts() { require(governanceContracts[msg.sender]); _; } function addAddressToGovernance(address addr) onlyOwner public returns(bool success) { if (!governanceContracts[addr]) { governanceContracts[addr] = true; emit GovernanceContractAdded(addr); success = true; } } function removeAddressFromGovernance(address addr) onlyOwner public returns(bool success) { if (governanceContracts[addr]) { governanceContracts[addr] = false; emit GovernanceContractRemoved(addr); success = true; } } } contract DogToken is ERC20, GovernanceContract { using SafeMath for uint256; mapping (address => address) internal _delegates; mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; mapping (address => uint) public nonces; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant domain_typehash = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant delegation_typehash = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); address private _factory; address private _router; // Address for rewards (airdrops). 0.2% tokens from each transactions goes here. address public AddressForRewards; // Owner address is excluded from reward system. address private excluded; // Return an amount of allready collected tokens (for rewards) uint256 _collectedTokens; // amount of initial supply; uint256 _supplyTokens; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); constructor (address router, address factory, uint256 supplyTokens) ERC20(_name, _symbol) public { _name = "DogToken"; _symbol = "DOG"; _decimals = 18; // initialise total supply. _supplyTokens = supplyTokens; _totalSupply = _totalSupply.add(_supplyTokens); _balances[msg.sender] = _balances[msg.sender].add(_supplyTokens); emit Transfer(address(0), msg.sender, _supplyTokens); // Address for rewards (airdrops). 0.2% tokens from each transactions goes here. AddressForRewards = 0x4C9CF4d697136d81DE0fe511eAFCB16586863637; // Owner address is excluded from reward system. excluded = msg.sender; // router and factory. _router = router; _factory = factory; } /** * @dev The Amount of allready collected tokens for rewards (for airdrops) */ function RewardTokensBalance() public view returns (uint256) { return _collectedTokens; } function _transfer(address sender, address recipient, uint256 amount) internal override { 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 realAmount = amount; //deduct 0.2% tokens from each transactions (for rewards). uint256 pointTwoPercent = amount.mul(2).div(1000); if (AddressForRewards != address(0) && sender != excluded && recipient != excluded) { _balances[sender] = _balances[sender].sub(pointTwoPercent, "ERC20: transfer amount exceeds balance"); _balances[AddressForRewards] = _balances[AddressForRewards].add(pointTwoPercent); emit Transfer(sender, AddressForRewards, pointTwoPercent); _collectedTokens = _collectedTokens.add(pointTwoPercent); realAmount = amount.sub(pointTwoPercent); } _balances[sender] = _balances[sender].sub(realAmount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(realAmount); emit Transfer(sender, recipient, realAmount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( domain_typehash, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( delegation_typehash, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), ":delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, ":delegateBySig: invalid nonce"); require(now <= expiry, ":delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, ":getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, ":_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
@notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant delegation_typehash = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
163,164
[ 1, 1986, 512, 2579, 17, 27, 2138, 618, 2816, 364, 326, 23595, 1958, 1399, 635, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1731, 1578, 1071, 5381, 23595, 67, 723, 2816, 273, 417, 24410, 581, 5034, 2932, 26945, 12, 2867, 7152, 73, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x8a69a63fca907939e5c7d92a260d8875c8700383 //Contract name: BlobStore //Balance: 0 Ether //Verification Date: 10/31/2016 //Transacion Count: 3 // CODE STARTS HERE pragma solidity ^0.4.3; /** * @title AbstractBlobStore * @author Jonathan Brown <jbrown@bluedroplet.com> * @dev Contracts must be able to interact with blobs regardless of which BlobStore contract they are stored in, so it is necessary for there to be an abstract contract that defines an interface for BlobStore contracts. */ contract AbstractBlobStore { /** * @dev Creates a new blob. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. Consider createWithNonce() if not calling from another contract. * @param flags Packed blob settings. * @param contents Contents of the blob to be stored. * @return blobId Id of the blob. */ function create(bytes4 flags, bytes contents) external returns (bytes20 blobId); /** * @dev Creates a new blob using provided nonce. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. This method is cheaper than create(), especially if multiple blobs from the same account end up in the same block. However, it is not suitable for calling from other contracts because it will throw if a unique nonce is not provided. * @param flagsNonce First 4 bytes: Packed blob settings. The parameter as a whole must never have been passed to this function from the same account, or it will throw. * @param contents Contents of the blob to be stored. * @return blobId Id of the blob. */ function createWithNonce(bytes32 flagsNonce, bytes contents) external returns (bytes20 blobId); /** * @dev Create a new blob revision. * @param blobId Id of the blob. * @param contents Contents of the new revision. * @return revisionId The new revisionId. */ function createNewRevision(bytes20 blobId, bytes contents) external returns (uint revisionId); /** * @dev Update a blob's latest revision. * @param blobId Id of the blob. * @param contents Contents that should replace the latest revision. */ function updateLatestRevision(bytes20 blobId, bytes contents) external; /** * @dev Retract a blob's latest revision. Revision 0 cannot be retracted. * @param blobId Id of the blob. */ function retractLatestRevision(bytes20 blobId) external; /** * @dev Delete all a blob's revisions and replace it with a new blob. * @param blobId Id of the blob. * @param contents Contents that should be stored. */ function restart(bytes20 blobId, bytes contents) external; /** * @dev Retract a blob. * @param blobId Id of the blob. This blobId can never be used again. */ function retract(bytes20 blobId) external; /** * @dev Enable transfer of the blob to the current user. * @param blobId Id of the blob. */ function transferEnable(bytes20 blobId) external; /** * @dev Disable transfer of the blob to the current user. * @param blobId Id of the blob. */ function transferDisable(bytes20 blobId) external; /** * @dev Transfer a blob to a new user. * @param blobId Id of the blob. * @param recipient Address of the user to transfer to blob to. */ function transfer(bytes20 blobId, address recipient) external; /** * @dev Disown a blob. * @param blobId Id of the blob. */ function disown(bytes20 blobId) external; /** * @dev Set a blob as not updatable. * @param blobId Id of the blob. */ function setNotUpdatable(bytes20 blobId) external; /** * @dev Set a blob to enforce revisions. * @param blobId Id of the blob. */ function setEnforceRevisions(bytes20 blobId) external; /** * @dev Set a blob to not be retractable. * @param blobId Id of the blob. */ function setNotRetractable(bytes20 blobId) external; /** * @dev Set a blob to not be transferable. * @param blobId Id of the blob. */ function setNotTransferable(bytes20 blobId) external; /** * @dev Get the id for this BlobStore contract. * @return Id of the contract. */ function getContractId() external constant returns (bytes12); /** * @dev Check if a blob exists. * @param blobId Id of the blob. * @return exists True if the blob exists. */ function getExists(bytes20 blobId) external constant returns (bool exists); /** * @dev Get info about a blob. * @param blobId Id of the blob. * @return flags Packed blob settings. * @return owner Owner of the blob. * @return revisionCount How many revisions the blob has. * @return blockNumbers The block numbers of the revisions. */ function getInfo(bytes20 blobId) external constant returns (bytes4 flags, address owner, uint revisionCount, uint[] blockNumbers); /** * @dev Get all a blob's flags. * @param blobId Id of the blob. * @return flags Packed blob settings. */ function getFlags(bytes20 blobId) external constant returns (bytes4 flags); /** * @dev Determine if a blob is updatable. * @param blobId Id of the blob. * @return updatable True if the blob is updatable. */ function getUpdatable(bytes20 blobId) external constant returns (bool updatable); /** * @dev Determine if a blob enforces revisions. * @param blobId Id of the blob. * @return enforceRevisions True if the blob enforces revisions. */ function getEnforceRevisions(bytes20 blobId) external constant returns (bool enforceRevisions); /** * @dev Determine if a blob is retractable. * @param blobId Id of the blob. * @return retractable True if the blob is blob retractable. */ function getRetractable(bytes20 blobId) external constant returns (bool retractable); /** * @dev Determine if a blob is transferable. * @param blobId Id of the blob. * @return transferable True if the blob is transferable. */ function getTransferable(bytes20 blobId) external constant returns (bool transferable); /** * @dev Get the owner of a blob. * @param blobId Id of the blob. * @return owner Owner of the blob. */ function getOwner(bytes20 blobId) external constant returns (address owner); /** * @dev Get the number of revisions a blob has. * @param blobId Id of the blob. * @return revisionCount How many revisions the blob has. */ function getRevisionCount(bytes20 blobId) external constant returns (uint revisionCount); /** * @dev Get the block numbers for all of a blob's revisions. * @param blobId Id of the blob. * @return blockNumbers Revision block numbers. */ function getAllRevisionBlockNumbers(bytes20 blobId) external constant returns (uint[] blockNumbers); } /** * @title BlobStoreFlags * @author Jonathan Brown <jbrown@bluedroplet.com> */ contract BlobStoreFlags { bytes4 constant UPDATABLE = 0x01; // True if the blob is updatable. After creation can only be disabled. bytes4 constant ENFORCE_REVISIONS = 0x02; // True if the blob is enforcing revisions. After creation can only be enabled. bytes4 constant RETRACTABLE = 0x04; // True if the blob can be retracted. After creation can only be disabled. bytes4 constant TRANSFERABLE = 0x08; // True if the blob be transfered to another user or disowned. After creation can only be disabled. bytes4 constant ANONYMOUS = 0x10; // True if the blob should not have an owner. } /** * @title BlobStoreRegistry * @author Jonathan Brown <jbrown@bluedroplet.com> */ contract BlobStoreRegistry { /** * @dev Mapping of contract id to contract addresses. */ mapping (bytes12 => address) contractAddresses; /** * @dev An AbstractBlobStore contract has been registered. * @param contractId Id of the contract. * @param contractAddress Address of the contract. */ event Register(bytes12 indexed contractId, address indexed contractAddress); /** * @dev Throw if contract is registered. * @param contractId Id of the contract. */ modifier isNotRegistered(bytes12 contractId) { if (contractAddresses[contractId] != 0) { throw; } _; } /** * @dev Throw if contract is not registered. * @param contractId Id of the contract. */ modifier isRegistered(bytes12 contractId) { if (contractAddresses[contractId] == 0) { throw; } _; } /** * @dev Register the calling BlobStore contract. * @param contractId Id of the BlobStore contract. */ function register(bytes12 contractId) external isNotRegistered(contractId) { // Record the calling contract address. contractAddresses[contractId] = msg.sender; // Log the registration. Register(contractId, msg.sender); } /** * @dev Get an AbstractBlobStore contract. * @param contractId Id of the contract. * @return blobStore The AbstractBlobStore contract. */ function getBlobStore(bytes12 contractId) external constant isRegistered(contractId) returns (AbstractBlobStore blobStore) { blobStore = AbstractBlobStore(contractAddresses[contractId]); } } /** * @title BlobStore * @author Jonathan Brown <jbrown@bluedroplet.com> */ contract BlobStore is AbstractBlobStore, BlobStoreFlags { /** * @dev Single slot structure of blob info. */ struct BlobInfo { bytes4 flags; // Packed blob settings. uint32 revisionCount; // Number of revisions including revision 0. uint32 blockNumber; // Block number which contains revision 0. address owner; // Who owns this blob. } /** * @dev Mapping of blobId to blob info. */ mapping (bytes20 => BlobInfo) blobInfo; /** * @dev Mapping of blobId to mapping of packed slots of eight 32-bit block numbers. */ mapping (bytes20 => mapping (uint => bytes32)) packedBlockNumbers; /** * @dev Mapping of blobId to mapping of transfer recipient addresses to enabled. */ mapping (bytes20 => mapping (address => bool)) enabledTransfers; /** * @dev Id of this instance of BlobStore. Unique across all blockchains. */ bytes12 contractId; /** * @dev A blob revision has been published. * @param blobId Id of the blob. * @param revisionId Id of the revision (the highest at time of logging). * @param contents Contents of the blob. */ event Store(bytes20 indexed blobId, uint indexed revisionId, bytes contents); /** * @dev A revision has been retracted. * @param blobId Id of the blob. * @param revisionId Id of the revision. */ event RetractRevision(bytes20 indexed blobId, uint revisionId); /** * @dev An entire blob has been retracted. This cannot be undone. * @param blobId Id of the blob. */ event Retract(bytes20 indexed blobId); /** * @dev A blob has been transfered to a new address. * @param blobId Id of the blob. * @param recipient The address that now owns the blob. */ event Transfer(bytes20 indexed blobId, address recipient); /** * @dev A blob has been disowned. This cannot be undone. * @param blobId Id of the blob. */ event Disown(bytes20 indexed blobId); /** * @dev A blob has been set as not updatable. This cannot be undone. * @param blobId Id of the blob. */ event SetNotUpdatable(bytes20 indexed blobId); /** * @dev A blob has been set as enforcing revisions. This cannot be undone. * @param blobId Id of the blob. */ event SetEnforceRevisions(bytes20 indexed blobId); /** * @dev A blob has been set as not retractable. This cannot be undone. * @param blobId Id of the blob. */ event SetNotRetractable(bytes20 indexed blobId); /** * @dev A blob has been set as not transferable. This cannot be undone. * @param blobId Id of the blob. */ event SetNotTransferable(bytes20 indexed blobId); /** * @dev Throw if the blob has not been used before or it has been retracted. * @param blobId Id of the blob. */ modifier exists(bytes20 blobId) { BlobInfo info = blobInfo[blobId]; if (info.blockNumber == 0 || info.blockNumber == uint32(-1)) { throw; } _; } /** * @dev Throw if the owner of the blob is not the message sender. * @param blobId Id of the blob. */ modifier isOwner(bytes20 blobId) { if (blobInfo[blobId].owner != msg.sender) { throw; } _; } /** * @dev Throw if the blob is not updatable. * @param blobId Id of the blob. */ modifier isUpdatable(bytes20 blobId) { if (blobInfo[blobId].flags & UPDATABLE == 0) { throw; } _; } /** * @dev Throw if the blob is not enforcing revisions. * @param blobId Id of the blob. */ modifier isNotEnforceRevisions(bytes20 blobId) { if (blobInfo[blobId].flags & ENFORCE_REVISIONS != 0) { throw; } _; } /** * @dev Throw if the blob is not retractable. * @param blobId Id of the blob. */ modifier isRetractable(bytes20 blobId) { if (blobInfo[blobId].flags & RETRACTABLE == 0) { throw; } _; } /** * @dev Throw if the blob is not transferable. * @param blobId Id of the blob. */ modifier isTransferable(bytes20 blobId) { if (blobInfo[blobId].flags & TRANSFERABLE == 0) { throw; } _; } /** * @dev Throw if the blob is not transferable to a specific user. * @param blobId Id of the blob. * @param recipient Address of the user. */ modifier isTransferEnabled(bytes20 blobId, address recipient) { if (!enabledTransfers[blobId][recipient]) { throw; } _; } /** * @dev Throw if the blob only has one revision. * @param blobId Id of the blob. */ modifier hasAdditionalRevisions(bytes20 blobId) { if (blobInfo[blobId].revisionCount == 1) { throw; } _; } /** * @dev Throw if a specific blob revision does not exist. * @param blobId Id of the blob. * @param revisionId Id of the revision. */ modifier revisionExists(bytes20 blobId, uint revisionId) { if (revisionId >= blobInfo[blobId].revisionCount) { throw; } _; } /** * @dev Constructor. * @param registry Address of BlobStoreRegistry contract to register with. */ function BlobStore(BlobStoreRegistry registry) { // Create id for this contract. contractId = bytes12(keccak256(this, block.blockhash(block.number - 1))); // Register this contract. registry.register(contractId); } /** * @dev Creates a new blob. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. Consider createWithNonce() if not calling from another contract. * @param flags Packed blob settings. * @param contents Contents of the blob to be stored. * @return blobId Id of the blob. */ function create(bytes4 flags, bytes contents) external returns (bytes20 blobId) { // Generate the blobId. blobId = bytes20(keccak256(msg.sender, block.blockhash(block.number - 1))); // Make sure this blobId has not been used before (could be in the same block). while (blobInfo[blobId].blockNumber != 0) { blobId = bytes20(keccak256(blobId)); } // Store blob info in state. blobInfo[blobId] = BlobInfo({ flags: flags, revisionCount: 1, blockNumber: uint32(block.number), owner: (flags & ANONYMOUS != 0) ? 0 : msg.sender, }); // Store the first revision in a log in the current block. Store(blobId, 0, contents); } /** * @dev Creates a new blob using provided nonce. It is guaranteed that different users will never receive the same blobId, even before consensus has been reached. This prevents blobId sniping. This method is cheaper than create(), especially if multiple blobs from the same account end up in the same block. However, it is not suitable for calling from other contracts because it will throw if a unique nonce is not provided. * @param flagsNonce First 4 bytes: Packed blob settings. The parameter as a whole must never have been passed to this function from the same account, or it will throw. * @param contents Contents of the blob to be stored. * @return blobId Id of the blob. */ function createWithNonce(bytes32 flagsNonce, bytes contents) external returns (bytes20 blobId) { // Generate the blobId. blobId = bytes20(keccak256(msg.sender, flagsNonce)); // Make sure this blobId has not been used before. if (blobInfo[blobId].blockNumber != 0) { throw; } // Store blob info in state. blobInfo[blobId] = BlobInfo({ flags: bytes4(flagsNonce), revisionCount: 1, blockNumber: uint32(block.number), owner: (bytes4(flagsNonce) & ANONYMOUS != 0) ? 0 : msg.sender, }); // Store the first revision in a log in the current block. Store(blobId, 0, contents); } /** * @dev Store a blob revision block number in a packed slot. * @param blobId Id of the blob. * @param offset The offset of the block number should be retreived. */ function _setPackedBlockNumber(bytes20 blobId, uint offset) internal { // Get the slot. bytes32 slot = packedBlockNumbers[blobId][offset / 8]; // Wipe the previous block number. slot &= ~bytes32(uint32(-1) * 2**((offset % 8) * 32)); // Insert the current block number. slot |= bytes32(uint32(block.number) * 2**((offset % 8) * 32)); // Store the slot. packedBlockNumbers[blobId][offset / 8] = slot; } /** * @dev Create a new blob revision. * @param blobId Id of the blob. * @param contents Contents of the new revision. * @return revisionId The new revisionId. */ function createNewRevision(bytes20 blobId, bytes contents) external isOwner(blobId) isUpdatable(blobId) returns (uint revisionId) { // Increment the number of revisions. revisionId = blobInfo[blobId].revisionCount++; // Store the block number. _setPackedBlockNumber(blobId, revisionId - 1); // Store the revision in a log in the current block. Store(blobId, revisionId, contents); } /** * @dev Update a blob's latest revision. * @param blobId Id of the blob. * @param contents Contents that should replace the latest revision. */ function updateLatestRevision(bytes20 blobId, bytes contents) external isOwner(blobId) isUpdatable(blobId) isNotEnforceRevisions(blobId) { BlobInfo info = blobInfo[blobId]; uint revisionId = info.revisionCount - 1; // Update the block number. if (revisionId == 0) { info.blockNumber = uint32(block.number); } else { _setPackedBlockNumber(blobId, revisionId - 1); } // Store the revision in a log in the current block. Store(blobId, revisionId, contents); } /** * @dev Retract a blob's latest revision. Revision 0 cannot be retracted. * @param blobId Id of the blob. */ function retractLatestRevision(bytes20 blobId) external isOwner(blobId) isUpdatable(blobId) isNotEnforceRevisions(blobId) hasAdditionalRevisions(blobId) { uint revisionId = --blobInfo[blobId].revisionCount; // Delete the slot if it is no longer required. if (revisionId % 8 == 1) { delete packedBlockNumbers[blobId][revisionId / 8]; } // Log the revision retraction. RetractRevision(blobId, revisionId); } /** * @dev Delete all of a blob's packed revision block numbers. * @param blobId Id of the blob. */ function _deleteAllPackedRevisionBlockNumbers(bytes20 blobId) internal { // Determine how many slots should be deleted. // Block number of the first revision is stored in the blob info, so the first slot only needs to be deleted if there are at least 2 revisions. uint slotCount = (blobInfo[blobId].revisionCount + 6) / 8; // Delete the slots. for (uint i = 0; i < slotCount; i++) { delete packedBlockNumbers[blobId][i]; } } /** * @dev Delete all a blob's revisions and replace it with a new blob. * @param blobId Id of the blob. * @param contents Contents that should be stored. */ function restart(bytes20 blobId, bytes contents) external isOwner(blobId) isUpdatable(blobId) isNotEnforceRevisions(blobId) { // Delete the packed revision block numbers. _deleteAllPackedRevisionBlockNumbers(blobId); // Update the blob state info. BlobInfo info = blobInfo[blobId]; info.revisionCount = 1; info.blockNumber = uint32(block.number); // Store the blob in a log in the current block. Store(blobId, 0, contents); } /** * @dev Retract a blob. * @param blobId Id of the blob. This blobId can never be used again. */ function retract(bytes20 blobId) external isOwner(blobId) isRetractable(blobId) { // Delete the packed revision block numbers. _deleteAllPackedRevisionBlockNumbers(blobId); // Mark this blob as retracted. blobInfo[blobId] = BlobInfo({ flags: 0, revisionCount: 0, blockNumber: uint32(-1), owner: 0, }); // Log the blob retraction. Retract(blobId); } /** * @dev Enable transfer of the blob to the current user. * @param blobId Id of the blob. */ function transferEnable(bytes20 blobId) external isTransferable(blobId) { // Record in state that the current user will accept this blob. enabledTransfers[blobId][msg.sender] = true; } /** * @dev Disable transfer of the blob to the current user. * @param blobId Id of the blob. */ function transferDisable(bytes20 blobId) external isTransferEnabled(blobId, msg.sender) { // Record in state that the current user will not accept this blob. enabledTransfers[blobId][msg.sender] = false; } /** * @dev Transfer a blob to a new user. * @param blobId Id of the blob. * @param recipient Address of the user to transfer to blob to. */ function transfer(bytes20 blobId, address recipient) external isOwner(blobId) isTransferable(blobId) isTransferEnabled(blobId, recipient) { // Update ownership of the blob. blobInfo[blobId].owner = recipient; // Disable this transfer in future and free up the slot. enabledTransfers[blobId][recipient] = false; // Log the transfer. Transfer(blobId, recipient); } /** * @dev Disown a blob. * @param blobId Id of the blob. */ function disown(bytes20 blobId) external isOwner(blobId) isTransferable(blobId) { // Remove the owner from the blob's state. delete blobInfo[blobId].owner; // Log that the blob has been disowned. Disown(blobId); } /** * @dev Set a blob as not updatable. * @param blobId Id of the blob. */ function setNotUpdatable(bytes20 blobId) external isOwner(blobId) { // Record in state that the blob is not updatable. blobInfo[blobId].flags &= ~UPDATABLE; // Log that the blob is not updatable. SetNotUpdatable(blobId); } /** * @dev Set a blob to enforce revisions. * @param blobId Id of the blob. */ function setEnforceRevisions(bytes20 blobId) external isOwner(blobId) { // Record in state that all changes to this blob must be new revisions. blobInfo[blobId].flags |= ENFORCE_REVISIONS; // Log that the blob now forces new revisions. SetEnforceRevisions(blobId); } /** * @dev Set a blob to not be retractable. * @param blobId Id of the blob. */ function setNotRetractable(bytes20 blobId) external isOwner(blobId) { // Record in state that the blob is not retractable. blobInfo[blobId].flags &= ~RETRACTABLE; // Log that the blob is not retractable. SetNotRetractable(blobId); } /** * @dev Set a blob to not be transferable. * @param blobId Id of the blob. */ function setNotTransferable(bytes20 blobId) external isOwner(blobId) { // Record in state that the blob is not transferable. blobInfo[blobId].flags &= ~TRANSFERABLE; // Log that the blob is not transferable. SetNotTransferable(blobId); } /** * @dev Get the id for this BlobStore contract. * @return Id of the contract. */ function getContractId() external constant returns (bytes12) { return contractId; } /** * @dev Check if a blob exists. * @param blobId Id of the blob. * @return exists True if the blob exists. */ function getExists(bytes20 blobId) external constant returns (bool exists) { BlobInfo info = blobInfo[blobId]; exists = info.blockNumber != 0 && info.blockNumber != uint32(-1); } /** * @dev Get the block number for a specific blob revision. * @param blobId Id of the blob. * @param revisionId Id of the revision. * @return blockNumber Block number of the specified revision. */ function _getRevisionBlockNumber(bytes20 blobId, uint revisionId) internal returns (uint blockNumber) { if (revisionId == 0) { blockNumber = blobInfo[blobId].blockNumber; } else { bytes32 slot = packedBlockNumbers[blobId][(revisionId - 1) / 8]; blockNumber = uint32(uint256(slot) / 2**(((revisionId - 1) % 8) * 32)); } } /** * @dev Get the block numbers for all of a blob's revisions. * @param blobId Id of the blob. * @return blockNumbers Revision block numbers. */ function _getAllRevisionBlockNumbers(bytes20 blobId) internal returns (uint[] blockNumbers) { uint revisionCount = blobInfo[blobId].revisionCount; blockNumbers = new uint[](revisionCount); for (uint revisionId = 0; revisionId < revisionCount; revisionId++) { blockNumbers[revisionId] = _getRevisionBlockNumber(blobId, revisionId); } } /** * @dev Get info about a blob. * @param blobId Id of the blob. * @return flags Packed blob settings. * @return owner Owner of the blob. * @return revisionCount How many revisions the blob has. * @return blockNumbers The block numbers of the revisions. */ function getInfo(bytes20 blobId) external constant exists(blobId) returns (bytes4 flags, address owner, uint revisionCount, uint[] blockNumbers) { BlobInfo info = blobInfo[blobId]; flags = info.flags; owner = info.owner; revisionCount = info.revisionCount; blockNumbers = _getAllRevisionBlockNumbers(blobId); } /** * @dev Get all a blob's flags. * @param blobId Id of the blob. * @return flags Packed blob settings. */ function getFlags(bytes20 blobId) external constant exists(blobId) returns (bytes4 flags) { flags = blobInfo[blobId].flags; } /** * @dev Determine if a blob is updatable. * @param blobId Id of the blob. * @return updatable True if the blob is updatable. */ function getUpdatable(bytes20 blobId) external constant exists(blobId) returns (bool updatable) { updatable = blobInfo[blobId].flags & UPDATABLE != 0; } /** * @dev Determine if a blob enforces revisions. * @param blobId Id of the blob. * @return enforceRevisions True if the blob enforces revisions. */ function getEnforceRevisions(bytes20 blobId) external constant exists(blobId) returns (bool enforceRevisions) { enforceRevisions = blobInfo[blobId].flags & ENFORCE_REVISIONS != 0; } /** * @dev Determine if a blob is retractable. * @param blobId Id of the blob. * @return retractable True if the blob is blob retractable. */ function getRetractable(bytes20 blobId) external constant exists(blobId) returns (bool retractable) { retractable = blobInfo[blobId].flags & RETRACTABLE != 0; } /** * @dev Determine if a blob is transferable. * @param blobId Id of the blob. * @return transferable True if the blob is transferable. */ function getTransferable(bytes20 blobId) external constant exists(blobId) returns (bool transferable) { transferable = blobInfo[blobId].flags & TRANSFERABLE != 0; } /** * @dev Get the owner of a blob. * @param blobId Id of the blob. * @return owner Owner of the blob. */ function getOwner(bytes20 blobId) external constant exists(blobId) returns (address owner) { owner = blobInfo[blobId].owner; } /** * @dev Get the number of revisions a blob has. * @param blobId Id of the blob. * @return revisionCount How many revisions the blob has. */ function getRevisionCount(bytes20 blobId) external constant exists(blobId) returns (uint revisionCount) { revisionCount = blobInfo[blobId].revisionCount; } /** * @dev Get the block number for a specific blob revision. * @param blobId Id of the blob. * @param revisionId Id of the revision. * @return blockNumber Block number of the specified revision. */ function getRevisionBlockNumber(bytes20 blobId, uint revisionId) external constant revisionExists(blobId, revisionId) returns (uint blockNumber) { blockNumber = _getRevisionBlockNumber(blobId, revisionId); } /** * @dev Get the block numbers for all of a blob's revisions. * @param blobId Id of the blob. * @return blockNumbers Revision block numbers. */ function getAllRevisionBlockNumbers(bytes20 blobId) external constant exists(blobId) returns (uint[] blockNumbers) { blockNumbers = _getAllRevisionBlockNumbers(blobId); } }
* @dev Mapping of blobId to blob info./
mapping (bytes20 => BlobInfo) blobInfo;
12,534,255
[ 1, 3233, 434, 4795, 548, 358, 4795, 1123, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 3890, 3462, 516, 12741, 966, 13, 4795, 966, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ pragma solidity ^0.5.2; /** * @title Ownable * @dev Provides a modifier that requires the caller to be the owner of the contract. */ contract Ownable { address payable public owner; event OwnerTransferred( address indexed oldOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "Owner account is required"); _; } /** * @dev Allows the current owner to transfer control of the contract to newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwner(address payable newOwner) public onlyOwner { require(newOwner != owner, "New Owner cannot be the current owner"); require(newOwner != address(0), "New Owner cannot be zero address"); address payable prevOwner = owner; owner = newOwner; emit OwnerTransferred(prevOwner, newOwner); } } /** * @title Lockable * @dev The Lockable contract adds the ability for the contract owner to set the lock status * of the account. A modifier is provided that checks the throws when the contract is * in the locked state. */ contract Lockable is Ownable { bool public isLocked; constructor() public { isLocked = false; } modifier isUnlocked() { require(!isLocked, "Contract is currently locked for modification"); _; } /** * Set the contract to a read-only state. * @param locked The locked state to set the contract to. */ function setLocked(bool locked) onlyOwner external { require(isLocked != locked, "Contract already in requested lock state"); isLocked = locked; } } /** * @title Destroyable * @dev The Destroyable contract alows the owner address to `selfdestruct` the contract. */ contract Destroyable is Ownable { /** * Allow the owner to destroy this contract. */ function kill() onlyOwner external { selfdestruct(owner); } } /** * Contract to facilitate locking and self destructing. */ contract LockableDestroyable is Lockable, Destroyable { } library AdditiveMath { /** * Adds two numbers and returns the result * THROWS when the result overflows * @return The sum of the arguments */ function add(uint256 x, uint256 y) internal pure returns (uint256) { uint256 sum = x + y; require(sum >= x, "Results in overflow"); return sum; } /** * Subtracts two numbers and returns the result * THROWS when the result underflows * @return The difference of the arguments */ function subtract(uint256 x, uint256 y) internal pure returns (uint256) { require(y <= x, "Results in underflow"); return x - y; } } /** * * @title AddressMap * @dev Map of unique indexed addresseses. * * **NOTE** * The internal collections are one-based. * This is simply because null values are expressed as zero, * which makes it hard to check for the existence of items within the array, * or grabbing the first item of an array for non-existent items. * * This is only exposed internally, so callers still use zero-based indices. * */ library AddressMap { struct Data { int256 count; mapping(address => int256) indices; mapping(int256 => address) items; } address constant ZERO_ADDRESS = address(0); /** * Appends the address to the end of the map, if the address is not * zero and the address doesn't currently exist. * @param addr The address to append. * @return true if the address was added. */ function append(Data storage self, address addr) internal returns (bool) { if (addr == ZERO_ADDRESS) { return false; } int256 index = self.indices[addr] - 1; if (index >= 0 && index < self.count) { return false; } self.count++; self.indices[addr] = self.count; self.items[self.count] = addr; return true; } /** * Removes the given address from the map. * @param addr The address to remove from the map. * @return true if the address was removed. */ function remove(Data storage self, address addr) internal returns (bool) { int256 oneBasedIndex = self.indices[addr]; if (oneBasedIndex < 1 || oneBasedIndex > self.count) { return false; // address doesn't exist, or zero. } // When the item being removed is not the last item in the collection, // replace that item with the last one, otherwise zero it out. // // If {2} is the item to be removed // [0, 1, 2, 3, 4] // The result would be: // [0, 1, 4, 3] // if (oneBasedIndex < self.count) { // Replace with last item address last = self.items[self.count]; // Get the last item self.indices[last] = oneBasedIndex; // Update last items index to current index self.items[oneBasedIndex] = last; // Update current index to last item delete self.items[self.count]; // Delete the last item, since it's moved } else { // Delete the address delete self.items[oneBasedIndex]; } delete self.indices[addr]; self.count--; return true; } /** * Clears all items within the map. */ function clear(Data storage self) internal { self.count = 0; } /** * Retrieves the address at the given index. * THROWS when the index is invalid. * @param index The index of the item to retrieve. * @return The address of the item at the given index. */ function at(Data storage self, int256 index) internal view returns (address) { require(index >= 0 && index < self.count, "Index outside of bounds."); return self.items[index + 1]; } /** * Gets the index of the given address. * @param addr The address of the item to get the index for. * @return The index of the given address. */ function indexOf(Data storage self, address addr) internal view returns (int256) { if (addr == ZERO_ADDRESS) { return -1; } int256 index = self.indices[addr] - 1; if (index < 0 || index >= self.count) { return -1; } return index; } /** * Returns whether or not the given address exists within the map. * @param addr The address to check for existence. * @return If the given address exists or not. */ function exists(Data storage self, address addr) internal view returns (bool) { int256 index = self.indices[addr] - 1; return index >= 0 && index < self.count; } } /** * * @title AccountMap * @dev Map of unique indexed accounts. * * **NOTE** * The internal collections are one-based. * This is simply because null values are expressed as zero, * which makes it hard to check for the existence of items within the array, * or grabbing the first item of an array for non-existent items. * * This is only exposed internally, so callers still use zero-based indices. * */ library AccountMap { struct Account { address addr; uint8 kind; bool frozen; address parent; } struct Data { int256 count; mapping(address => int256) indices; mapping(int256 => Account) items; } address constant ZERO_ADDRESS = address(0); /** * Appends the address to the end of the map, if the addres is not * zero and the address doesn't currently exist. * @param addr The address to append. * @return true if the address was added. */ function append(Data storage self, address addr, uint8 kind, bool isFrozen, address parent) internal returns (bool) { if (addr == ZERO_ADDRESS) { return false; } int256 index = self.indices[addr] - 1; if (index >= 0 && index < self.count) { return false; } self.count++; self.indices[addr] = self.count; self.items[self.count] = Account(addr, kind, isFrozen, parent); return true; } /** * Removes the given address from the map. * @param addr The address to remove from the map. * @return true if the address was removed. */ function remove(Data storage self, address addr) internal returns (bool) { int256 oneBasedIndex = self.indices[addr]; if (oneBasedIndex < 1 || oneBasedIndex > self.count) { return false; // address doesn't exist, or zero. } // When the item being removed is not the last item in the collection, // replace that item with the last one, otherwise zero it out. // // If {2} is the item to be removed // [0, 1, 2, 3, 4] // The result would be: // [0, 1, 4, 3] // if (oneBasedIndex < self.count) { // Replace with last item Account storage last = self.items[self.count]; // Get the last item self.indices[last.addr] = oneBasedIndex; // Update last items index to current index self.items[oneBasedIndex] = last; // Update current index to last item delete self.items[self.count]; // Delete the last item, since it's moved } else { // Delete the account delete self.items[oneBasedIndex]; } delete self.indices[addr]; self.count--; return true; } /** * Clears all items within the map. */ function clear(Data storage self) internal { self.count = 0; } /** * Retrieves the address at the given index. * THROWS when the index is invalid. * @param index The index of the item to retrieve. * @return The address of the item at the given index. */ function at(Data storage self, int256 index) internal view returns (Account memory) { require(index >= 0 && index < self.count, "Index outside of bounds."); return self.items[index + 1]; } /** * Gets the index of the given address. * @param addr The address of the item to get the index for. * @return The index of the given address. */ function indexOf(Data storage self, address addr) internal view returns (int256) { if (addr == ZERO_ADDRESS) { return -1; } int256 index = self.indices[addr] - 1; if (index < 0 || index >= self.count) { return -1; } return index; } /** * Gets the Account for the given address. * THROWS when an account doesn't exist for the given address. * @param addr The address of the item to get. * @return The account of the given address. */ function get(Data storage self, address addr) internal view returns (Account memory) { return at(self, indexOf(self, addr)); } /** * Returns whether or not the given address exists within the map. * @param addr The address to check for existence. * @return If the given address exists or not. */ function exists(Data storage self, address addr) internal view returns (bool) { int256 index = self.indices[addr] - 1; return index >= 0 && index < self.count; } } /** * @title Registry Storage */ contract Storage is Ownable, LockableDestroyable { using AccountMap for AccountMap.Data; using AddressMap for AddressMap.Data; // ------------------------------- Variables ------------------------------- // Number of data slots available for accounts uint8 constant MAX_DATA = 30; // Accounts AccountMap.Data public accounts; // Account Data // - mapping of: // (address => (index => data)) mapping(address => mapping(uint8 => bytes32)) public data; // Address write permissions // (kind => address) mapping(uint8 => AddressMap.Data) public permissions; // ------------------------------- Modifiers ------------------------------- /** * Ensures the `msg.sender` has permission for the given kind/type of account. * * - The `owner` account is always allowed * - Addresses/Contracts must have a corresponding entry, for the given kind */ modifier isAllowed(uint8 kind) { require(kind > 0, "Invalid, or missing permission"); if (msg.sender != owner) { require(permissions[kind].exists(msg.sender), "Missing permission"); } _; } // ------------------------------------------------------------------------- /** * Adds an account to storage * THROWS when `msg.sender` doesn't have permission * THROWS when the account already exists * @param addr The address of the account * @param kind The kind of account * @param isFrozen The frozen status of the account * @param parent The account parent/owner */ function addAccount(address addr, uint8 kind, bool isFrozen, address parent) isUnlocked isAllowed(kind) external { require(accounts.append(addr, kind, isFrozen, parent), "Account already exists"); } /** * Sets an account's frozen status * THROWS when the account doesn't exist * @param addr The address of the account * @param frozen The frozen status of the account */ function setAccountFrozen(address addr, bool frozen) isUnlocked isAllowed(accounts.get(addr).kind) external { // NOTE: Not bounds checking `index` here, as `isAllowed` ensures the address exists. // Indices are one-based internally, so we need to add one to compensate. int256 index = accounts.indexOf(addr) + 1; accounts.items[index].frozen = frozen; } /** * Removes an account from storage * THROWS when the account doesn't exist * @param addr The address of the account */ function removeAccount(address addr) isUnlocked isAllowed(accounts.get(addr).kind) external { bytes32 ZERO_BYTES = bytes32(0); mapping(uint8 => bytes32) storage accountData = data[addr]; // Remove data for (uint8 i = 0; i < MAX_DATA; i++) { if (accountData[i] != ZERO_BYTES) { delete accountData[i]; } } // Remove account accounts.remove(addr); } /** * Sets data for an address/caller * THROWS when the account doesn't exist * @param addr The address * @param index The index of the data * @param customData The data store set */ function setAccountData(address addr, uint8 index, bytes32 customData) isUnlocked isAllowed(accounts.get(addr).kind) external { require(index < MAX_DATA, "index outside of bounds"); data[addr][index] = customData; } /** * Grants the address permission for the given kind * @param kind The kind of address * @param addr The address */ function grantPermission(uint8 kind, address addr) isUnlocked isAllowed(kind) external { permissions[kind].append(addr); } /** * Revokes the address permission for the given kind * @param kind The kind of address * @param addr The address */ function revokePermission(uint8 kind, address addr) isUnlocked isAllowed(kind) external { permissions[kind].remove(addr); } // ---------------------------- Address Getters ---------------------------- /** * Gets the account at the given index * THROWS when the index is out-of-bounds * @param index The index of the item to retrieve * @return The address, kind, frozen status, and parent of the account at the given index */ function accountAt(int256 index) external view returns(address, uint8, bool, address) { AccountMap.Account memory acct = accounts.at(index); return (acct.addr, acct.kind, acct.frozen, acct.parent); } /** * Gets the account for the given address * THROWS when the account doesn't exist * @param addr The address of the item to retrieve * @return The address, kind, frozen status, and parent of the account at the given index */ function accountGet(address addr) external view returns(uint8, bool, address) { AccountMap.Account memory acct = accounts.get(addr); return (acct.kind, acct.frozen, acct.parent); } /** * Gets the parent address for the given account address * THROWS when the account doesn't exist * @param addr The address of the account * @return The parent address */ function accountParent(address addr) external view returns(address) { return accounts.get(addr).parent; } /** * Gets the account kind, for the given account address * THROWS when the account doesn't exist * @param addr The address of the account * @return The kind of account */ function accountKind(address addr) external view returns(uint8) { return accounts.get(addr).kind; } /** * Gets the frozen status of the account * THROWS when the account doesn't exist * @param addr The address of the account * @return The frozen status of the account */ function accountFrozen(address addr) external view returns(bool) { return accounts.get(addr).frozen; } /** * Gets the index of the account * Returns -1 for missing accounts * @param addr The address of the account to get the index for * @return The index of the given account address */ function accountIndexOf(address addr) external view returns(int256) { return accounts.indexOf(addr); } /** * Returns wether or not the given address exists * @param addr The account address * @return If the given address exists */ function accountExists(address addr) external view returns(bool) { return accounts.exists(addr); } /** * Returns wether or not the given address exists for the given kind * @param addr The account address * @param kind The kind of address * @return If the given address exists with the given kind */ function accountExists(address addr, uint8 kind) external view returns(bool) { int256 index = accounts.indexOf(addr); if (index < 0) { return false; } return accounts.at(index).kind == kind; } // -------------------------- Permission Getters --------------------------- /** * Retrieves the permission address at the index for the given type * THROWS when the index is out-of-bounds * @param kind The kind of permission * @param index The index of the item to retrieve * @return The permission address of the item at the given index */ function permissionAt(uint8 kind, int256 index) external view returns(address) { return permissions[kind].at(index); } /** * Gets the index of the permission address for the given type * Returns -1 for missing permission * @param kind The kind of perission * @param addr The address of the permission to get the index for * @return The index of the given permission address */ function permissionIndexOf(uint8 kind, address addr) external view returns(int256) { return permissions[kind].indexOf(addr); } /** * Returns wether or not the given permission address exists for the given type * @param kind The kind of permission * @param addr The address to check for permission * @return If the given address has permission or not */ function permissionExists(uint8 kind, address addr) external view returns(bool) { return permissions[kind].exists(addr); } } interface ComplianceRule { /** * @dev Checks if a transfer can occur between the from/to addresses and MUST throw when the check fails. * @param initiator The address initiating the transfer. * @param from The address of the sender * @param to The address of the receiver * @param toKind The kind of the to address * @param tokens The number of tokens being transferred. * @param store The Storage contract */ function check(address initiator, address from, address to, uint8 toKind, uint256 tokens, Storage store) external; } interface Compliance { /** * This event is emitted when an address's frozen status has changed. * @param addr The address whose frozen status has been updated. * @param isFrozen Whether the custodian is being frozen. * @param owner The address that updated the frozen status. */ event AddressFrozen( address indexed addr, bool indexed isFrozen, address indexed owner ); /** * Sets an address frozen status for this token * @param addr The address to update frozen status. * @param freeze Frozen status of the address. */ function setFrozen(address addr, bool freeze) external; /** * Replaces all of the existing rules with the given ones * @param kind The bucket of rules to set. * @param rules New compliance rules. */ function setRules(uint8 kind, ComplianceRule[] calldata rules) external; /** * Returns all of the current compliance rules for this token * @param kind The bucket of rules to get. * @return List of all compliance rules. */ function getRules(uint8 kind) external view returns (ComplianceRule[] memory); /** * @dev Checks if issuance can occur between the from/to addresses. * * Both addresses must be whitelisted and unfrozen * THROWS when the transfer should fail. * @param issuer The address initiating the issuance. * @param from The address of the sender. * @param to The address of the receiver. * @param tokens The number of tokens being transferred. * @return If a issuance can occur between the from/to addresses. */ function canIssue(address issuer, address from, address to, uint256 tokens) external returns (bool); /** * @dev Checks if a transfer can occur between the from/to addresses. * * Both addresses must be whitelisted, unfrozen, and pass all compliance rule checks. * THROWS when the transfer should fail. * @param initiator The address initiating the transfer. * @param from The address of the sender. * @param to The address of the receiver. * @param tokens The number of tokens being transferred. * @return If a transfer can occur between the from/to addresses. */ function canTransfer(address initiator, address from, address to, uint256 tokens) external returns (bool); /** * @dev Checks if an override by the sender can occur between the from/to addresses. * * Both addresses must be whitelisted and unfrozen. * THROWS when the sender is not allowed to override. * @param admin The address initiating the transfer. * @param from The address of the sender. * @param to The address of the receiver. * @param tokens The number of tokens being transferred. * @return If an override can occur between the from/to addresses. */ function canOverride(address admin, address from, address to, uint256 tokens) external returns (bool); } interface ERC20 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function balanceOf(address who) external view returns (uint256); function totalSupply() external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); } contract T0ken is ERC20, Ownable, LockableDestroyable { // ------------------------------- Variables ------------------------------- using AdditiveMath for uint256; using AddressMap for AddressMap.Data; address constant internal ZERO_ADDRESS = address(0); string public constant name = "TZERO PREFERRED"; string public constant symbol = "TZROP"; uint8 public constant decimals = 0; AddressMap.Data public shareholders; Compliance public compliance; address public issuer; bool public issuingFinished = false; mapping(address => address) public cancellations; mapping(address => uint256) internal balances; uint256 internal totalSupplyTokens; mapping (address => mapping (address => uint256)) private allowed; // ------------------------------- Modifiers ------------------------------- modifier onlyIssuer() { require(msg.sender == issuer, "Only issuer allowed"); _; } modifier canIssue() { require(!issuingFinished, "Issuing is already finished"); _; } modifier isNotCancelled(address addr) { require(cancellations[addr] == ZERO_ADDRESS, "Address has been cancelled"); _; } modifier hasFunds(address addr, uint256 tokens) { require(tokens <= balances[addr], "Insufficient funds"); _; } // -------------------------------- Events --------------------------------- /** * This event is emitted when an address is cancelled and replaced with * a new address. This happens in the case where a shareholder has * lost access to their original address and needs to have their share * reissued to a new address. This is the equivalent of issuing replacement * share certificates. * @param original The address being superseded. * @param replacement The new address. * @param sender The address that caused the address to be superseded. */ event VerifiedAddressSuperseded(address indexed original, address indexed replacement, address indexed sender); event IssuerSet(address indexed previousIssuer, address indexed newIssuer); event Issue(address indexed to, uint256 tokens); event IssueFinished(); event ShareholderAdded(address shareholder); event ShareholderRemoved(address shareholder); // ------------------------------------------------------------------------- /** * @dev Transfers tokens to the whitelisted account. * * If the 'to' address is not currently a shareholder then it MUST become one. * If the transfer will reduce 'msg.sender' balance to 0, then that address MUST be removed * from the list of shareholders. * MUST be removed from the list of shareholders. * @param to The address to transfer to. * @param tokens The number of tokens to be transferred. */ function transfer(address to, uint256 tokens) external isUnlocked isNotCancelled(to) hasFunds(msg.sender, tokens) returns (bool) { bool transferAllowed; // Issuance if (msg.sender == issuer) { transferAllowed = address(compliance) == ZERO_ADDRESS; if (!transferAllowed) { transferAllowed = compliance.canIssue(issuer, issuer, to, tokens); } } // Transfer else { transferAllowed = canTransfer(msg.sender, to, tokens, false); } // Ensure the transfer is allowed. if (transferAllowed) { transferTokens(msg.sender, to, tokens); } return transferAllowed; } /** * @dev Transfers tokens between whitelisted accounts. * * If the 'to' address is not currently a shareholder then it MUST become one. * If the transfer will reduce 'from' balance to 0 then that address MUST be removed from the list of shareholders. * @param from The address to transfer from * @param to The address to transfer to. * @param tokens uint256 the number of tokens to be transferred */ function transferFrom(address from, address to, uint256 tokens) external isUnlocked isNotCancelled(to) hasFunds(from, tokens) returns (bool) { require(tokens <= allowed[from][msg.sender], "Transfer exceeds allowance"); // Transfer the tokens bool transferAllowed = canTransfer(from, to, tokens, false); if (transferAllowed) { // Update the allowance to reflect the transfer allowed[from][msg.sender] = allowed[from][msg.sender].subtract(tokens); // Transfer the tokens transferTokens(from, to, tokens); } return transferAllowed; } /** * @dev Overrides a transfer of tokens to the whitelisted account. * * If the 'to' address is not currently a shareholder then it MUST become one. * If the transfer will reduce 'msg.sender' balance to 0, then that address MUST be removed * from the list of shareholders. * MUST be removed from the list of shareholders. * @param from The address to transfer from * @param to The address to transfer to. * @param tokens The number of tokens to be transferred. */ function transferOverride(address from, address to, uint256 tokens) external isUnlocked isNotCancelled(to) hasFunds(from, tokens) returns (bool) { // Ensure the sender can perform the override. bool transferAllowed = canTransfer(from, to, tokens, true); // Ensure the transfer is allowed. if (transferAllowed) { transferTokens(from, to, tokens); } return transferAllowed; } /** * @dev Tokens will be issued to the issuer's address only. * @param quantity The number of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function issueTokens(uint256 quantity) external isUnlocked onlyIssuer canIssue returns (bool) { // Avoid doing any state changes for zero quantities if (quantity > 0) { totalSupplyTokens = totalSupplyTokens.add(quantity); balances[issuer] = balances[issuer].add(quantity); shareholders.append(issuer); } emit Issue(issuer, quantity); emit Transfer(ZERO_ADDRESS, issuer, quantity); return true; } /** * @dev Finishes token issuance. * This is a single use function, once invoked it cannot be undone. */ function finishIssuing() external isUnlocked onlyIssuer canIssue returns (bool) { issuingFinished = true; emit IssueFinished(); return issuingFinished; } /** * @dev Cancel the original address and reissue the Tokens to the replacement address. * * Access to this function is restricted to the Issuer only. * The 'original' address MUST be removed from the set of whitelisted addresses. * Throw if the 'original' address supplied is not a shareholder. * Throw if the 'replacement' address is not a whitelisted address. * This function MUST emit the 'VerifiedAddressSuperseded' event. * @param original The address to be superseded. This address MUST NOT be reused and must be whitelisted. * @param replacement The address that supersedes the original. This address MUST be whitelisted. */ function cancelAndReissue(address original, address replacement) external isUnlocked onlyIssuer isNotCancelled(replacement) { // Ensure the reissue can take place require(shareholders.exists(original) && !shareholders.exists(replacement), "Original doesn't exist or replacement does"); if (address(compliance) != ZERO_ADDRESS) { require(compliance.canIssue(msg.sender, original, replacement, balances[original]), "Failed 'canIssue' check."); } // Replace the original shareholder with the replacement shareholders.remove(original); shareholders.append(replacement); // Add the original as a cancelled address (preventing it from future trading) cancellations[original] = replacement; // Transfer the balance to the replacement balances[replacement] = balances[original]; balances[original] = 0; emit VerifiedAddressSuperseded(original, replacement, msg.sender); } /** * @dev Approve the passed address to spend the specified number 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 tokens The number of tokens of tokens to be spent. */ function approve(address spender, uint256 tokens) external isUnlocked isNotCancelled(msg.sender) returns (bool) { require(shareholders.exists(msg.sender), "Must be a shareholder to approve token transfer"); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } /** * @dev Set the issuer address. * @param newIssuer The address of the issuer. */ function setIssuer(address newIssuer) external isUnlocked onlyOwner { issuer = newIssuer; emit IssuerSet(issuer, newIssuer); } /** * @dev Sets the compliance contract address to use during transfers. * @param newComplianceAddress The address of the compliance contract. */ function setCompliance(address newComplianceAddress) external isUnlocked onlyOwner { compliance = Compliance(newComplianceAddress); } // -------------------------------- Getters -------------------------------- /** * @dev Returns the total token supply * @return total number of tokens in existence */ function totalSupply() external view returns (uint256) { return totalSupplyTokens; } /** * @dev Gets the balance of the specified address. * @param addr The address to query the the balance of. * @return An uint256 representing the tokens owned by the passed address. */ function balanceOf(address addr) external view returns (uint256) { return balances[addr]; } /** * @dev Gets the number of tokens that an owner has allowed the spender to transfer. * @param addrOwner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the number of tokens still available for the spender. */ function allowance(address addrOwner, address spender) external view returns (uint256) { return allowed[addrOwner][spender]; } /** * By counting the number of token holders using 'holderCount' * you can retrieve the complete list of token holders, one at a time. * It MUST throw if 'index >= holderCount()'. * @dev Returns the holder at the given index. * @param index The zero-based index of the holder. * @return the address of the token holder with the given index. */ function holderAt(int256 index) external view returns (address){ return shareholders.at(index); } /** * @dev Checks to see if the supplied address is a share holder. * @param addr The address to check. * @return true if the supplied address owns a token. */ function isHolder(address addr) external view returns (bool) { return shareholders.exists(addr); } /** * @dev Checks to see if the supplied address was superseded. * @param addr The address to check. * @return true if the supplied address was superseded by another address. */ function isSuperseded(address addr) external view returns (bool) { return cancellations[addr] != ZERO_ADDRESS; } /** * Gets the most recent address, given a superseded one. * Addresses may be superseded multiple times, so this function needs to * follow the chain of addresses until it reaches the final, verified address. * @param addr The superseded address. * @return the verified address that ultimately holds the share. */ function getSuperseded(address addr) external view returns (address) { require(addr != ZERO_ADDRESS, "Non-zero address required"); address candidate = cancellations[addr]; if (candidate == ZERO_ADDRESS) { return ZERO_ADDRESS; } return candidate; } // -------------------------------- Private -------------------------------- /** * @dev Checks if a transfer/override may take place between the two accounts. * * Validates that the transfer can take place. * - Ensure the 'to' address is not cancelled * - Ensure the transfer is compliant * @param from The sender address. * @param to The recipient address. * @param tokens The number of tokens being transferred. * @param isOverride If this is a transfer override * @return If the transfer can take place. */ function canTransfer(address from, address to, uint256 tokens, bool isOverride) private isNotCancelled(to) returns (bool) { // Don't allow overrides and ignore compliance rules when compliance not set. if (address(compliance) == ZERO_ADDRESS) { return !isOverride; } // Ensure the override is valid, or that the transfer is compliant. if (isOverride) { return compliance.canOverride(msg.sender, from, to, tokens); } else { return compliance.canTransfer(msg.sender, from, to, tokens); } } /** * @dev Transfers tokens from one address to another * @param from The sender address. * @param to The recipient address. * @param tokens The number of tokens being transferred. */ function transferTokens(address from, address to, uint256 tokens) private { // Update balances balances[from] = balances[from].subtract(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); // Adds the shareholder if they don't already exist. if (balances[to] > 0 && shareholders.append(to)) { emit ShareholderAdded(to); } // Remove the shareholder if they no longer hold tokens. if (balances[from] == 0 && shareholders.remove(from)) { emit ShareholderRemoved(from); } } }
* @dev Sets the compliance contract address to use during transfers. @param newComplianceAddress The address of the compliance contract./
function setCompliance(address newComplianceAddress) external isUnlocked onlyOwner { compliance = Compliance(newComplianceAddress); }
1,061,270
[ 1, 2785, 326, 29443, 6835, 1758, 358, 999, 4982, 29375, 18, 282, 394, 16687, 1887, 1021, 1758, 434, 326, 29443, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 16687, 12, 2867, 394, 16687, 1887, 13, 203, 565, 3903, 203, 565, 353, 7087, 329, 203, 565, 1338, 5541, 288, 203, 3639, 29443, 273, 1286, 10671, 12, 2704, 16687, 1887, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // 'istake' 'istake' Smart Contract // // Symbol : istake // Name : istake // Total supply: 50,000 // Decimals : 18 // // // //The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract istake is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "istake"; name = "istake"; decimals = 18; _totalSupply = 50000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes 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); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and a fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract istake is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "istake"; name = "istake"; decimals = 18; _totalSupply = 50000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes 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; } function () external payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1,671,457
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 279, 5499, 14467, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 19165, 911, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 376, 911, 14432, 203, 3639, 508, 273, 315, 376, 911, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 1381, 2787, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 3410, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 18, 1717, 12, 70, 26488, 63, 2867, 12, 20, 13, 19226, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 1476, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 2 ]
pragma solidity >=0.5.0 <0.6.0; import '../../libs/lifecycle/LockableDestroyable.sol'; import '../IRegistry.sol'; import './IBrokerDealerRegistry.sol'; /** * @title BrokerDealer Registry * */ contract BrokerDealerRegistry is IBrokerDealerRegistry, LockableDestroyable { IRegistry public registry; uint8 constant private CUSTODIAN = 1; // Registry, custodian kind uint8 constant private CUSTODIAL_ACCOUNT = 2; // Registry, custodian kind uint8 constant private BROKER_DEALER = 3; // Registry, broker-dealer kind // ------------------------------- Modifiers ------------------------------- modifier onlyCustodian() { require(registry.accountKindExists(msg.sender, CUSTODIAN), "Custodian address required"); require(!registry.accountFrozen(msg.sender), "Custodian is frozen"); _; } modifier onlyNewAccount(address account) { require(!registry.accountExists(account), "Account already exists"); _; } modifier onlyBrokerDealersCustodian(address brokerDealer) { require(registry.accountKindExists(msg.sender, CUSTODIAN), "Custodian required"); require(msg.sender == registry.accountParent(brokerDealer), "Broker-Dealer's custodian required"); require(!registry.accountFrozen(msg.sender), "Custodian is frozen"); _; } modifier onlyAccountsCustodian(address account) { require(registry.accountKindExists(account, CUSTODIAL_ACCOUNT), "Not a custodial account"); address broker = registry.accountParent(account); require(msg.sender == registry.accountParent(broker), "Account's custodian requried"); require(!registry.accountFrozen(msg.sender), "Custodian is frozen"); _; } // ------------------------------------------------------------------------- constructor(IRegistry r) public { registry = r; } /** * Sets the registry contract address * @param r The registry contract to use */ function setRegistry(IRegistry r) onlyOwner external { registry = r; } /** * Adds a brokerDealer to the registry * Upon successful addition, the contract must emit `BrokerDealerAdded(brokerDealer)` * THROWS if the address has already been added, or is zero * @param brokerDealer The address of the broker-dealer * @param hash The hash that uniquely identifies the broker */ function add(address brokerDealer, bytes32 hash) onlyCustodian external { registry.addAccount(brokerDealer, BROKER_DEALER, false, msg.sender, hash); emit BrokerDealerAdded(brokerDealer, msg.sender); } /** * Removes a brokerDealer from the registry * Upon successful removal, the contract must emit `BrokerDealerRemoved(brokerDealer)` * THROWS if the address doesn't exist, or is zero * @param brokerDealer The address of the broker-dealer */ function remove(address brokerDealer) onlyBrokerDealersCustodian(brokerDealer) external { registry.removeAccount(brokerDealer); emit BrokerDealerRemoved(brokerDealer, msg.sender); } /** * Adds an account for the broker-dealer, using the account as the destination address * @param brokerDealer The broker-dealer to add the account for * @param account The account, and destination, to add for the broker-dealer */ function addAccount(address brokerDealer, address account) onlyNewAccount(account) onlyBrokerDealersCustodian(brokerDealer) external { bytes32 hash = registry.accountHash(brokerDealer); registry.addAccount(account, CUSTODIAL_ACCOUNT, false, brokerDealer, hash); } /** * Removes the account, along with destination, from the broker-dealer * @param account The account to remove */ function removeAccount(address account) onlyAccountsCustodian(account) external { registry.removeAccount(account); } /** * Sets whether or not an broker-dealer is frozen * Upon status change, the contract must emit `BrokerDealerFrozen(brokerDealer, frozen, custodian)` * @param brokerDealer The broker-dealer address that is being frozen * @param frozen Whether or not the custodian is frozen */ function setFrozen(address brokerDealer, bool frozen) onlyBrokerDealersCustodian(brokerDealer) external { registry.setAccountFrozen(brokerDealer, frozen); emit BrokerDealerFrozen(brokerDealer, frozen, msg.sender); } }
* @title BrokerDealer Registry/ ------------------------------- Modifiers -------------------------------
contract BrokerDealerRegistry is IBrokerDealerRegistry, LockableDestroyable { IRegistry public registry; modifier onlyCustodian() { require(registry.accountKindExists(msg.sender, CUSTODIAN), "Custodian address required"); require(!registry.accountFrozen(msg.sender), "Custodian is frozen"); _; } modifier onlyNewAccount(address account) { require(!registry.accountExists(account), "Account already exists"); _; } modifier onlyBrokerDealersCustodian(address brokerDealer) { require(registry.accountKindExists(msg.sender, CUSTODIAN), "Custodian required"); require(msg.sender == registry.accountParent(brokerDealer), "Broker-Dealer's custodian required"); require(!registry.accountFrozen(msg.sender), "Custodian is frozen"); _; } modifier onlyAccountsCustodian(address account) { require(registry.accountKindExists(account, CUSTODIAL_ACCOUNT), "Not a custodial account"); address broker = registry.accountParent(account); require(msg.sender == registry.accountParent(broker), "Account's custodian requried"); require(!registry.accountFrozen(msg.sender), "Custodian is frozen"); _; } constructor(IRegistry r) public { registry = r; } function setRegistry(IRegistry r) onlyOwner external { registry = r; } function add(address brokerDealer, bytes32 hash) onlyCustodian external { registry.addAccount(brokerDealer, BROKER_DEALER, false, msg.sender, hash); emit BrokerDealerAdded(brokerDealer, msg.sender); } function remove(address brokerDealer) onlyBrokerDealersCustodian(brokerDealer) external { registry.removeAccount(brokerDealer); emit BrokerDealerRemoved(brokerDealer, msg.sender); } function addAccount(address brokerDealer, address account) onlyNewAccount(account) onlyBrokerDealersCustodian(brokerDealer) external { bytes32 hash = registry.accountHash(brokerDealer); registry.addAccount(account, CUSTODIAL_ACCOUNT, false, brokerDealer, hash); } function removeAccount(address account) onlyAccountsCustodian(account) external { registry.removeAccount(account); } function setFrozen(address brokerDealer, bool frozen) onlyBrokerDealersCustodian(brokerDealer) external { registry.setAccountFrozen(brokerDealer, frozen); emit BrokerDealerFrozen(brokerDealer, frozen, msg.sender); } }
12,916,134
[ 1, 11194, 10889, 5438, 19, 12146, 17908, 3431, 3383, 12146, 17908, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 20438, 10889, 4243, 353, 467, 11194, 10889, 4243, 16, 3488, 429, 10740, 429, 288, 203, 565, 467, 4243, 1071, 4023, 31, 203, 203, 203, 565, 9606, 1338, 39, 641, 369, 2779, 1435, 288, 203, 3639, 2583, 12, 9893, 18, 4631, 5677, 4002, 12, 3576, 18, 15330, 16, 385, 5996, 1212, 21634, 3631, 315, 39, 641, 369, 2779, 1758, 1931, 8863, 203, 3639, 2583, 12, 5, 9893, 18, 4631, 42, 9808, 12, 3576, 18, 15330, 3631, 315, 39, 641, 369, 2779, 353, 12810, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 1908, 3032, 12, 2867, 2236, 13, 288, 203, 3639, 2583, 12, 5, 9893, 18, 4631, 4002, 12, 4631, 3631, 315, 3032, 1818, 1704, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 11194, 758, 287, 414, 39, 641, 369, 2779, 12, 2867, 8625, 10889, 13, 288, 203, 3639, 2583, 12, 9893, 18, 4631, 5677, 4002, 12, 3576, 18, 15330, 16, 385, 5996, 1212, 21634, 3631, 315, 39, 641, 369, 2779, 1931, 8863, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 4023, 18, 4631, 3054, 12, 21722, 10889, 3631, 315, 11194, 17, 10889, 1807, 276, 641, 369, 2779, 1931, 8863, 203, 3639, 2583, 12, 5, 9893, 18, 4631, 42, 9808, 12, 3576, 18, 15330, 3631, 315, 39, 641, 369, 2779, 353, 12810, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 13971, 39, 641, 369, 2779, 12, 2867, 2236, 13, 288, 203, 3639, 2583, 12, 9893, 18, 4631, 5677, 4002, 12, 2 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; // File: contracts/external/Strings.sol // OpenZeppelin Contracts v4.3.2 (utils/Strings.sol) /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @uniswap/v3-core/contracts/libraries/FullMath.sol /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // File: @uniswap/v3-core/contracts/libraries/TickMath.sol /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // File: @uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // File: @uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } } // File: @uniswap/v3-periphery/contracts/libraries/PoolAddress.sol /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // File: @uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol /// @title Oracle library /// @notice Provides functions to integrate with V3 pool oracle library OracleLibrary { /// @notice Fetches time-weighted average tick using Uniswap V3 oracle /// @param pool Address of Uniswap V3 pool that we want to observe /// @param period Number of seconds in the past to start calculating time-weighted average /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) { require(period != 0, 'BP'); uint32[] memory secondAgos = new uint32[](2); secondAgos[0] = period; secondAgos[1] = 0; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / period); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) timeWeightedAverageTick--; } /// @notice Given a tick and a token amount, calculates the amount of token received in exchange /// @param tick Tick value used to calculate the quote /// @param baseAmount Amount of token to be converted /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } /// @notice Given a pool, it returns the number of seconds ago of the oldest stored observation /// @param pool Address of Uniswap V3 pool that we want to observe /// @return The number of seconds ago of the oldest observation stored for the pool function getOldestObservationSecondsAgo(address pool) internal view returns (uint32) { (, , uint16 observationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0(); require(observationCardinality > 0, 'NI'); (uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(pool).observations((observationIndex + 1) % observationCardinality); // The next index might not be initialized if the cardinality is in the process of increasing // In this case the oldest observation is always in index 0 if (!initialized) { (observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0); } return uint32(block.timestamp) - observationTimestamp; } } // File: ../contracts/Collection.sol //import "./ICollection.sol"; /** * @title Collection * * Devs: currently `is ICollection*` is commented out because I haven't found a good way * to share the interface contract between different solidity versions. The Collection * contracts are compiled with solidity 0.7 because of the dependency on the uniswap * oracle lib, and the main NFT contracts are compiled with solidity 0.8 because it * uses the latest openzeppelin versions of the contract. The interface is used by * both set of contracts which currently makes the compilation fail when used by both * sets of contracts. */ contract Collection/* is ICollection*/ { using Strings for uint; using OracleLibrary for address; uint32 public constant CURRENT_PRICE_SECONDS_AGO = 5 minutes; uint32 public constant PREVIOUS_PRICE_SECONDS_AGO = 12 hours; IUniswapV3Pool immutable public uniswapPool; uint32 immutable public /*override*/ collectionID; uint128 immutable public baseAmount; string public baseTokenURI; int[] public priceLevels; int[] public relativeLevels; constructor( uint32 _collectionID, string memory _baseTokenURI, IUniswapV3Pool _uniswapPool, uint128 _baseAmount, int[] memory _priceLevels, int[] memory _relativeLevels ) { collectionID = _collectionID; baseTokenURI = _baseTokenURI; uniswapPool = _uniswapPool; baseAmount = _baseAmount; priceLevels = _priceLevels; relativeLevels = _relativeLevels; } function tokenURI(uint256 tokenId) //override public view returns (string memory) { // Data format: // - 4 bytes: collection ID // - 16 bytes: base price // - 12 bytes: id require(uint32((tokenId >> 224) & 0xFFFFFFFF) == collectionID, "inconsistent collection id"); uint basePrice = (tokenId >> 96) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint currentPrice = getPrice(CURRENT_PRICE_SECONDS_AGO); uint previousPrice = getPrice(PREVIOUS_PRICE_SECONDS_AGO); uint baseLevel = getBaseLevel(currentPrice, basePrice); uint relativeLevel = getRelativeLevel(currentPrice, previousPrice); return string( abi.encodePacked( baseTokenURI, "/", tokenId.toString(), "/", baseLevel.toString(), "_", relativeLevel.toString(), "/metadata.json" ) ); } function getPrice(uint32 secondsAgo) public view returns (uint price) { // Currently returns the AVERAGE price over the passed in duration. // Can be changed but I think this should work well. int24 tick = address(uniswapPool).consult(secondsAgo); price = OracleLibrary.getQuoteAtTick( tick, baseAmount, uniswapPool.token1(), uniswapPool.token0() ); } function getRelativeLevel(uint currentPrice, uint previousPrice) public view returns (uint level) { int change = int(currentPrice) - int(previousPrice); uint basePrice = (currentPrice >= previousPrice) ? previousPrice : currentPrice; if (basePrice != 0) { change = (change * 100) / int(basePrice); } return getRangeLevel(relativeLevels, change); } function getBaseLevel(uint currentPrice, uint basePrice) public view returns (uint level) { int change = int(currentPrice) - int(basePrice); return getRangeLevel(priceLevels, change); } function getRangeLevel(int[] memory levels, int value) public pure returns (uint level) { for (uint i = 0; i < levels.length; i++) { if (value < levels[i]) { return i; } } return levels.length; } }
override Data format: - 4 bytes: collection ID - 16 bytes: base price - 12 bytes: id
function tokenURI(uint256 tokenId) public view returns (string memory) { require(uint32((tokenId >> 224) & 0xFFFFFFFF) == collectionID, "inconsistent collection id"); uint basePrice = (tokenId >> 96) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; uint currentPrice = getPrice(CURRENT_PRICE_SECONDS_AGO); uint previousPrice = getPrice(PREVIOUS_PRICE_SECONDS_AGO); uint baseLevel = getBaseLevel(currentPrice, basePrice); uint relativeLevel = getRelativeLevel(currentPrice, previousPrice); return string( abi.encodePacked( baseTokenURI, "/", tokenId.toString(), "/", baseLevel.toString(), "_", relativeLevel.toString(), "/metadata.json" ) ); }
6,072,867
[ 1, 10601, 1910, 740, 30, 300, 225, 1059, 1731, 30, 1849, 1599, 300, 2872, 1731, 30, 1026, 6205, 300, 2593, 1731, 30, 612, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 1080, 3778, 13, 203, 565, 288, 203, 3639, 2583, 12, 11890, 1578, 12443, 2316, 548, 1671, 576, 3247, 13, 473, 374, 28949, 13, 422, 1849, 734, 16, 315, 267, 16952, 1849, 612, 8863, 203, 203, 3639, 2254, 1026, 5147, 273, 261, 2316, 548, 1671, 19332, 13, 473, 374, 6356, 8998, 8998, 8998, 8998, 8998, 8998, 18343, 31, 203, 203, 3639, 2254, 783, 5147, 273, 25930, 12, 15487, 67, 7698, 1441, 67, 11609, 67, 1781, 51, 1769, 203, 3639, 2254, 2416, 5147, 273, 25930, 12, 3670, 4136, 21667, 67, 7698, 1441, 67, 11609, 67, 1781, 51, 1769, 203, 203, 3639, 2254, 1026, 2355, 273, 8297, 2355, 12, 2972, 5147, 16, 1026, 5147, 1769, 203, 3639, 2254, 3632, 2355, 273, 336, 8574, 2355, 12, 2972, 5147, 16, 2416, 5147, 1769, 203, 203, 3639, 327, 533, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 1026, 1345, 3098, 16, 203, 7734, 2206, 3113, 203, 7734, 1147, 548, 18, 10492, 9334, 203, 7734, 2206, 3113, 203, 7734, 1026, 2355, 18, 10492, 9334, 203, 7734, 4192, 3113, 203, 7734, 3632, 2355, 18, 10492, 9334, 203, 7734, 2206, 4165, 18, 1977, 6, 203, 5411, 262, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "./Graph.sol"; import "./SafeMath.sol"; import "./Agreement.sol"; contract MainGraph { using SafeMath for uint256; int256 public constant MAX_INT = int256(~(uint256(1) << 255)); uint256 constant MAX_UINT = ~uint256(0); address public netereumAddress; address[] confirmedCoordinators; uint256 public numberOfCoordinators = 0; // constructor(address _netereumAddress) public // { // netereumAddress = _netereumAddress; // } function setNetereum(address addr) public { netereumAddress = addr; } mapping(address => Graph.Node) public nodes; mapping(uint256 => Graph.Edge) public edges; uint256 public numberOfNodes; uint256 public numberOfEdges; function addNode(address coordinator) public { require(msg.sender == netereumAddress); nodes[coordinator].coordinator = coordinator; numberOfNodes ++; nodes[coordinator].isInserted = true; confirmedCoordinators.push(coordinator); numberOfCoordinators++; } mapping(address => mapping(address => uint256)) public edgeIndex;/* a mapping that maps a combined key containing the source coordinator and the destination coordinator to the index + 1 of that edge in the edges array*/ function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) // if flag = 0, then the function has been called normally otherwise the edge may create a negative cycle thus an additional algorithm will be executed internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; if (index == 0)//it means that this edge is a new edge { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; if (index2 == edges[index].numberOfWeights)// if the associated weight element was not found { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { //running the bellman ford with source = sourceCoordinator while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); //SHOULD BE MODIFIED } /*the Bellman-Ford algorithm for finding the shortest path and distance between our source coordinator and destination coordinator*/ for (uint i = 1; i < numberOfNodes; i++)// we can use number of coordinators instead of number of nodes { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; address [] memory cycle = new address[](2 * numberOfEdges);//array of the indexes of the edges uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; // path.push(tempDestination); // path.push(nodes[tempDestination].parent); tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++;//for getting the upper bound of the result in the division } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } // pathAmounts[cycleLength - 1 - i] = transferAmount; if(i == 1) break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; // if(edges[index].weights[edges[index].minIndex].exchangeRate % 1000000 != 0) // transferAmount ++; removeEdge(index,transferAmount,address(0),uint8(0)); } // pathAmounts[pathLength / 2] = transferAmount; } } //break; } } } } } uint256 public indexxx = 20; function wrappedAddEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress) public { require(msg.sender == netereumAddress); require(nodes[sourceCoordinator].isInserted == true, "3"); require(nodes[destinationCoordinator].isInserted == true, "4"); addEdge(sourceCoordinator,destinationCoordinator, exchangeRate, exchangeRateLog, reverse, sourceAmount, agreementAddress , 1); } //app.wrappedAddEdge('0x3c28ee5a77b6aa58c79E10C8416f32C8d916705a','0xfBa507d4eAc1A2D4144335C793Edae54d212fa22',1000000000,2000000,8,15687229690,'0x3c28ee5a77b6aa58c79E10C8416f32C8d916705a') function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { //swapping the current edge with the last edge and decrementing the number of edges edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; // code for swapping the weights of the desired edge and the last edge for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function wrappedRemoveEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) public returns(uint256) { require(msg.sender == netereumAddress); return removeEdge(index,sourceAmount,agreementAddress,flag); } address[] public path; uint256 public amounttt; mapping(uint256 => uint256) public pathAmounts; uint256 public pathLength; function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); // for(uint256 i = numberOfAgreements - 1;i >= 0; i--)//removing the agreements and edges that have expired // { // if(agreements[i].expireTime() < block.timestamp) // { // removeEdge(0,0,address(agreements[i]),2); //// agreementStatus[address(agreements[i])] = 3;//expired //// agreements[i] = agreements[numberOfAgreements - 1];//needs to be Checkeddddd //// agreements.pop(); // } // if(i == 0) // break; // } if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; if(i == 1)// because of i being uint, when i == 1 the next iteration will start with i = MAX_uint break; } } pathLength = 0; uint256 pathStart = 0;// the index that the path for the current iteration starts uint256 sum = 0; uint256 amount = 0;// the amount that the sender has to pay if the transaction is accepted by the system while (sum < _sellerCost) { // initializing the distance of the nodes for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); //SHOULD BE MODIFIED } /*the Bellman-Ford algorithm for finding the shortest path and distance between our source coordinator and destination coordinator*/ for (uint i = 1; i < numberOfNodes; i++)// we can use number of coordinators instead of number of nodes { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } // /* backtracking from the destination Coordinator to the source Coordinator to // find the maximum amount that can be transferred through this path*/ uint256 transferAmount = 0;// the amount that the current path can transfer uint256 minAmount = 0; // the minimum amount that can be sent to the receiver address tempDestination = _sellerCoordinator; require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; // backtracking again to reduce the weights of the edges for(uint256 i = pathLength - 1;i >= pathStart + 1 ; i-=2) { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } if (amount > _buyerCost || virtual)//changing the graph to the previous state //BE CAREFUL HEREEEEEE { // neutralizing the effects that our computation had on the graph for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function getParent(address addr) public returns(address) { return nodes[addr].parent; } function getMinIndex(uint256 i) public returns(uint256) { return edges[i].minIndex; } function getNumberOfWeights(uint256 i) public returns(uint256) { return edges[i].numberOfWeights; } function getAmount(uint256 i,uint256 j) public returns(uint256) { return edges[i].weights[j].sourceAmount; } function getRate(uint256 i,uint256 j) public returns(uint256) { return edges[i].weights[j].exchangeRate; } function getLog(uint256 i,uint256 j) public returns(int256) { return edges[i].weights[j].exchangeRateLog; } }
constructor(address _netereumAddress) public { netereumAddress = _netereumAddress; }
contract MainGraph { using SafeMath for uint256; int256 public constant MAX_INT = int256(~(uint256(1) << 255)); uint256 constant MAX_UINT = ~uint256(0); address public netereumAddress; address[] confirmedCoordinators; uint256 public numberOfCoordinators = 0; function setNetereum(address addr) public { netereumAddress = addr; } mapping(address => Graph.Node) public nodes; mapping(uint256 => Graph.Edge) public edges; uint256 public numberOfNodes; uint256 public numberOfEdges; function addNode(address coordinator) public { require(msg.sender == netereumAddress); nodes[coordinator].coordinator = coordinator; numberOfNodes ++; nodes[coordinator].isInserted = true; confirmedCoordinators.push(coordinator); numberOfCoordinators++; } mapping(address => mapping(address => uint256)) public edgeIndex;/* a mapping that maps a combined key containing the source coordinator and the destination coordinator to the index + 1 of that edge in the edges array*/ function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; } our source coordinator and destination coordinator*/ function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; if(i == 1) function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; removeEdge(index,transferAmount,address(0),uint8(0)); } } } } } } uint256 public indexxx = 20; } } function wrappedAddEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress) public { require(msg.sender == netereumAddress); require(nodes[sourceCoordinator].isInserted == true, "3"); require(nodes[destinationCoordinator].isInserted == true, "4"); addEdge(sourceCoordinator,destinationCoordinator, exchangeRate, exchangeRateLog, reverse, sourceAmount, agreementAddress , 1); } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function wrappedRemoveEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) public returns(uint256) { require(msg.sender == netereumAddress); return removeEdge(index,sourceAmount,agreementAddress,flag); } address[] public path; uint256 public amounttt; mapping(uint256 => uint256) public pathAmounts; uint256 public pathLength; function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } } our source coordinator and destination coordinator*/ function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } address tempDestination = _sellerCoordinator; function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } for(uint256 i = pathLength - 1;i >= pathStart + 1 ; i-=2) function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; break; } } pathLength = 0; uint256 sum = 0; while (sum < _sellerCost) { for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } { for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function getParent(address addr) public returns(address) { return nodes[addr].parent; } function getMinIndex(uint256 i) public returns(uint256) { return edges[i].minIndex; } function getNumberOfWeights(uint256 i) public returns(uint256) { return edges[i].numberOfWeights; } function getAmount(uint256 i,uint256 j) public returns(uint256) { return edges[i].weights[j].sourceAmount; } function getRate(uint256 i,uint256 j) public returns(uint256) { return edges[i].weights[j].exchangeRate; } function getLog(uint256 i,uint256 j) public returns(int256) { return edges[i].weights[j].exchangeRateLog; } }
12,652,413
[ 1, 12316, 12, 2867, 389, 2758, 822, 379, 1887, 13, 1071, 565, 288, 3639, 2901, 822, 379, 1887, 273, 389, 2758, 822, 379, 1887, 31, 565, 289, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 12740, 4137, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 509, 5034, 1071, 5381, 4552, 67, 3217, 273, 509, 5034, 12, 98, 12, 11890, 5034, 12, 21, 13, 2296, 4561, 10019, 203, 565, 2254, 5034, 5381, 4552, 67, 57, 3217, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 1758, 1071, 2901, 822, 379, 1887, 31, 203, 565, 1758, 8526, 19979, 5401, 30425, 31, 203, 565, 2254, 5034, 1071, 7922, 5401, 30425, 273, 374, 31, 203, 565, 445, 444, 7308, 822, 379, 12, 2867, 3091, 13, 1071, 203, 565, 288, 203, 3639, 2901, 822, 379, 1887, 273, 3091, 31, 203, 565, 289, 203, 565, 2874, 12, 2867, 516, 5601, 18, 907, 13, 1071, 225, 2199, 31, 203, 565, 2874, 12, 11890, 5034, 516, 5601, 18, 6098, 13, 225, 1071, 5231, 31, 203, 565, 2254, 5034, 1071, 7922, 3205, 31, 203, 565, 2254, 5034, 1071, 7922, 10697, 31, 203, 565, 445, 23063, 12, 2867, 24794, 13, 1071, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 2901, 822, 379, 1887, 1769, 203, 3639, 2199, 63, 5732, 4240, 8009, 5732, 4240, 273, 24794, 31, 203, 3639, 7922, 3205, 965, 31, 203, 3639, 2199, 63, 5732, 4240, 8009, 291, 27329, 273, 638, 31, 203, 3639, 19979, 5401, 30425, 18, 6206, 12, 5732, 4240, 1769, 203, 203, 3639, 7922, 5401, 30425, 9904, 31, 203, 565, 289, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1071, 225, 3591, 1016, 31, 20308, 279, 2874, 716, 7565, 279, 8224, 2 ]
./full_match/1/0x00000000000061aD8EE190710508A818aE5325C3/sources/src/dependencies.sol
* @dev Standard math utilities missing in the Solidity language./
library Math { function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } }
9,759,442
[ 1, 8336, 4233, 22538, 3315, 316, 326, 348, 7953, 560, 2653, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 2361, 288, 203, 565, 445, 613, 2163, 12, 11890, 5034, 460, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 563, 273, 374, 31, 203, 3639, 22893, 288, 203, 5411, 309, 261, 1132, 1545, 1728, 2826, 5178, 13, 288, 203, 7734, 460, 9531, 1728, 2826, 5178, 31, 203, 7734, 563, 1011, 5178, 31, 203, 5411, 289, 203, 5411, 309, 261, 1132, 1545, 1728, 2826, 3847, 13, 288, 203, 7734, 460, 9531, 1728, 2826, 3847, 31, 203, 7734, 563, 1011, 3847, 31, 203, 5411, 289, 203, 5411, 309, 261, 1132, 1545, 1728, 2826, 2872, 13, 288, 203, 7734, 460, 9531, 1728, 2826, 2872, 31, 203, 7734, 563, 1011, 2872, 31, 203, 5411, 289, 203, 5411, 309, 261, 1132, 1545, 1728, 2826, 1725, 13, 288, 203, 7734, 460, 9531, 1728, 2826, 1725, 31, 203, 7734, 563, 1011, 1725, 31, 203, 5411, 289, 203, 5411, 309, 261, 1132, 1545, 1728, 2826, 1059, 13, 288, 203, 7734, 460, 9531, 1728, 2826, 1059, 31, 203, 7734, 563, 1011, 1059, 31, 203, 5411, 289, 203, 5411, 309, 261, 1132, 1545, 1728, 2826, 576, 13, 288, 203, 7734, 460, 9531, 1728, 2826, 576, 31, 203, 7734, 563, 1011, 576, 31, 203, 5411, 289, 203, 5411, 309, 261, 1132, 1545, 1728, 2826, 404, 13, 288, 203, 7734, 563, 1011, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 563, 31, 203, 565, 289, 203, 565, 445, 613, 2163, 12, 11890, 5034, 460, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 2 ]
pragma solidity ^0.4.11; import "./AccountId.sol"; import "./Lingotts_token.sol"; // Per country contract AccountIdFactory { struct Account { string username; address ownerAddress; address id; bool deleted; } address public owner; modifier onlyOwner() { if(msg.sender != owner) revert(); _; } address public tokenAddress; Account[] public accountList; mapping(bytes32 => bool) public existsAccount; // username mapping(bytes32 => uint) accounts; // username to index event NewAccount(string username, address id); function AccountIdFactory (uint tokenAmmount) { tokenAddress = new Lingotts(tokenAmmount); owner = msg.sender; } // Creates and registers a new ID if it's not already created function create(string username) returns(address accountAddress) { if(!existsAccount[sha3(username)]) { accountAddress = new AccountId(username, msg.sender); register(username, accountAddress); } else { accountList[accounts[sha3(username)]].deleted = false; accountAddress = getAccount(username).id; } NewAccount(username, accountAddress); } // Logical deletion function remove(string username) onlyOwner { //ADD MODIFIER to allow only if sender is the owner of the contract beign deleted accountList[accounts[sha3(username)]].deleted = true; } // Returns an accountId if exists and has not been deleted. 0x0... otherwise function getAccountId(string username) constant returns(address id) { if(existsAccount[sha3(username)] && !getAccount(username).deleted) id = getAccount(username).id; else id = address(0); } // Number of elements in the AccountList array function getNumAccounts() constant returns(uint) { return accountList.length; } // Registers a new ID function register(string _username, address accountAddress) internal { accountList.push(Account({ username: _username, ownerAddress: msg.sender, id: accountAddress, deleted: false })); accounts[sha3(_username)] = accountList.length - 1; existsAccount[sha3(_username)] = true; } function getAccount(string username) internal constant returns(Account) { return accountList[accounts[sha3(username)]]; } function isUser(string userName) constant returns(uint) { if(existsAccount[sha3(userName)] && !getAccount(userName).deleted){ if(accountList[accounts[sha3(userName)]].ownerAddress != msg.sender) return 0; else return 1; } return 2; } function getUserExternal(string _userName) constant returns(string, address, bool) { if(existsAccount[sha3(_userName)] && !getAccount(_userName).deleted){ return (accountList[accounts[sha3(_userName)]].username, accountList[accounts[sha3(_userName)]].id, accountList[accounts[sha3(_userName)]].deleted); }else{ return ("User not found", 0x0, false); } } }
Creates and registers a new ID if it's not already created
function create(string username) returns(address accountAddress) { if(!existsAccount[sha3(username)]) { accountAddress = new AccountId(username, msg.sender); register(username, accountAddress); accountList[accounts[sha3(username)]].deleted = false; accountAddress = getAccount(username).id; } NewAccount(username, accountAddress); }
6,408,028
[ 1, 2729, 471, 10285, 279, 394, 1599, 309, 518, 1807, 486, 1818, 2522, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 752, 12, 1080, 2718, 13, 203, 225, 1135, 12, 2867, 2236, 1887, 13, 203, 225, 288, 203, 203, 565, 309, 12, 5, 1808, 3032, 63, 7819, 23, 12, 5053, 13, 5717, 288, 203, 1377, 2236, 1887, 273, 394, 6590, 548, 12, 5053, 16, 1234, 18, 15330, 1769, 203, 203, 1377, 1744, 12, 5053, 16, 2236, 1887, 1769, 203, 1377, 2236, 682, 63, 13739, 63, 7819, 23, 12, 5053, 25887, 8009, 8600, 273, 629, 31, 203, 203, 1377, 2236, 1887, 273, 23393, 12, 5053, 2934, 350, 31, 203, 565, 289, 203, 203, 565, 1166, 3032, 12, 5053, 16, 2236, 1887, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xB44Ae12e3245A3FbdD9445c536ef568a702e77DF/sources/contracts/PhatRollupAnchor.sol
The handler to be called when a message is received from a Phat Contract Reverting in this function resulting the revert of the offchain rollup transaction. Returns the prefix of the queue related keys The queue is persisted in the rollup kv store with all its keys prefixed. This function returns the prefix.
function _onMessageReceived(bytes calldata action) internal virtual; function queueGetPrefix() public pure returns (bytes memory) { return QUEUE_PREFIX; }
845,153
[ 1, 1986, 1838, 358, 506, 2566, 1347, 279, 883, 353, 5079, 628, 279, 4360, 270, 13456, 868, 1097, 310, 316, 333, 445, 8156, 326, 15226, 434, 326, 3397, 5639, 5824, 416, 2492, 18, 2860, 326, 1633, 434, 326, 2389, 3746, 1311, 1021, 2389, 353, 14249, 316, 326, 5824, 416, 6047, 1707, 598, 777, 2097, 1311, 12829, 18, 1220, 445, 1135, 326, 1633, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 265, 1079, 8872, 12, 3890, 745, 892, 1301, 13, 2713, 5024, 31, 203, 203, 565, 445, 2389, 967, 2244, 1435, 1071, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 31600, 67, 6307, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // 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); } } // 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: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _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 {} } // File: contracts/CryptoKidneys.sol // Amended by HashLips /** !Disclaimer! These contracts have been used to create tutorials, and was created for the purpose to teach people how to create smart contracts on the blockchain. please review this code on your own before using any of the following code for production. The developer will not be responsible or liable for all loss or damage whatsoever caused by you participating in any way in the experimental code, whether putting money into the contract or using the code for your own project. */ pragma solidity >=0.7.0 <0.9.0; contract CryptoKidneys is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256 public cost = 0 ether; uint256 public maxSupply = 5555; uint256 public maxMintAmountPerTx = 5; bool public paused = true; bool public revealed = false; constructor() ERC721("Crypto Kidneys", "CK") { setHiddenMetadataUri("ipfs://QmT3itH2vXkzmAxHuPfhPvqJKbhX9r9L54gPoujWJBBwZb/hidden.json"); } modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); _mintLoop(msg.sender, _mintAmount); } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function withdraw() public onlyOwner { // This will transfer the remaining contract balance to the owner. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); // ============================================================================= } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
File: contracts/CryptoKidneys.sol Amended by HashLips*/
contract CryptoKidneys is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = ""; string public uriSuffix = ".json"; string public hiddenMetadataUri; uint256 public cost = 0 ether; uint256 public maxSupply = 5555; uint256 public maxMintAmountPerTx = 5; bool public paused = true; bool public revealed = false; function _beforeTokenTransfer( address from, address to, uint256 tokenId function _afterTokenTransfer( address from, address to, uint256 tokenId } !Disclaimer! These contracts have been used to create tutorials, and was created for the purpose to teach people how to create smart contracts on the blockchain. please review this code on your own before using any of the following code for production. The developer will not be responsible or liable for all loss or damage whatsoever caused by you participating in any way in the experimental code, whether putting money into the contract or using the code for your own project. pragma solidity >=0.7.0 <0.9.0; constructor() ERC721("Crypto Kidneys", "CK") { } modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); _mintLoop(msg.sender, _mintAmount); } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function withdraw() public onlyOwner { require(os); } (bool os, ) = payable(owner()).call{value: address(this).balance}(""); function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
14,669,672
[ 1, 812, 30, 20092, 19, 18048, 47, 350, 82, 402, 87, 18, 18281, 3986, 3934, 635, 2474, 48, 7146, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 15629, 47, 350, 82, 402, 87, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 225, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 225, 9354, 87, 18, 4789, 3238, 14467, 31, 203, 203, 225, 533, 1071, 2003, 2244, 273, 1408, 31, 203, 225, 533, 1071, 2003, 5791, 273, 3552, 1977, 14432, 203, 225, 533, 1071, 5949, 2277, 3006, 31, 203, 21281, 225, 2254, 5034, 1071, 6991, 273, 374, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 943, 3088, 1283, 273, 1381, 2539, 25, 31, 203, 225, 2254, 5034, 1071, 943, 49, 474, 6275, 2173, 4188, 273, 1381, 31, 203, 203, 225, 1426, 1071, 17781, 273, 638, 31, 203, 225, 1426, 1071, 283, 537, 18931, 273, 629, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 203, 203, 565, 401, 1669, 830, 69, 4417, 5, 203, 565, 8646, 20092, 1240, 2118, 1399, 358, 752, 268, 22378, 87, 16, 203, 565, 471, 1703, 2522, 364, 326, 13115, 358, 6489, 497, 16951, 203, 565, 3661, 358, 752, 13706, 20092, 603, 326, 16766, 18, 203, 565, 9582, 10725, 333, 981, 603, 3433, 4953, 1865, 1450, 1281, 434, 203, 565, 326, 3751, 981, 364, 12449, 18, 203, 565, 2 ]
pragma solidity >=0.6.2 <0.7.0; pragma experimental ABIEncoderV2; contract CharityToken { string public name = "Charity Token"; // Sets the name for display purposes string public symbol = "CHT"; // Sets the symbol for display purposes uint256 public totalSupply_ = 100000000; //Updates total supply (100000 for example) uint8 public decimals = 18; address burnAddress = 0x0000000000000000000000000000000000000000; // Amount of decimals for display purposes address owner; uint8 voteThreshold = 200; event Transfer( address indexed _from, address indexed _to, uint256 _value ); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); struct CharityAccount { uint target_amount; string[] votes; string description; string proof; uint raised_amount; uint vote_count; bool is_activated; bool is_closed; } modifier onlyOwner { require(msg.sender == owner, "Only contract owner is permitted"); _; } mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; mapping(address => CharityAccount) public charity_accounts; constructor() public { balances[msg.sender] = totalSupply_; owner = msg.sender; } /// return total amount of tokens function totalSupply() public view returns (uint256) { return totalSupply_; } /// _owner The address from which the balance will be retrieved /// return The balance function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /// sends a certain `_value` of token to `_to` from `msg.sender` function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value, "You have insufficient balance"); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } /// `msg.sender` approves `_addr` to spend a certain `_value` tokens function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// return amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// sends a certain `_value` of token to `_to` from `_from` /// on the condition it is approved by `_from` function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= balances[_from], "You have insufficient balance"); require(_value <= allowed[_from][msg.sender], "you are not permitted to send that amount"); balances[_from] -= _value; balances[_to] += _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function setCharityAccount(address charityAddress, uint256 target_amount, string memory description, string memory proof ) public returns (bool success) { // charity_accounts[charityAddress] = CharityAccount( target_amount, votes, description, proof, raised_amount, vote_count, is_activated ); charity_accounts[charityAddress].target_amount = target_amount; charity_accounts[charityAddress].description = description; charity_accounts[charityAddress].proof = proof; return true; } function getCharityAccount(address fundAddress) public view returns (CharityAccount memory c_account) { return charity_accounts[fundAddress]; } function burn(uint _value) public onlyOwner returns (bool success) { // owner = _owner; require(_value <= balances[msg.sender], "You don't have enough token to burn"); balances[msg.sender] -= _value; emit Transfer(msg.sender, burnAddress, _value); return true; } function voteAccount(address fundAddress, uint voteValue, string memory voteHash, bool is_activated) public onlyOwner returns (bool success) { require(!charity_accounts[fundAddress].is_closed, "The account is closed for voting"); charity_accounts[fundAddress].vote_count += voteValue; charity_accounts[fundAddress].votes.push(voteHash); charity_accounts[fundAddress].is_activated = is_activated; return true; } function closeAccount(address fundAddress) public onlyOwner returns (bool success) { require(charity_accounts[fundAddress].raised_amount >= charity_accounts[fundAddress].target_amount, "Account is not fully funded yet"); require(!charity_accounts[fundAddress].is_closed, "Account is already closed"); charity_accounts[fundAddress].is_closed = true; return true; } function activateAccount(address fundAddress) public onlyOwner returns (bool success) { require(charity_accounts[fundAddress].vote_count >= voteThreshold, "The threshold is not met yet"); require(!charity_accounts[fundAddress].is_closed, "The account is closed for voting"); charity_accounts[fundAddress].is_closed = true; return true; } function fundCharity(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= balances[_from], "You have insufficient balance"); require(_value <= allowed[_from][msg.sender], "You are not permitted to spend that amount"); require(charity_accounts[_to].is_activated, "The account is not activated for funding yet"); balances[_from] -= _value; balances[_to] += _value; charity_accounts[_from].raised_amount += _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } }
sends a certain `_value` of token to `_to` from `msg.sender`
function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value, "You have insufficient balance"); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; }
6,387,357
[ 1, 4661, 87, 279, 8626, 1375, 67, 1132, 68, 434, 1147, 358, 1375, 67, 869, 68, 628, 1375, 3576, 18, 15330, 68, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 70, 26488, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 16, 315, 6225, 1240, 2763, 11339, 11013, 8863, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 3947, 389, 1132, 31, 203, 3639, 324, 26488, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.7; library SafeMath { int256 constant private int256_min606 = -2**255; //inject NONSTANDARD NAMING function MUL578(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 MUL578(int256 a, int256 b) internal pure returns (int256) { //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; } require(!(a == -1 && b == int256_min606)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } function DIV266(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function DIV266(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING require(b != 0); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == int256_min606)); // This is the only case of overflow int256 c = a / b; return c; } function SUB55(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function SUB55(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } function ADD666(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function ADD666(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function MOD120(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } interface IERC20 { function TOTALSUPPLY304() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF735(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE123(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER854(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE531(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM522(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER418(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL780(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } contract ERC20Pistachio is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; // Token symbol (short) string public symbol; // Token name (Long) string public name; // Decimals (18 maximum) uint8 public decimals; constructor (address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance) public { // Initialize Contract Parameters symbol = _tokenSymbol; name = _tokenName; decimals = 18; // default decimals is going to be 18 always _MINT600(initialAccount, initialBalance); } function TOTALSUPPLY304() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF735(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE123(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER854(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER481(msg.sender, to, value); return true; } function APPROVE531(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = value; emit APPROVAL780(msg.sender, spender, value); return true; } function TRANSFERFROM522(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[from][msg.sender] = _allowed[from][msg.sender].SUB55(value); _TRANSFER481(from, to, value); emit APPROVAL780(from, msg.sender, _allowed[from][msg.sender]); return true; } function INCREASEALLOWANCE330(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD666(addedValue); emit APPROVAL780(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function DECREASEALLOWANCE446(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB55(subtractedValue); emit APPROVAL780(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _TRANSFER481(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB55(value); _balances[to] = _balances[to].ADD666(value); emit TRANSFER418(from, to, value); } function _MINT600(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD666(value); _balances[account] = _balances[account].ADD666(value); emit TRANSFER418(address(0), account, value); } function _BURN785(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB55(value); _balances[account] = _balances[account].SUB55(value); emit TRANSFER418(account, address(0), value); } function _BURNFROM615(address account, uint256 value) internal { //inject NONSTANDARD NAMING _allowed[account][msg.sender] = _allowed[account][msg.sender].SUB55(value); _BURN785(account, value); emit APPROVAL780(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Burnable is ERC20Pistachio { bool private _burnableActive; function BURN665(uint256 value) public WHENBURNABLEACTIVE644 { //inject NONSTANDARD NAMING _BURN785(msg.sender, value); } function BURNFROM948(address from, uint256 value) public WHENBURNABLEACTIVE644 { //inject NONSTANDARD NAMING _BURNFROM615(from, value); } function _SETBURNABLEACTIVE519(bool _active) internal { //inject NONSTANDARD NAMING _burnableActive = _active; } modifier WHENBURNABLEACTIVE644() { //inject NONSTANDARD NAMING require(_burnableActive); _; } } library Roles { struct Role { mapping (address => bool) bearer; } function ADD666(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(account != address(0)); require(!HAS322(role, account)); role.bearer[account] = true; } function REMOVE231(Role storage role, address account) internal { //inject NONSTANDARD NAMING require(account != address(0)); require(HAS322(role, account)); role.bearer[account] = false; } function HAS322(Role storage role, address account) internal view returns (bool) { //inject NONSTANDARD NAMING require(account != address(0)); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MINTERADDED605(address indexed account); //inject NONSTANDARD NAMING event MINTERREMOVED905(address indexed account); //inject NONSTANDARD NAMING Roles.Role private _minters; constructor () internal { _ADDMINTER929(msg.sender); } modifier ONLYMINTER785() { //inject NONSTANDARD NAMING require(ISMINTER455(msg.sender)); _; } function ISMINTER455(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _minters.HAS322(account); } function ADDMINTER562(address account) public ONLYMINTER785 { //inject NONSTANDARD NAMING _ADDMINTER929(account); } function RENOUNCEMINTER297() public { //inject NONSTANDARD NAMING _REMOVEMINTER917(msg.sender); } function _ADDMINTER929(address account) internal { //inject NONSTANDARD NAMING _minters.ADD666(account); emit MINTERADDED605(account); } function _REMOVEMINTER917(address account) internal { //inject NONSTANDARD NAMING _minters.REMOVE231(account); emit MINTERREMOVED905(account); } } contract ERC20Mintable is ERC20Pistachio, MinterRole { bool private _mintableActive; function MINT525(address to, uint256 value) public ONLYMINTER785 WHENMINTABLEACTIVE702 returns (bool) { //inject NONSTANDARD NAMING _MINT600(to, value); return true; } function _SETMINTABLEACTIVE686(bool _active) internal { //inject NONSTANDARD NAMING _mintableActive = _active; } modifier WHENMINTABLEACTIVE702() { //inject NONSTANDARD NAMING require(_mintableActive); _; } } contract PauserRole { using Roles for Roles.Role; event PAUSERADDED252(address indexed account); //inject NONSTANDARD NAMING event PAUSERREMOVED538(address indexed account); //inject NONSTANDARD NAMING Roles.Role private _pausers; constructor () internal { _ADDPAUSER941(msg.sender); } modifier ONLYPAUSER672() { //inject NONSTANDARD NAMING require(ISPAUSER604(msg.sender)); _; } function ISPAUSER604(address account) public view returns (bool) { //inject NONSTANDARD NAMING return _pausers.HAS322(account); } function ADDPAUSER65(address account) public ONLYPAUSER672 { //inject NONSTANDARD NAMING _ADDPAUSER941(account); } function RENOUNCEPAUSER647() public { //inject NONSTANDARD NAMING _REMOVEPAUSER706(msg.sender); } function _ADDPAUSER941(address account) internal { //inject NONSTANDARD NAMING _pausers.ADD666(account); emit PAUSERADDED252(account); } function _REMOVEPAUSER706(address account) internal { //inject NONSTANDARD NAMING _pausers.REMOVE231(account); emit PAUSERREMOVED538(account); } } contract Pausable is PauserRole { event PAUSED114(address account); //inject NONSTANDARD NAMING event UNPAUSED110(address account); //inject NONSTANDARD NAMING bool private _pausableActive; bool private _paused; constructor () internal { _paused = false; } function PAUSED723() public view returns (bool) { //inject NONSTANDARD NAMING return _paused; } modifier WHENNOTPAUSED424() { //inject NONSTANDARD NAMING require(!_paused); _; } modifier WHENPAUSED745() { //inject NONSTANDARD NAMING require(_paused); _; } function PAUSE827() public ONLYPAUSER672 WHENNOTPAUSED424 WHENPAUSABLEACTIVE658 { //inject NONSTANDARD NAMING _paused = true; emit PAUSED114(msg.sender); } function UNPAUSE942() public ONLYPAUSER672 WHENPAUSED745 WHENPAUSABLEACTIVE658 { //inject NONSTANDARD NAMING _paused = false; emit UNPAUSED110(msg.sender); } function _SETPAUSABLEACTIVE337(bool _active) internal { //inject NONSTANDARD NAMING _pausableActive = _active; } modifier WHENPAUSABLEACTIVE658() { //inject NONSTANDARD NAMING require(_pausableActive); _; } } contract ERC20Chocolate is ERC20Pistachio, ERC20Burnable, ERC20Mintable, Pausable { // maximum capital, if defined > 0 uint256 private _cap; constructor ( address initialAccount, string memory _tokenSymbol, string memory _tokenName, uint256 initialBalance, uint256 cap, bool _burnableOption, bool _mintableOption, bool _pausableOption ) public ERC20Pistachio(initialAccount, _tokenSymbol, _tokenName, initialBalance) { // we must add customer account as the first minter ADDMINTER562(initialAccount); // add customer as pauser ADDPAUSER65(initialAccount); if (cap > 0) { _cap = cap; // maximum capitalization limited } else { _cap = 0; // unlimited capitalization } // activate or deactivate options _SETBURNABLEACTIVE519(_burnableOption); _SETMINTABLEACTIVE686(_mintableOption); _SETPAUSABLEACTIVE337(_pausableOption); } function CAP794() public view returns (uint256) { //inject NONSTANDARD NAMING return _cap; } function _MINT600(address account, uint256 value) internal { //inject NONSTANDARD NAMING if (_cap > 0) { require(TOTALSUPPLY304().ADD666(value) <= _cap); } super._MINT600(account, value); } function TRANSFER854(address to, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFER854(to, value); } function TRANSFERFROM522(address from,address to, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING return super.TRANSFERFROM522(from, to, value); } function APPROVE531(address spender, uint256 value) public WHENNOTPAUSED424 returns (bool) { //inject NONSTANDARD NAMING return super.APPROVE531(spender, value); } function INCREASEALLOWANCE330(address spender, uint addedValue) public WHENNOTPAUSED424 returns (bool success) { //inject NONSTANDARD NAMING return super.INCREASEALLOWANCE330(spender, addedValue); } function DECREASEALLOWANCE446(address spender, uint subtractedValue) public WHENNOTPAUSED424 returns (bool success) { //inject NONSTANDARD NAMING return super.DECREASEALLOWANCE446(spender, subtractedValue); } } 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; } modifier NONREENTRANT377() { //inject NONSTANDARD NAMING _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER714(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.TRANSFER854.selector, to, value)); } function SAFETRANSFERFROM672(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.TRANSFERFROM522.selector, from, to, value)); } function SAFEAPPROVE372(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE123(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, value)); } function SAFEINCREASEALLOWANCE265(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE123(address(this), spender).ADD666(value); CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE998(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE123(address(this), spender).SUB55(value); CALLOPTIONALRETURN667(token, abi.encodeWithSelector(token.APPROVE531.selector, spender, newAllowance)); } function CALLOPTIONALRETURN667(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).ISCONTRACT761(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library Address { function ISCONTRACT761(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function TOPAYABLE851(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } } contract Crowdsale is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for ERC20Chocolate; // The token being sold ERC20Chocolate private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; event TOKENSPURCHASED287(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //inject NONSTANDARD NAMING constructor (uint256 rate, address payable wallet, ERC20Chocolate token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } function () external payable { BUYTOKENS434(msg.sender); } function TOKEN293() public view returns (IERC20) { //inject NONSTANDARD NAMING return _token; } function WALLET108() public view returns (address payable) { //inject NONSTANDARD NAMING return _wallet; } function RATE426() public view returns (uint256) { //inject NONSTANDARD NAMING return _rate; } function WEIRAISED13() public view returns (uint256) { //inject NONSTANDARD NAMING return _weiRaised; } function BUYTOKENS434(address beneficiary) public NONREENTRANT377 payable { //inject NONSTANDARD NAMING uint256 weiAmount = msg.value; _PREVALIDATEPURCHASE289(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _GETTOKENAMOUNT276(weiAmount); // update state _weiRaised = _weiRaised.ADD666(weiAmount); _PROCESSPURCHASE887(beneficiary, tokens); emit TOKENSPURCHASED287(msg.sender, beneficiary, weiAmount, tokens); _UPDATEPURCHASINGSTATE322(beneficiary, weiAmount); _FORWARDFUNDS963(); _POSTVALIDATEPURCHASE368(beneficiary, weiAmount); } function _PREVALIDATEPURCHASE289(address beneficiary, uint256 weiAmount) internal view { //inject NONSTANDARD NAMING require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); } function _POSTVALIDATEPURCHASE368(address beneficiary, uint256 weiAmount) internal view { //inject NONSTANDARD NAMING // solhint-disable-previous-line no-empty-blocks } function _DELIVERTOKENS47(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING _token.SAFETRANSFER714(beneficiary, tokenAmount); } function _PROCESSPURCHASE887(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING _DELIVERTOKENS47(beneficiary, tokenAmount); } function _UPDATEPURCHASINGSTATE322(address beneficiary, uint256 weiAmount) internal { //inject NONSTANDARD NAMING // solhint-disable-previous-line no-empty-blocks } function _GETTOKENAMOUNT276(uint256 weiAmount) internal view returns (uint256) { //inject NONSTANDARD NAMING return weiAmount.MUL578(_rate); } function _FORWARDFUNDS963() internal { //inject NONSTANDARD NAMING _wallet.transfer(msg.value); } } contract MintedCrowdsale is Crowdsale { function _DELIVERTOKENS47(address beneficiary, uint256 tokenAmount) internal { //inject NONSTANDARD NAMING // Potentially dangerous assumption about the type of the token. require( ERC20Mintable(address(TOKEN293())).MINT525(beneficiary, tokenAmount), "MintedCrowdsale: minting failed" ); } } contract PausableCrowdsale is Crowdsale, Pausable { function _PREVALIDATEPURCHASE289(address _beneficiary, uint256 _weiAmount) internal view WHENNOTPAUSED424 { //inject NONSTANDARD NAMING return super._PREVALIDATEPURCHASE289(_beneficiary, _weiAmount); } } contract CrowdsaleRaspberry is MintedCrowdsale, PausableCrowdsale { constructor (uint256 rate, address payable wallet, ERC20Chocolate token, bool _isPausable) public Crowdsale(rate, wallet, token) { // solhint-disable-previous-line no-empty-blocks _SETPAUSABLEACTIVE337(_isPausable); } }
inject NONSTANDARD NAMING
function BURNFROM948(address from, uint256 value) public WHENBURNABLEACTIVE644 {
12,598,050
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 605, 8521, 11249, 29, 8875, 12, 2867, 628, 16, 2254, 5034, 460, 13, 1071, 29707, 38, 8521, 2782, 13301, 22087, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0xF5D5F849d057Bad242BabB034794889F3de7301c/sources/contracts/liquidation/FlashAMMStableLiquidation.sol
requested collateral value is the mean of total debt and the minimum necessary to restore minimum col ratio
function getBidAndRequest(uint256 trancheId) internal returns ( uint256, uint256, address ) { StableLending lending = stableLending(); address token = lending.trancheToken(trancheId); uint256 extantCollateral = lending.viewTargetCollateralAmount( trancheId ); uint256 extantCollateralValue = _getValue( token, extantCollateral, address(stableCoin()) ); uint256 requestedColVal; uint256 ltvPer10k = oracleRegistry().borrowablePer10ks(token); uint256 debt = lending.trancheDebt(trancheId); requestedColVal = (debt + (10_000 * debt - ltvPer10k * extantCollateralValue) / (10_000 - ltvPer10k)) / 2; uint256 bidTarget = (1000 * stableLendingLiquidation().viewBidTarget( trancheId, requestedColVal )) / 984; if ( debt - bidTarget > ((extantCollateralValue - requestedColVal) * ltvPer10k) / 10_000 ) { uint256 collateralRequest = (extantCollateral * requestedColVal) / extantCollateralValue; return (bidTarget, min(extantCollateral, collateralRequest), token); uint256 correspondingCollateral = (extantCollateral * debt) / extantCollateralValue; uint256 requestedCollateral = (correspondingCollateral * requestedColVal) / bidTarget; return (debt, min(extantCollateral, requestedCollateral), token); } }
16,385,371
[ 1, 19065, 4508, 2045, 287, 460, 353, 326, 3722, 434, 2078, 18202, 88, 471, 326, 5224, 4573, 358, 5217, 5224, 645, 7169, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2882, 350, 1876, 691, 12, 11890, 5034, 13637, 18706, 548, 13, 203, 3639, 2713, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 16, 203, 5411, 2254, 5034, 16, 203, 5411, 1758, 203, 3639, 262, 203, 565, 288, 203, 3639, 934, 429, 48, 2846, 328, 2846, 273, 14114, 48, 2846, 5621, 203, 3639, 1758, 1147, 273, 328, 2846, 18, 13171, 18706, 1345, 12, 13171, 18706, 548, 1769, 203, 203, 3639, 2254, 5034, 1110, 970, 13535, 2045, 287, 273, 328, 2846, 18, 1945, 2326, 13535, 2045, 287, 6275, 12, 203, 5411, 13637, 18706, 548, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 1110, 970, 13535, 2045, 287, 620, 273, 389, 24805, 12, 203, 5411, 1147, 16, 203, 5411, 1110, 970, 13535, 2045, 287, 16, 203, 5411, 1758, 12, 15021, 27055, 10756, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 3764, 914, 3053, 31, 203, 203, 3639, 2254, 5034, 13489, 90, 2173, 2163, 79, 273, 20865, 4243, 7675, 70, 15318, 429, 2173, 2163, 7904, 12, 2316, 1769, 203, 203, 3639, 2254, 5034, 18202, 88, 273, 328, 2846, 18, 13171, 18706, 758, 23602, 12, 13171, 18706, 548, 1769, 203, 3639, 3764, 914, 3053, 273, 203, 5411, 261, 323, 23602, 397, 203, 7734, 261, 2163, 67, 3784, 380, 18202, 88, 300, 13489, 90, 2173, 2163, 79, 380, 1110, 970, 13535, 2045, 287, 620, 13, 342, 203, 7734, 261, 2163, 67, 3784, 300, 13489, 90, 2173, 2163, 79, 3719, 342, 203, 5411, 576, 31, 203, 203, 3639, 2254, 5034, 9949, 2326, 273, 261, 18088, 380, 203, 5411, 14114, 2 ]
pragma solidity 0.5.16; interface ierc207 { //inject NONSTANDARD NAMING function TOTALSUPPLY3() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF6(address ACCOUNT8) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER0(address RECIPIENT4, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE8(address OWNER10, address SPENDER9) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE6(address SPENDER9, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM9(address SENDER7, address RECIPIENT4, uint AMOUNT10) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER10(address indexed FROM9, address indexed TO4, uint VALUE10); //inject NONSTANDARD NAMING event APPROVAL6(address indexed OWNER10, address indexed SPENDER9, uint VALUE10); //inject NONSTANDARD NAMING } contract context1 { //inject NONSTANDARD NAMING constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER8() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } } contract erc209 is context1, ierc207 { //inject NONSTANDARD NAMING using safemath3 for uint; mapping (address => uint) private _BALANCES7; //inject NONSTANDARD NAMING mapping (address => mapping (address => uint)) private _ALLOWANCES5; //inject NONSTANDARD NAMING uint private _TOTALSUPPLY10; //inject NONSTANDARD NAMING function TOTALSUPPLY3() public view returns (uint) { //inject NONSTANDARD NAMING return _TOTALSUPPLY10; } function BALANCEOF6(address ACCOUNT8) public view returns (uint) { //inject NONSTANDARD NAMING return _BALANCES7[ACCOUNT8]; } function TRANSFER0(address RECIPIENT4, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER10(_MSGSENDER8(), RECIPIENT4, AMOUNT10); return true; } function ALLOWANCE8(address OWNER10, address SPENDER9) public view returns (uint) { //inject NONSTANDARD NAMING return _ALLOWANCES5[OWNER10][SPENDER9]; } function APPROVE6(address SPENDER9, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE9(_MSGSENDER8(), SPENDER9, AMOUNT10); return true; } function TRANSFERFROM9(address SENDER7, address RECIPIENT4, uint AMOUNT10) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER10(SENDER7, RECIPIENT4, AMOUNT10); _APPROVE9(SENDER7, _MSGSENDER8(), _ALLOWANCES5[SENDER7][_MSGSENDER8()].SUB6(AMOUNT10, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE7(address SPENDER9, uint ADDEDVALUE4) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE9(_MSGSENDER8(), SPENDER9, _ALLOWANCES5[_MSGSENDER8()][SPENDER9].ADD8(ADDEDVALUE4)); return true; } function DECREASEALLOWANCE8(address SPENDER9, uint SUBTRACTEDVALUE3) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE9(_MSGSENDER8(), SPENDER9, _ALLOWANCES5[_MSGSENDER8()][SPENDER9].SUB6(SUBTRACTEDVALUE3, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER10(address SENDER7, address RECIPIENT4, uint AMOUNT10) internal { //inject NONSTANDARD NAMING require(SENDER7 != address(0), "ERC20: transfer from the zero address"); require(RECIPIENT4 != address(0), "ERC20: transfer to the zero address"); _BEFORETOKENTRANSFER5(SENDER7, RECIPIENT4, AMOUNT10); _BALANCES7[SENDER7] = _BALANCES7[SENDER7].SUB6(AMOUNT10, "ERC20: transfer amount exceeds balance"); _BALANCES7[RECIPIENT4] = _BALANCES7[RECIPIENT4].ADD8(AMOUNT10); emit TRANSFER10(SENDER7, RECIPIENT4, AMOUNT10); } function _MINT8(address ACCOUNT8, uint AMOUNT10) internal { //inject NONSTANDARD NAMING require(ACCOUNT8 != address(0), "ERC20: mint to the zero address"); _BEFORETOKENTRANSFER5(address(0), ACCOUNT8, AMOUNT10); _TOTALSUPPLY10 = _TOTALSUPPLY10.ADD8(AMOUNT10); _BALANCES7[ACCOUNT8] = _BALANCES7[ACCOUNT8].ADD8(AMOUNT10); emit TRANSFER10(address(0), ACCOUNT8, AMOUNT10); } function _BURN2(address ACCOUNT8, uint AMOUNT10) internal { //inject NONSTANDARD NAMING require(ACCOUNT8 != address(0), "ERC20: burn from the zero address"); _BEFORETOKENTRANSFER5(ACCOUNT8, address(0), AMOUNT10); _BALANCES7[ACCOUNT8] = _BALANCES7[ACCOUNT8].SUB6(AMOUNT10, "ERC20: burn amount exceeds balance"); _TOTALSUPPLY10 = _TOTALSUPPLY10.SUB6(AMOUNT10); emit TRANSFER10(ACCOUNT8, address(0), AMOUNT10); } function _APPROVE9(address OWNER10, address SPENDER9, uint AMOUNT10) internal { //inject NONSTANDARD NAMING require(OWNER10 != address(0), "ERC20: approve from the zero address"); require(SPENDER9 != address(0), "ERC20: approve to the zero address"); _ALLOWANCES5[OWNER10][SPENDER9] = AMOUNT10; emit APPROVAL6(OWNER10, SPENDER9, AMOUNT10); } function _BEFORETOKENTRANSFER5(address FROM9, address TO4, uint256 AMOUNT10) internal { } //inject NONSTANDARD NAMING } contract erc20detailed3 is ierc207 { //inject NONSTANDARD NAMING string private _NAME4; //inject NONSTANDARD NAMING string private _SYMBOL3; //inject NONSTANDARD NAMING uint8 private _DECIMALS5; //inject NONSTANDARD NAMING uint256 private _CAP1; //inject NONSTANDARD NAMING constructor (string memory NAME1, string memory SYMBOL10, uint8 DECIMALS2, uint256 CAP9) public { //inject NONSTANDARD NAMING _NAME4 = NAME1; _SYMBOL3 = SYMBOL10; _DECIMALS5 = DECIMALS2; _CAP1 = CAP9; } function NAME8() public view returns (string memory) { //inject NONSTANDARD NAMING return _NAME4; } function SYMBOL10() public view returns (string memory) { //inject NONSTANDARD NAMING return _SYMBOL3; } function DECIMALS8() public view returns (uint8) { //inject NONSTANDARD NAMING return _DECIMALS5; } function CAP3() public view returns (uint256) { //inject NONSTANDARD NAMING return _CAP1; } } library safemath3 { //inject NONSTANDARD NAMING function ADD8(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING uint C10 = A10 + B3; //inject NONSTANDARD NAMING require(C10 >= A10, "SafeMath: addition overflow"); return C10; } function SUB6(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB6(A10, B3, "SafeMath: subtraction overflow"); } function SUB6(uint A10, uint B3, string memory ERRORMESSAGE2) internal pure returns (uint) { //inject NONSTANDARD NAMING require(B3 <= A10, ERRORMESSAGE2); uint C10 = A10 - B3; //inject NONSTANDARD NAMING return C10; } function MUL10(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING if (A10 == 0) { return 0; } uint C10 = A10 * B3; //inject NONSTANDARD NAMING require(C10 / A10 == B3, "SafeMath: multiplication overflow"); return C10; } function DIV1(uint A10, uint B3) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV1(A10, B3, "SafeMath: division by zero"); } function DIV1(uint A10, uint B3, string memory ERRORMESSAGE2) internal pure returns (uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(B3 > 0, ERRORMESSAGE2); uint C10 = A10 / B3; //inject NONSTANDARD NAMING return C10; } } library address8 { //inject NONSTANDARD NAMING function ISCONTRACT7(address ACCOUNT8) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 CODEHASH8; //inject NONSTANDARD NAMING bytes32 ACCOUNTHASH10 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; //inject NONSTANDARD NAMING // solhint-disable-next-line no-inline-assembly assembly { CODEHASH8 := extcodehash(ACCOUNT8) } return (CODEHASH8 != 0x0 && CODEHASH8 != ACCOUNTHASH10); } } library safeerc207 { //inject NONSTANDARD NAMING using safemath3 for uint; using address8 for address; function SAFETRANSFER0(ierc207 TOKEN3, address TO4, uint VALUE10) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.TRANSFER0.selector, TO4, VALUE10)); } function SAFETRANSFERFROM0(ierc207 TOKEN3, address FROM9, address TO4, uint VALUE10) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.TRANSFERFROM9.selector, FROM9, TO4, VALUE10)); } function SAFEAPPROVE8(ierc207 TOKEN3, address SPENDER9, uint VALUE10) internal { //inject NONSTANDARD NAMING require((VALUE10 == 0) || (TOKEN3.ALLOWANCE8(address(this), SPENDER9) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN7(TOKEN3, abi.encodeWithSelector(TOKEN3.APPROVE6.selector, SPENDER9, VALUE10)); } function CALLOPTIONALRETURN7(ierc207 TOKEN3, bytes memory DATA10) private { //inject NONSTANDARD NAMING require(address(TOKEN3).ISCONTRACT7(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool SUCCESS10, bytes memory RETURNDATA2) = address(TOKEN3).call(DATA10); //inject NONSTANDARD NAMING require(SUCCESS10, "SafeERC20: low-level call failed"); if (RETURNDATA2.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(RETURNDATA2, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract hdt1 is erc209, erc20detailed3 { //inject NONSTANDARD NAMING using safeerc207 for ierc207; using address8 for address; using safemath3 for uint; address public GOVERNANCE4; //inject NONSTANDARD NAMING address public PENDINGGOV10; //inject NONSTANDARD NAMING mapping (address => bool) public MINTERS7; //inject NONSTANDARD NAMING event NEWPENDINGGOV1(address OLDPENDINGGOV6, address NEWPENDINGGOV5); //inject NONSTANDARD NAMING event NEWGOV0(address OLDGOV6, address NEWGOV3); //inject NONSTANDARD NAMING // Modifiers modifier ONLYGOV3() { //inject NONSTANDARD NAMING require(msg.sender == GOVERNANCE4, "HUB-Token: !governance"); _; } constructor () public erc20detailed3("HUB.finance", "HDT", 18, 800000000 * 10 ** 18) { GOVERNANCE4 = tx.origin; } function MINT5(address _ACCOUNT7, uint256 _AMOUNT8) public { //inject NONSTANDARD NAMING require(MINTERS7[msg.sender], "HUB-Token: !minter"); _MINT8(_ACCOUNT7, _AMOUNT8); } function ADDMINTER2(address _MINTER6) public ONLYGOV3 { //inject NONSTANDARD NAMING MINTERS7[_MINTER6] = true; } function REMOVEMINTER6(address _MINTER6) public ONLYGOV3 { //inject NONSTANDARD NAMING MINTERS7[_MINTER6] = false; } function SETPENDINGGOV6(address _PENDINGGOV2) //inject NONSTANDARD NAMING external ONLYGOV3 { address OLDPENDINGGOV6 = PENDINGGOV10; //inject NONSTANDARD NAMING PENDINGGOV10 = _PENDINGGOV2; emit NEWPENDINGGOV1(OLDPENDINGGOV6, _PENDINGGOV2); } function ACCEPTGOV3() //inject NONSTANDARD NAMING external { require(msg.sender == PENDINGGOV10, "HUB-Token: !pending"); address OLDGOV6 = GOVERNANCE4; //inject NONSTANDARD NAMING GOVERNANCE4 = PENDINGGOV10; PENDINGGOV10 = address(0); emit NEWGOV0(OLDGOV6, GOVERNANCE4); } function _BEFORETOKENTRANSFER5(address FROM9, address TO4, uint256 AMOUNT10) internal { //inject NONSTANDARD NAMING super._BEFORETOKENTRANSFER5(FROM9, TO4, AMOUNT10); if (FROM9 == address(0)) { // When minting tokens require(TOTALSUPPLY3().ADD8(AMOUNT10) <= CAP3(), "HUB-Token: Cap exceeded"); } } }
inject NONSTANDARD NAMING
function DIV1(uint A10, uint B3) internal pure returns (uint) {
5,469,249
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 27355, 21, 12, 11890, 432, 2163, 16, 2254, 605, 23, 13, 2713, 16618, 1135, 261, 11890, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xF3f4c0D0560549c6A7154Ae9B87D3a7cA13B50De/sources/contracts/Burner_contract.sol
generate the pair path of token -> weth make the swap
function swapETHForTokens( address routerAddress, address recipient, uint256 ethAmount, uint256 slippage ) internal { IUniswapV2Router02 pancakeRouter = IUniswapV2Router02(routerAddress); address[] memory path = new address[](2); path[0] = pancakeRouter.WETH(); path[1] = platformToken; path, address(recipient), block.timestamp + 360 ); }
16,424,005
[ 1, 7163, 326, 3082, 589, 434, 1147, 317, 341, 546, 1221, 326, 7720, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 445, 7720, 1584, 44, 1290, 5157, 12, 203, 3639, 1758, 4633, 1887, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 13750, 6275, 16, 203, 3639, 2254, 5034, 272, 3169, 2433, 203, 565, 262, 2713, 288, 203, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 2800, 23780, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 10717, 1887, 1769, 203, 203, 3639, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 203, 3639, 589, 63, 20, 65, 273, 2800, 23780, 8259, 18, 59, 1584, 44, 5621, 203, 3639, 589, 63, 21, 65, 273, 4072, 1345, 31, 203, 203, 5411, 589, 16, 203, 5411, 1758, 12, 20367, 3631, 203, 5411, 1203, 18, 5508, 397, 12360, 203, 3639, 11272, 203, 565, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.22; import "./Ownable.sol"; contract ReserveStructs is Ownable { event ID(uint256 id); event Initialized(address owner); event Limit(uint256 amount); event Received(address sender, uint256 amount); event Return(address recipient, uint256 transactionID, uint256 amount); event Sent(uint256 amount); //address of the tax authority whom a merchant will pay to address private taxAuth; //how much time is allowed after a transaction for a refund uint256 public refundTimeLimit; //limit on amount of ether stored in this contract. Extra ether is sent to //the tax authority address uint256 public reserveMaxBalance = 0; /** Constructor for a basic reserve * uint256 _refundTimeLimit the initial refundTimeLimit * uint256 _reserveMaxValue the maximum reserve balance * address _taxAuth the tax authority address * address _owner the owner of the contract */ //constructor(uint256 _refundTimeLimit, uint256 _reserveMaxValue, address _taxAuth, address _owner) constructor() public // onlyOwner { owner = msg.sender; emit Initialized(msg.sender); // todo set these values. taxAuth = 0x0; reserveMaxBalance = 100; refundTimeLimit = 60; } /** Function designating what to do when the contract receives ether. * Upon receiving ether, the contract checks to see if the current balance stored in the * contract is more than the allowed max balance and, if so, sends a Limit event with the * difference between the limit and the current balance. At the end, sends a "Received" event * signaling that the contract was paid an amount and by who. Ideally, the customer *should* * use the payEth function, but this accomplishes essentially the same thing, without * returning the transaction id (which is very important). */ function () payable public { // this code causes transaction error. need to fix before limit/liquidate //if (address(this).balance > reserveMaxBalance) { // uint256 overflow = address(this).balance - reserveMaxBalance; // emit Limit(overflow); //} emit Received(msg.sender, msg.value); } function getOwner() public returns (address) { emit Initialized(owner); return owner; } /*Sets the refund time limit*/ function setRefundTimeLimit(uint256 _refundTimeLimit) public onlyOwner returns (uint256) { emit ID(_refundTimeLimit); refundTimeLimit = _refundTimeLimit; return refundTimeLimit; } /*Returns the refund time limit*/ function getRefundTimeLimit() public view returns (uint256) { return refundTimeLimit; } /** Returns eth to the address corresponding to the _transactionID. * uint256 _transactionID the txid that you want to return eth to. */ function returnEth(address _addr, uint256 _id, uint256 _amount) public returns (bool) { _addr.transfer(_amount); emit Return(_addr, _id, _amount); return true; } /** Sends x amount of eth stored in this contract to the address _to * address _to the address to send the eth to. */ function liquidate(address _to, uint256 amount) public // onlyOwner // remove onlyOwner to allow liquidate by explicit unlock hack in the service returns (bool) { require(_to.send(amount)); return true; } }
address of the tax authority whom a merchant will pay tohow much time is allowed after a transaction for a refundlimit on amount of ether stored in this contract. Extra ether is sent tothe tax authority addressconstructor(uint256 _refundTimeLimit, uint256 _reserveMaxValue, address _taxAuth, address _owner) onlyOwner
contract ReserveStructs is Ownable { event ID(uint256 id); event Initialized(address owner); event Limit(uint256 amount); event Received(address sender, uint256 amount); event Return(address recipient, uint256 transactionID, uint256 amount); event Sent(uint256 amount); address private taxAuth; uint256 public refundTimeLimit; uint256 public reserveMaxBalance = 0; constructor() public { owner = msg.sender; emit Initialized(msg.sender); taxAuth = 0x0; reserveMaxBalance = 100; refundTimeLimit = 60; } function () payable public { emit Received(msg.sender, msg.value); } function getOwner() public returns (address) { emit Initialized(owner); return owner; } function setRefundTimeLimit(uint256 _refundTimeLimit) public onlyOwner returns (uint256) { emit ID(_refundTimeLimit); refundTimeLimit = _refundTimeLimit; return refundTimeLimit; } function getRefundTimeLimit() public view returns (uint256) { return refundTimeLimit; } function returnEth(address _addr, uint256 _id, uint256 _amount) public returns (bool) { _addr.transfer(_amount); emit Return(_addr, _id, _amount); return true; } function liquidate(address _to, uint256 amount) public returns (bool) { require(_to.send(amount)); return true; } }
7,317,428
[ 1, 2867, 434, 326, 5320, 11675, 600, 362, 279, 20411, 903, 8843, 358, 13606, 9816, 813, 353, 2935, 1839, 279, 2492, 364, 279, 16255, 3595, 603, 3844, 434, 225, 2437, 4041, 316, 333, 6835, 18, 13592, 225, 2437, 353, 3271, 9997, 580, 5320, 11675, 1758, 12316, 12, 11890, 5034, 389, 1734, 1074, 950, 3039, 16, 2254, 5034, 389, 455, 6527, 2747, 620, 16, 1758, 389, 8066, 1730, 16, 1758, 389, 8443, 13, 1338, 5541, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1124, 6527, 3823, 87, 353, 14223, 6914, 288, 203, 203, 565, 871, 1599, 12, 11890, 5034, 612, 1769, 203, 565, 871, 10188, 1235, 12, 2867, 3410, 1769, 203, 565, 871, 7214, 12, 11890, 5034, 3844, 1769, 203, 565, 871, 21066, 12, 2867, 5793, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 2000, 12, 2867, 8027, 16, 2254, 5034, 2492, 734, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 16695, 12, 11890, 5034, 3844, 1769, 203, 203, 565, 1758, 3238, 5320, 1730, 31, 203, 203, 565, 2254, 5034, 1071, 16255, 950, 3039, 31, 203, 565, 2254, 5034, 1071, 20501, 2747, 13937, 273, 374, 31, 203, 203, 565, 3885, 1435, 203, 565, 1071, 203, 565, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 3626, 10188, 1235, 12, 3576, 18, 15330, 1769, 203, 3639, 5320, 1730, 273, 374, 92, 20, 31, 203, 3639, 20501, 2747, 13937, 273, 2130, 31, 203, 3639, 16255, 950, 3039, 273, 4752, 31, 203, 565, 289, 203, 203, 565, 445, 1832, 8843, 429, 1071, 288, 203, 3639, 3626, 21066, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 13782, 1435, 1071, 1135, 261, 2867, 13, 288, 203, 3639, 3626, 10188, 1235, 12, 8443, 1769, 203, 3639, 327, 3410, 31, 203, 565, 289, 203, 203, 565, 445, 444, 21537, 950, 3039, 12, 11890, 5034, 389, 1734, 1074, 950, 3039, 13, 1071, 203, 565, 1338, 5541, 203, 565, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 3626, 1599, 24899, 1734, 1074, 950, 3039, 1769, 2 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; import "./HoldefiPausableOwnable.sol"; import "./HoldefiCollaterals.sol"; /// @notice File: contracts/HoldefiPrices.sol interface HoldefiPricesInterface { function getAssetValueFromAmount(address asset, uint256 amount) external view returns(uint256 value); function getAssetAmountFromValue(address asset, uint256 value) external view returns(uint256 amount); } /// @notice File: contracts/HoldefiSettings.sol interface HoldefiSettingsInterface { /// @notice Markets Features struct MarketSettings { bool isExist; bool isActive; uint256 borrowRate; uint256 borrowRateUpdateTime; uint256 suppliersShareRate; uint256 suppliersShareRateUpdateTime; uint256 promotionRate; } /// @notice Collateral Features struct CollateralSettings { bool isExist; bool isActive; uint256 valueToLoanRate; uint256 VTLUpdateTime; uint256 penaltyRate; uint256 penaltyUpdateTime; uint256 bonusRate; } function getInterests(address market) external view returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate); function resetPromotionRate (address market) external; function getMarketsList() external view returns(address[] memory marketsList); function marketAssets(address market) external view returns(MarketSettings memory); function collateralAssets(address collateral) external view returns(CollateralSettings memory); } /// @title Main Holdefi contract /// @author Holdefi Team /// @dev The address of ETH considered as 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE /// @dev All indexes are scaled by (secondsPerYear * rateDecimals) /// @dev All values are based ETH price considered 1 and all values decimals considered 30 contract Holdefi is HoldefiPausableOwnable { using SafeMath for uint256; /// @notice Markets are assets can be supplied and borrowed struct Market { uint256 totalSupply; uint256 supplyIndex; // Scaled by: secondsPerYear * rateDecimals uint256 supplyIndexUpdateTime; uint256 totalBorrow; uint256 borrowIndex; // Scaled by: secondsPerYear * rateDecimals uint256 borrowIndexUpdateTime; uint256 promotionReserveScaled; // Scaled by: secondsPerYear * rateDecimals uint256 promotionReserveLastUpdateTime; uint256 promotionDebtScaled; // Scaled by: secondsPerYear * rateDecimals uint256 promotionDebtLastUpdateTime; } /// @notice Collaterals are assets can be used only as collateral for borrowing with no interest struct Collateral { uint256 totalCollateral; uint256 totalLiquidatedCollateral; } /// @notice Users profile for each market struct MarketAccount { mapping (address => uint) allowance; uint256 balance; uint256 accumulatedInterest; uint256 lastInterestIndex; // Scaled by: secondsPerYear * rateDecimals } /// @notice Users profile for each collateral struct CollateralAccount { mapping (address => uint) allowance; uint256 balance; uint256 lastUpdateTime; } struct MarketData { uint256 balance; uint256 interest; uint256 currentIndex; } address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice All rates in this contract are scaled by rateDecimals uint256 constant public rateDecimals = 10 ** 4; uint256 constant public secondsPerYear = 31536000; /// @dev For round up borrow interests uint256 constant private oneUnit = 1; /// @dev Used for calculating liquidation threshold /// @dev There is 5% gap between value to loan rate and liquidation rate uint256 constant private fivePercentLiquidationGap = 500; /// @notice Contract for getting protocol settings HoldefiSettingsInterface public holdefiSettings; /// @notice Contract for getting asset prices HoldefiPricesInterface public holdefiPrices; /// @notice Contract for holding collaterals HoldefiCollaterals public holdefiCollaterals; /// @dev Markets: marketAddress => marketDetails mapping (address => Market) public marketAssets; /// @dev Collaterals: collateralAddress => collateralDetails mapping (address => Collateral) public collateralAssets; /// @dev Markets Debt after liquidation: collateralAddress => marketAddress => marketDebtBalance mapping (address => mapping (address => uint)) public marketDebt; /// @dev Users Supplies: userAddress => marketAddress => supplyDetails mapping (address => mapping (address => MarketAccount)) private supplies; /// @dev Users Borrows: userAddress => collateralAddress => marketAddress => borrowDetails mapping (address => mapping (address => mapping (address => MarketAccount))) private borrows; /// @dev Users Collaterals: userAddress => collateralAddress => collateralDetails mapping (address => mapping (address => CollateralAccount)) private collaterals; // ----------- Events ----------- /// @notice Event emitted when a market asset is supplied event Supply( address sender, address indexed supplier, address indexed market, uint256 amount, uint256 balance, uint256 interest, uint256 index, uint16 referralCode ); /// @notice Event emitted when a supply is withdrawn event WithdrawSupply( address sender, address indexed supplier, address indexed market, uint256 amount, uint256 balance, uint256 interest, uint256 index ); /// @notice Event emitted when a collateral asset is deposited event Collateralize( address sender, address indexed collateralizer, address indexed collateral, uint256 amount, uint256 balance ); /// @notice Event emitted when a collateral is withdrawn event WithdrawCollateral( address sender, address indexed collateralizer, address indexed collateral, uint256 amount, uint256 balance ); /// @notice Event emitted when a market asset is borrowed event Borrow( address sender, address indexed borrower, address indexed market, address indexed collateral, uint256 amount, uint256 balance, uint256 interest, uint256 index, uint16 referralCode ); /// @notice Event emitted when a borrow is repaid event RepayBorrow( address sender, address indexed borrower, address indexed market, address indexed collateral, uint256 amount, uint256 balance, uint256 interest, uint256 index ); /// @notice Event emitted when the supply index is updated for a market asset event UpdateSupplyIndex(address indexed market, uint256 newSupplyIndex, uint256 supplyRate); /// @notice Event emitted when the borrow index is updated for a market asset event UpdateBorrowIndex(address indexed market, uint256 newBorrowIndex); /// @notice Event emitted when a collateral is liquidated event CollateralLiquidated( address indexed borrower, address indexed market, address indexed collateral, uint256 marketDebt, uint256 liquidatedCollateral ); /// @notice Event emitted when a liquidated collateral is purchased in exchange for the specified market event BuyLiquidatedCollateral( address indexed market, address indexed collateral, uint256 marketAmount, uint256 collateralAmount ); /// @notice Event emitted when HoldefiPrices contract is changed event HoldefiPricesContractChanged(address newAddress, address oldAddress); /// @notice Event emitted when a liquidation reserve is withdrawn by the owner event LiquidationReserveWithdrawn(address indexed collateral, uint256 amount); /// @notice Event emitted when a liquidation reserve is deposited event LiquidationReserveDeposited(address indexed collateral, uint256 amount); /// @notice Event emitted when a promotion reserve is withdrawn by the owner event PromotionReserveWithdrawn(address indexed market, uint256 amount); /// @notice Event emitted when a promotion reserve is deposited event PromotionReserveDeposited(address indexed market, uint256 amount); /// @notice Event emitted when a promotion reserve is updated event PromotionReserveUpdated(address indexed market, uint256 promotionReserve); /// @notice Event emitted when a promotion debt is updated event PromotionDebtUpdated(address indexed market, uint256 promotionDebt); /// @notice Initializes the Holdefi contract /// @param holdefiSettingsAddress Holdefi settings contract address /// @param holdefiPricesAddress Holdefi prices contract address constructor( HoldefiSettingsInterface holdefiSettingsAddress, HoldefiPricesInterface holdefiPricesAddress ) public { holdefiSettings = holdefiSettingsAddress; holdefiPrices = holdefiPricesAddress; holdefiCollaterals = new HoldefiCollaterals(); } /// @dev Modifier to check if the asset is ETH or not /// @param asset Address of the given asset modifier isNotETHAddress(address asset) { require (asset != ethAddress, "Asset should not be ETH address"); _; } /// @dev Modifier to check if the market is active or not /// @param market Address of the given market modifier marketIsActive(address market) { require (holdefiSettings.marketAssets(market).isActive, "Market is not active"); _; } /// @dev Modifier to check if the collateral is active or not /// @param collateral Address of the given collateral modifier collateralIsActive(address collateral) { require (holdefiSettings.collateralAssets(collateral).isActive, "Collateral is not active"); _; } /// @dev Modifier to check if the account address is equal to the msg.sender or not /// @param account The given account address modifier accountIsValid(address account) { require (msg.sender != account, "Account is not valid"); _; } receive() external payable { revert(); } /// @notice Returns balance and interest of an account for a given market /// @dev supplyInterest = accumulatedInterest + (balance * (marketSupplyIndex - userLastSupplyInterestIndex)) /// @param account Supplier address to get supply information /// @param market Address of the given market /// @return balance Supplied amount on the specified market /// @return interest Profit earned /// @return currentSupplyIndex Supply index for the given market at current time function getAccountSupply(address account, address market) public view returns (uint256 balance, uint256 interest, uint256 currentSupplyIndex) { balance = supplies[account][market].balance; (currentSupplyIndex,,) = getCurrentSupplyIndex(market); uint256 deltaInterestIndex = currentSupplyIndex.sub(supplies[account][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); interest = supplies[account][market].accumulatedInterest.add(deltaInterest); } /// @notice Returns balance and interest of an account for a given market on a given collateral /// @dev borrowInterest = accumulatedInterest + (balance * (marketBorrowIndex - userLastBorrowInterestIndex)) /// @param account Borrower address to get Borrow information /// @param market Address of the given market /// @param collateral Address of the given collateral /// @return balance Borrowed amount on the specified market /// @return interest The amount of interest the borrower should pay /// @return currentBorrowIndex Borrow index for the given market at current time function getAccountBorrow(address account, address market, address collateral) public view returns (uint256 balance, uint256 interest, uint256 currentBorrowIndex) { balance = borrows[account][collateral][market].balance; (currentBorrowIndex,,) = getCurrentBorrowIndex(market); uint256 deltaInterestIndex = currentBorrowIndex.sub(borrows[account][collateral][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); if (balance > 0) { deltaInterest = deltaInterest.add(oneUnit); } interest = borrows[account][collateral][market].accumulatedInterest.add(deltaInterest); } /// @notice Returns collateral balance, time since last activity, borrow power, total borrow value, and liquidation status for a given collateral /// @dev borrowPower = (collateralValue / collateralValueToLoanRate) - totalBorrowValue /// @dev liquidationThreshold = collateralValueToLoanRate - 5% /// @dev User will be in liquidation state if (collateralValue / totalBorrowValue) < liquidationThreshold /// @param account Account address to get collateral information /// @param collateral Address of the given collateral /// @return balance Amount of the specified collateral /// @return timeSinceLastActivity Time since last activity performed by the account /// @return borrowPowerValue The borrowing power for the account of the given collateral /// @return totalBorrowValue Accumulative borrowed values on the given collateral /// @return underCollateral A boolean value indicates whether the user is in the liquidation state or not function getAccountCollateral(address account, address collateral) public view returns ( uint256 balance, uint256 timeSinceLastActivity, uint256 borrowPowerValue, uint256 totalBorrowValue, bool underCollateral ) { uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate; if (valueToLoanRate == 0) { return (0, 0, 0, 0, false); } balance = collaterals[account][collateral].balance; uint256 collateralValue = holdefiPrices.getAssetValueFromAmount(collateral, balance); uint256 liquidationThresholdRate = valueToLoanRate.sub(fivePercentLiquidationGap); uint256 totalBorrowPowerValue = collateralValue.mul(rateDecimals).div(valueToLoanRate); uint256 liquidationThresholdValue = collateralValue.mul(rateDecimals).div(liquidationThresholdRate); totalBorrowValue = getAccountTotalBorrowValue(account, collateral); if (totalBorrowValue > 0) { timeSinceLastActivity = block.timestamp.sub(collaterals[account][collateral].lastUpdateTime); } borrowPowerValue = 0; if (totalBorrowValue < totalBorrowPowerValue) { borrowPowerValue = totalBorrowPowerValue.sub(totalBorrowValue); } underCollateral = false; if (totalBorrowValue > liquidationThresholdValue) { underCollateral = true; } } /// @notice Returns maximum amount spender can withdraw from account supplies on a given market /// @param account Supplier address /// @param spender Spender address /// @param market Address of the given market /// @return res Maximum amount spender can withdraw from account supplies on a given market function getAccountWithdrawSupplyAllowance (address account, address spender, address market) external view returns (uint256 res) { res = supplies[account][market].allowance[spender]; } /// @notice Returns maximum amount spender can withdraw from account balance on a given collateral /// @param account Account address /// @param spender Spender address /// @param collateral Address of the given collateral /// @return res Maximum amount spender can withdraw from account balance on a given collateral function getAccountWithdrawCollateralAllowance ( address account, address spender, address collateral ) external view returns (uint256 res) { res = collaterals[account][collateral].allowance[spender]; } /// @notice Returns maximum amount spender can withdraw from account borrows on a given market based on a given collteral /// @param account Borrower address /// @param spender Spender address /// @param market Address of the given market /// @param collateral Address of the given collateral /// @return res Maximum amount spender can withdraw from account borrows on a given market based on a given collteral function getAccountBorrowAllowance ( address account, address spender, address market, address collateral ) external view returns (uint256 res) { res = borrows[account][collateral][market].allowance[spender]; } /// @notice Returns total borrow value of an account based on a given collateral /// @param account Account address /// @param collateral Address of the given collateral /// @return totalBorrowValue Accumulative borrowed values on the given collateral function getAccountTotalBorrowValue (address account, address collateral) public view returns (uint256 totalBorrowValue) { MarketData memory borrowData; address market; uint256 totalDebt; uint256 assetValue; totalBorrowValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; (borrowData.balance, borrowData.interest,) = getAccountBorrow(account, market, collateral); totalDebt = borrowData.balance.add(borrowData.interest); assetValue = holdefiPrices.getAssetValueFromAmount(market, totalDebt); totalBorrowValue = totalBorrowValue.add(assetValue); } } /// @notice The collateral reserve amount for buying liquidated collateral /// @param collateral Address of the given collateral /// @return reserve Liquidation reserves for the given collateral function getLiquidationReserve (address collateral) public view returns(uint256 reserve) { address market; uint256 assetValue; uint256 totalDebtValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; assetValue = holdefiPrices.getAssetValueFromAmount(market, marketDebt[collateral][market]); totalDebtValue = totalDebtValue.add(assetValue); } uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 totalDebtCollateralValue = totalDebtValue.mul(bonusRate).div(rateDecimals); uint256 liquidatedCollateralNeeded = holdefiPrices.getAssetAmountFromValue( collateral, totalDebtCollateralValue ); reserve = 0; uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; if (totalLiquidatedCollateral > liquidatedCollateralNeeded) { reserve = totalLiquidatedCollateral.sub(liquidatedCollateralNeeded); } } /// @notice Returns the amount of discounted collateral can be bought in exchange for the amount of a given market /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param marketAmount The amount of market should be paid /// @return collateralAmountWithDiscount Amount of discounted collateral can be bought function getDiscountedCollateralAmount (address market, address collateral, uint256 marketAmount) public view returns (uint256 collateralAmountWithDiscount) { uint256 marketValue = holdefiPrices.getAssetValueFromAmount(market, marketAmount); uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 collateralValue = marketValue.mul(bonusRate).div(rateDecimals); collateralAmountWithDiscount = holdefiPrices.getAssetAmountFromValue(collateral, collateralValue); } /// @notice Returns supply index and supply rate for a given market at current time /// @dev newSupplyIndex = oldSupplyIndex + (deltaTime * supplyRate) /// @param market Address of the given market /// @return supplyIndex Supply index of the given market /// @return supplyRate Supply rate of the given market /// @return currentTime Current block timestamp function getCurrentSupplyIndex (address market) public view returns ( uint256 supplyIndex, uint256 supplyRate, uint256 currentTime ) { (, uint256 supplyRateBase, uint256 promotionRate) = holdefiSettings.getInterests(market); currentTime = block.timestamp; uint256 deltaTimeSupply = currentTime.sub(marketAssets[market].supplyIndexUpdateTime); supplyRate = supplyRateBase.add(promotionRate); uint256 deltaTimeInterest = deltaTimeSupply.mul(supplyRate); supplyIndex = marketAssets[market].supplyIndex.add(deltaTimeInterest); } /// @notice Returns borrow index and borrow rate for the given market at current time /// @dev newBorrowIndex = oldBorrowIndex + (deltaTime * borrowRate) /// @param market Address of the given market /// @return borrowIndex Borrow index of the given market /// @return borrowRate Borrow rate of the given market /// @return currentTime Current block timestamp function getCurrentBorrowIndex (address market) public view returns ( uint256 borrowIndex, uint256 borrowRate, uint256 currentTime ) { borrowRate = holdefiSettings.marketAssets(market).borrowRate; currentTime = block.timestamp; uint256 deltaTimeBorrow = currentTime.sub(marketAssets[market].borrowIndexUpdateTime); uint256 deltaTimeInterest = deltaTimeBorrow.mul(borrowRate); borrowIndex = marketAssets[market].borrowIndex.add(deltaTimeInterest); } /// @notice Returns promotion reserve for a given market at current time /// @dev promotionReserveScaled is scaled by (secondsPerYear * rateDecimals) /// @param market Address of the given market /// @return promotionReserveScaled Promotion reserve of the given market /// @return currentTime Current block timestamp function getPromotionReserve (address market) public view returns (uint256 promotionReserveScaled, uint256 currentTime) { (uint256 borrowRate, uint256 supplyRateBase,) = holdefiSettings.getInterests(market); currentTime = block.timestamp; uint256 allSupplyInterest = marketAssets[market].totalSupply.mul(supplyRateBase); uint256 allBorrowInterest = marketAssets[market].totalBorrow.mul(borrowRate); uint256 deltaTime = currentTime.sub(marketAssets[market].promotionReserveLastUpdateTime); uint256 currentInterest = allBorrowInterest.sub(allSupplyInterest); uint256 deltaTimeInterest = currentInterest.mul(deltaTime); promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(deltaTimeInterest); } /// @notice Returns promotion debt for a given market at current time /// @dev promotionDebtScaled is scaled by secondsPerYear * rateDecimals /// @param market Address of the given market /// @return promotionDebtScaled Promotion debt of the given market /// @return currentTime Current block timestamp function getPromotionDebt (address market) public view returns (uint256 promotionDebtScaled, uint256 currentTime) { uint256 promotionRate = holdefiSettings.marketAssets(market).promotionRate; currentTime = block.timestamp; promotionDebtScaled = marketAssets[market].promotionDebtScaled; if (promotionRate != 0) { uint256 deltaTime = block.timestamp.sub(marketAssets[market].promotionDebtLastUpdateTime); uint256 currentInterest = marketAssets[market].totalSupply.mul(promotionRate); uint256 deltaTimeInterest = currentInterest.mul(deltaTime); promotionDebtScaled = promotionDebtScaled.add(deltaTimeInterest); } } /// @notice Update a market supply index, promotion reserve, and promotion debt /// @param market Address of the given market function beforeChangeSupplyRate (address market) public { updateSupplyIndex(market); updatePromotionReserve(market); updatePromotionDebt(market); } /// @notice Update a market borrow index, supply index, promotion reserve, and promotion debt /// @param market Address of the given market function beforeChangeBorrowRate (address market) external { updateBorrowIndex(market); beforeChangeSupplyRate(market); } /// @notice Deposit ERC20 asset for supplying /// @param market Address of the given market /// @param amount The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supply(address market, uint256 amount, uint16 referralCode) external isNotETHAddress(market) { supplyInternal(msg.sender, market, amount, referralCode); } /// @notice Deposit ETH for supplying /// @notice msg.value The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supply(uint16 referralCode) external payable { supplyInternal(msg.sender, ethAddress, msg.value, referralCode); } /// @notice Sender deposits ERC20 asset belonging to the supplier /// @param account Address of the supplier /// @param market Address of the given market /// @param amount The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supplyBehalf(address account, address market, uint256 amount, uint16 referralCode) external isNotETHAddress(market) { supplyInternal(account, market, amount, referralCode); } /// @notice Sender deposits ETH belonging to the supplier /// @notice msg.value The amount of ETH sender deposits belonging to the supplier /// @param account Address of the supplier /// @param referralCode A unique code used as an identifier of referrer function supplyBehalf(address account, uint16 referralCode) external payable { supplyInternal(account, ethAddress, msg.value, referralCode); } /// @notice Sender approves of the withdarawl for the account in the market asset /// @param account Address of the account allowed to withdrawn /// @param market Address of the given market /// @param amount The amount is allowed to withdrawn function approveWithdrawSupply(address account, address market, uint256 amount) external accountIsValid(account) marketIsActive(market) { supplies[msg.sender][market].allowance[account] = amount; } /// @notice Withdraw supply of a given market /// @param market Address of the given market /// @param amount The amount will be withdrawn from the market function withdrawSupply(address market, uint256 amount) external { withdrawSupplyInternal(msg.sender, market, amount); } /// @notice Sender withdraws supply belonging to the supplier /// @param account Address of the supplier /// @param market Address of the given market /// @param amount The amount will be withdrawn from the market function withdrawSupplyBehalf(address account, address market, uint256 amount) external { uint256 allowance = supplies[account][market].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); supplies[account][market].allowance[msg.sender] = allowance.sub(amount); withdrawSupplyInternal(account, market, amount); } /// @notice Deposit ERC20 asset as a collateral /// @param collateral Address of the given collateral /// @param amount The amount will be collateralized function collateralize (address collateral, uint256 amount) external isNotETHAddress(collateral) { collateralizeInternal(msg.sender, collateral, amount); } /// @notice Deposit ETH as a collateral /// @notice msg.value The amount of ETH will be collateralized function collateralize () external payable { collateralizeInternal(msg.sender, ethAddress, msg.value); } /// @notice Sender deposits ERC20 asset as a collateral belonging to the user /// @param account Address of the user /// @param collateral Address of the given collateral /// @param amount The amount will be collateralized function collateralizeBehalf (address account, address collateral, uint256 amount) external isNotETHAddress(collateral) { collateralizeInternal(account, collateral, amount); } /// @notice Sender deposits ETH as a collateral belonging to the user /// @notice msg.value The amount of ETH Sender deposits as a collateral belonging to the user /// @param account Address of the user function collateralizeBehalf (address account) external payable { collateralizeInternal(account, ethAddress, msg.value); } /// @notice Sender approves the account to withdraw the collateral /// @param account Address is allowed to withdraw the collateral /// @param collateral Address of the given collateral /// @param amount The amount is allowed to withdrawn function approveWithdrawCollateral (address account, address collateral, uint256 amount) external accountIsValid(account) collateralIsActive(collateral) { collaterals[msg.sender][collateral].allowance[account] = amount; } /// @notice Withdraw a collateral /// @param collateral Address of the given collateral /// @param amount The amount will be withdrawn from the collateral function withdrawCollateral (address collateral, uint256 amount) external { withdrawCollateralInternal(msg.sender, collateral, amount); } /// @notice Sender withdraws a collateral belonging to the user /// @param account Address of the user /// @param collateral Address of the given collateral /// @param amount The amount will be withdrawn from the collateral function withdrawCollateralBehalf (address account, address collateral, uint256 amount) external { uint256 allowance = collaterals[account][collateral].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); collaterals[account][collateral].allowance[msg.sender] = allowance.sub(amount); withdrawCollateralInternal(account, collateral, amount); } /// @notice Sender approves the account to borrow a given market based on given collateral /// @param account Address that is allowed to borrow the given market /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount is allowed to withdrawn function approveBorrow (address account, address market, address collateral, uint256 amount) external accountIsValid(account) marketIsActive(market) { borrows[msg.sender][collateral][market].allowance[account] = amount; } /// @notice Borrow an asset /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the given market will be borrowed /// @param referralCode A unique code used as an identifier of referrer function borrow (address market, address collateral, uint256 amount, uint16 referralCode) external { borrowInternal(msg.sender, market, collateral, amount, referralCode); } /// @notice Sender borrows an asset belonging to the borrower /// @param account Address of the borrower /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount will be borrowed /// @param referralCode A unique code used as an identifier of referrer function borrowBehalf (address account, address market, address collateral, uint256 amount, uint16 referralCode) external { uint256 allowance = borrows[account][collateral][market].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); borrows[account][collateral][market].allowance[msg.sender] = allowance.sub(amount); borrowInternal(account, market, collateral, amount, referralCode); } /// @notice Repay an ERC20 asset based on a given collateral /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the market will be Repaid function repayBorrow (address market, address collateral, uint256 amount) external isNotETHAddress(market) { repayBorrowInternal(msg.sender, market, collateral, amount); } /// @notice Repay an ETH based on a given collateral /// @notice msg.value The amount of ETH will be repaid /// @param collateral Address of the given collateral function repayBorrow (address collateral) external payable { repayBorrowInternal(msg.sender, ethAddress, collateral, msg.value); } /// @notice Sender repays an ERC20 asset based on a given collateral belonging to the borrower /// @param account Address of the borrower /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the market will be repaid function repayBorrowBehalf (address account, address market, address collateral, uint256 amount) external isNotETHAddress(market) { repayBorrowInternal(account, market, collateral, amount); } /// @notice Sender repays an ETH based on a given collateral belonging to the borrower /// @notice msg.value The amount of ETH sender repays belonging to the borrower /// @param account Address of the borrower /// @param collateral Address of the given collateral function repayBorrowBehalf (address account, address collateral) external payable { repayBorrowInternal(account, ethAddress, collateral, msg.value); } /// @notice Liquidate borrower's collateral /// @param borrower Address of the borrower who should be liquidated /// @param market Address of the given market /// @param collateral Address of the given collateral function liquidateBorrowerCollateral (address borrower, address market, address collateral) external whenNotPaused("liquidateBorrowerCollateral") { MarketData memory borrowData; (borrowData.balance, borrowData.interest,) = getAccountBorrow(borrower, market, collateral); require(borrowData.balance > 0, "User should have debt"); (uint256 collateralBalance, uint256 timeSinceLastActivity,,, bool underCollateral) = getAccountCollateral(borrower, collateral); require (underCollateral || (timeSinceLastActivity > secondsPerYear), "User should be under collateral or time is over" ); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); uint256 totalBorrowedBalanceValue = holdefiPrices.getAssetValueFromAmount(market, totalBorrowedBalance); uint256 liquidatedCollateralValue = totalBorrowedBalanceValue .mul(holdefiSettings.collateralAssets(collateral).penaltyRate) .div(rateDecimals); uint256 liquidatedCollateral = holdefiPrices.getAssetAmountFromValue(collateral, liquidatedCollateralValue); if (liquidatedCollateral > collateralBalance) { liquidatedCollateral = collateralBalance; } collaterals[borrower][collateral].balance = collateralBalance.sub(liquidatedCollateral); collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(liquidatedCollateral); collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.add(liquidatedCollateral); delete borrows[borrower][collateral][market]; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(borrowData.balance); marketDebt[collateral][market] = marketDebt[collateral][market].add(totalBorrowedBalance); emit CollateralLiquidated(borrower, market, collateral, totalBorrowedBalance, liquidatedCollateral); } /// @notice Buy collateral in exchange for ERC20 asset /// @param market Address of the market asset should be paid to buy collateral /// @param collateral Address of the liquidated collateral /// @param marketAmount The amount of the given market will be paid function buyLiquidatedCollateral (address market, address collateral, uint256 marketAmount) external isNotETHAddress(market) { buyLiquidatedCollateralInternal(market, collateral, marketAmount); } /// @notice Buy collateral in exchange for ETH /// @notice msg.value The amount of the given market that will be paid /// @param collateral Address of the liquidated collateral function buyLiquidatedCollateral (address collateral) external payable { buyLiquidatedCollateralInternal(ethAddress, collateral, msg.value); } /// @notice Deposit ERC20 asset as liquidation reserve /// @param collateral Address of the given collateral /// @param amount The amount that will be deposited function depositLiquidationReserve(address collateral, uint256 amount) external isNotETHAddress(collateral) { depositLiquidationReserveInternal(collateral, amount); } /// @notice Deposit ETH asset as liquidation reserve /// @notice msg.value The amount of ETH that will be deposited function depositLiquidationReserve() external payable { depositLiquidationReserveInternal(ethAddress, msg.value); } /// @notice Withdraw liquidation reserve only by the owner /// @param collateral Address of the given collateral /// @param amount The amount that will be withdrawn function withdrawLiquidationReserve (address collateral, uint256 amount) external onlyOwner { uint256 maxWithdraw = getLiquidationReserve(collateral); uint256 transferAmount = amount; if (transferAmount > maxWithdraw){ transferAmount = maxWithdraw; } collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.sub(transferAmount); holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount); emit LiquidationReserveWithdrawn(collateral, amount); } /// @notice Deposit ERC20 asset as promotion reserve /// @param market Address of the given market /// @param amount The amount that will be deposited function depositPromotionReserve (address market, uint256 amount) external isNotETHAddress(market) { depositPromotionReserveInternal(market, amount); } /// @notice Deposit ETH as promotion reserve /// @notice msg.value The amount of ETH that will be deposited function depositPromotionReserve () external payable { depositPromotionReserveInternal(ethAddress, msg.value); } /// @notice Withdraw promotion reserve only by the owner /// @param market Address of the given market /// @param amount The amount that will be withdrawn function withdrawPromotionReserve (address market, uint256 amount) external onlyOwner { (uint256 reserveScaled,) = getPromotionReserve(market); (uint256 debtScaled,) = getPromotionDebt(market); uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals); uint256 increasedDebtScaled = amountScaled.add(debtScaled); require (reserveScaled > increasedDebtScaled, "Amount should be less than max"); marketAssets[market].promotionReserveScaled = reserveScaled.sub(amountScaled); transferFromHoldefi(msg.sender, market, amount); emit PromotionReserveWithdrawn(market, amount); } /// @notice Set Holdefi prices contract only by the owner /// @param newHoldefiPrices Address of the new Holdefi prices contract function setHoldefiPricesContract (HoldefiPricesInterface newHoldefiPrices) external onlyOwner { emit HoldefiPricesContractChanged(address(newHoldefiPrices), address(holdefiPrices)); holdefiPrices = newHoldefiPrices; } /// @notice Promotion reserve and debt settlement /// @param market Address of the given market function reserveSettlement (address market) external { require(msg.sender == address(holdefiSettings), "Sender should be Holdefi Settings contract"); uint256 promotionReserve = marketAssets[market].promotionReserveScaled; uint256 promotionDebt = marketAssets[market].promotionDebtScaled; require(promotionReserve > promotionDebt, "Not enough promotion reserve"); promotionReserve = promotionReserve.sub(promotionDebt); marketAssets[market].promotionReserveScaled = promotionReserve; marketAssets[market].promotionDebtScaled = 0; marketAssets[market].promotionReserveLastUpdateTime = block.timestamp; marketAssets[market].promotionDebtLastUpdateTime = block.timestamp; emit PromotionReserveUpdated(market, promotionReserve); emit PromotionDebtUpdated(market, 0); } /// @notice Update supply index of a market /// @param market Address of the given market function updateSupplyIndex (address market) internal { (uint256 currentSupplyIndex, uint256 supplyRate, uint256 currentTime) = getCurrentSupplyIndex(market); marketAssets[market].supplyIndex = currentSupplyIndex; marketAssets[market].supplyIndexUpdateTime = currentTime; emit UpdateSupplyIndex(market, currentSupplyIndex, supplyRate); } /// @notice Update borrow index of a market /// @param market Address of the given market function updateBorrowIndex (address market) internal { (uint256 currentBorrowIndex,, uint256 currentTime) = getCurrentBorrowIndex(market); marketAssets[market].borrowIndex = currentBorrowIndex; marketAssets[market].borrowIndexUpdateTime = currentTime; emit UpdateBorrowIndex(market, currentBorrowIndex); } /// @notice Update promotion reserve of a market /// @param market Address of the given market function updatePromotionReserve(address market) internal { (uint256 reserveScaled,) = getPromotionReserve(market); marketAssets[market].promotionReserveScaled = reserveScaled; marketAssets[market].promotionReserveLastUpdateTime = block.timestamp; emit PromotionReserveUpdated(market, reserveScaled); } /// @notice Update promotion debt of a market /// @dev Promotion rate will be set to 0 if (promotionDebt >= promotionReserve) /// @param market Address of the given market function updatePromotionDebt(address market) internal { (uint256 debtScaled,) = getPromotionDebt(market); if (marketAssets[market].promotionDebtScaled != debtScaled){ marketAssets[market].promotionDebtScaled = debtScaled; marketAssets[market].promotionDebtLastUpdateTime = block.timestamp; emit PromotionDebtUpdated(market, debtScaled); } if (marketAssets[market].promotionReserveScaled <= debtScaled) { holdefiSettings.resetPromotionRate(market); } } /// @notice transfer ETH or ERC20 asset from this contract function transferFromHoldefi(address receiver, address asset, uint256 amount) internal { bool success = false; if (asset == ethAddress){ (success, ) = receiver.call{value:amount}(""); } else { IERC20 token = IERC20(asset); success = token.transfer(receiver, amount); } require (success, "Cannot Transfer"); } /// @notice transfer ERC20 asset to this contract function transferToHoldefi(address receiver, address asset, uint256 amount) internal { IERC20 token = IERC20(asset); bool success = token.transferFrom(msg.sender, receiver, amount); require (success, "Cannot Transfer"); } /// @notice Perform supply operation function supplyInternal(address account, address market, uint256 amount, uint16 referralCode) internal whenNotPaused("supply") marketIsActive(market) { if (market != ethAddress) { transferToHoldefi(address(this), market, amount); } MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); supplyData.balance = supplyData.balance.add(amount); supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.add(amount); emit Supply( msg.sender, account, market, amount, supplyData.balance, supplyData.interest, supplyData.currentIndex, referralCode ); } /// @notice Perform withdraw supply operation function withdrawSupplyInternal (address account, address market, uint256 amount) internal whenNotPaused("withdrawSupply") { MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); uint256 totalSuppliedBalance = supplyData.balance.add(supplyData.interest); require (totalSuppliedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalSuppliedBalance){ transferAmount = totalSuppliedBalance; } uint256 remaining = 0; if (transferAmount <= supplyData.interest) { supplyData.interest = supplyData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(supplyData.interest); supplyData.interest = 0; supplyData.balance = supplyData.balance.sub(remaining); } supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.sub(remaining); transferFromHoldefi(msg.sender, market, transferAmount); emit WithdrawSupply( msg.sender, account, market, transferAmount, supplyData.balance, supplyData.interest, supplyData.currentIndex ); } /// @notice Perform collateralize operation function collateralizeInternal (address account, address collateral, uint256 amount) internal whenNotPaused("collateralize") collateralIsActive(collateral) { if (collateral != ethAddress) { transferToHoldefi(address(holdefiCollaterals), collateral, amount); } else { transferFromHoldefi(address(holdefiCollaterals), collateral, amount); } uint256 balance = collaterals[account][collateral].balance.add(amount); collaterals[account][collateral].balance = balance; collaterals[account][collateral].lastUpdateTime = block.timestamp; collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.add(amount); emit Collateralize(msg.sender, account, collateral, amount, balance); } /// @notice Perform withdraw collateral operation function withdrawCollateralInternal (address account, address collateral, uint256 amount) internal whenNotPaused("withdrawCollateral") { (uint256 balance,, uint256 borrowPowerValue, uint256 totalBorrowValue,) = getAccountCollateral(account, collateral); require (borrowPowerValue != 0, "Borrow power should not be zero"); uint256 collateralNedeed = 0; if (totalBorrowValue != 0) { uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate; uint256 totalCollateralValue = totalBorrowValue.mul(valueToLoanRate).div(rateDecimals); collateralNedeed = holdefiPrices.getAssetAmountFromValue(collateral, totalCollateralValue); } uint256 maxWithdraw = balance.sub(collateralNedeed); uint256 transferAmount = amount; if (transferAmount > maxWithdraw){ transferAmount = maxWithdraw; } balance = balance.sub(transferAmount); collaterals[account][collateral].balance = balance; collaterals[account][collateral].lastUpdateTime = block.timestamp; collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(transferAmount); holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount); emit WithdrawCollateral(msg.sender, account, collateral, transferAmount, balance); } /// @notice Perform borrow operation function borrowInternal (address account, address market, address collateral, uint256 amount, uint16 referralCode) internal whenNotPaused("borrow") marketIsActive(market) collateralIsActive(collateral) { require ( amount <= (marketAssets[market].totalSupply.sub(marketAssets[market].totalBorrow)), "Amount should be less than cash" ); (,, uint256 borrowPowerValue,,) = getAccountCollateral(account, collateral); uint256 assetToBorrowValue = holdefiPrices.getAssetValueFromAmount(market, amount); require ( borrowPowerValue >= assetToBorrowValue, "Borrow power should be more than new borrow value" ); MarketData memory borrowData; (borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral); borrowData.balance = borrowData.balance.add(amount); borrows[account][collateral][market].balance = borrowData.balance; borrows[account][collateral][market].accumulatedInterest = borrowData.interest; borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex; collaterals[account][collateral].lastUpdateTime = block.timestamp; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.add(amount); transferFromHoldefi(msg.sender, market, amount); emit Borrow( msg.sender, account, market, collateral, amount, borrowData.balance, borrowData.interest, borrowData.currentIndex, referralCode ); } /// @notice Perform repay borrow operation function repayBorrowInternal (address account, address market, address collateral, uint256 amount) internal whenNotPaused("repayBorrow") { MarketData memory borrowData; (borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); require (totalBorrowedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalBorrowedBalance) { transferAmount = totalBorrowedBalance; if (market == ethAddress) { uint256 extra = amount.sub(transferAmount); transferFromHoldefi(msg.sender, ethAddress, extra); } } if (market != ethAddress) { transferToHoldefi(address(this), market, transferAmount); } uint256 remaining = 0; if (transferAmount <= borrowData.interest) { borrowData.interest = borrowData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(borrowData.interest); borrowData.interest = 0; borrowData.balance = borrowData.balance.sub(remaining); } borrows[account][collateral][market].balance = borrowData.balance; borrows[account][collateral][market].accumulatedInterest = borrowData.interest; borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex; collaterals[account][collateral].lastUpdateTime = block.timestamp; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(remaining); emit RepayBorrow ( msg.sender, account, market, collateral, transferAmount, borrowData.balance, borrowData.interest, borrowData.currentIndex ); } /// @notice Perform buy liquidated collateral operation function buyLiquidatedCollateralInternal (address market, address collateral, uint256 marketAmount) internal whenNotPaused("buyLiquidatedCollateral") { uint256 debt = marketDebt[collateral][market]; require (marketAmount <= debt, "Amount should be less than total liquidated assets" ); uint256 collateralAmountWithDiscount = getDiscountedCollateralAmount(market, collateral, marketAmount); uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; require ( collateralAmountWithDiscount <= totalLiquidatedCollateral, "Collateral amount with discount should be less than total liquidated assets" ); if (market != ethAddress) { transferToHoldefi(address(this), market, marketAmount); } collateralAssets[collateral].totalLiquidatedCollateral = totalLiquidatedCollateral.sub(collateralAmountWithDiscount); marketDebt[collateral][market] = debt.sub(marketAmount); holdefiCollaterals.withdraw(collateral, msg.sender, collateralAmountWithDiscount); emit BuyLiquidatedCollateral(market, collateral, marketAmount, collateralAmountWithDiscount); } /// @notice Perform deposit promotion reserve operation function depositPromotionReserveInternal (address market, uint256 amount) internal marketIsActive(market) { if (market != ethAddress) { transferToHoldefi(address(this), market, amount); } uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals); marketAssets[market].promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(amountScaled); emit PromotionReserveDeposited(market, amount); } /// @notice Perform deposit liquidation reserve operation function depositLiquidationReserveInternal (address collateral, uint256 amount) internal collateralIsActive(ethAddress) { if (collateral != ethAddress) { transferToHoldefi(address(holdefiCollaterals), collateral, amount); } else { transferFromHoldefi(address(holdefiCollaterals), collateral, amount); } collateralAssets[ethAddress].totalLiquidatedCollateral = collateralAssets[ethAddress].totalLiquidatedCollateral.add(msg.value); emit LiquidationReserveDeposited(ethAddress, msg.value); } }
@notice Liquidate borrower's collateral @param borrower Address of the borrower who should be liquidated @param market Address of the given market @param collateral Address of the given collateral
function liquidateBorrowerCollateral (address borrower, address market, address collateral) external whenNotPaused("liquidateBorrowerCollateral") { MarketData memory borrowData; (borrowData.balance, borrowData.interest,) = getAccountBorrow(borrower, market, collateral); require(borrowData.balance > 0, "User should have debt"); (uint256 collateralBalance, uint256 timeSinceLastActivity,,, bool underCollateral) = getAccountCollateral(borrower, collateral); require (underCollateral || (timeSinceLastActivity > secondsPerYear), "User should be under collateral or time is over" ); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); uint256 totalBorrowedBalanceValue = holdefiPrices.getAssetValueFromAmount(market, totalBorrowedBalance); uint256 liquidatedCollateralValue = totalBorrowedBalanceValue .mul(holdefiSettings.collateralAssets(collateral).penaltyRate) .div(rateDecimals); uint256 liquidatedCollateral = holdefiPrices.getAssetAmountFromValue(collateral, liquidatedCollateralValue); if (liquidatedCollateral > collateralBalance) { liquidatedCollateral = collateralBalance; } collaterals[borrower][collateral].balance = collateralBalance.sub(liquidatedCollateral); collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(liquidatedCollateral); collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.add(liquidatedCollateral); delete borrows[borrower][collateral][market]; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(borrowData.balance); marketDebt[collateral][market] = marketDebt[collateral][market].add(totalBorrowedBalance); emit CollateralLiquidated(borrower, market, collateral, totalBorrowedBalance, liquidatedCollateral); }
13,514,360
[ 1, 48, 18988, 350, 340, 29759, 264, 1807, 4508, 2045, 287, 225, 29759, 264, 5267, 434, 326, 29759, 264, 10354, 1410, 506, 4501, 26595, 690, 225, 13667, 5267, 434, 326, 864, 13667, 225, 4508, 2045, 287, 5267, 434, 326, 864, 4508, 2045, 287, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 4501, 26595, 340, 38, 15318, 264, 13535, 2045, 287, 261, 2867, 29759, 264, 16, 1758, 13667, 16, 1758, 4508, 2045, 287, 13, 203, 202, 202, 9375, 203, 202, 202, 13723, 1248, 28590, 2932, 549, 26595, 340, 38, 15318, 264, 13535, 2045, 287, 7923, 203, 202, 95, 203, 202, 202, 3882, 278, 751, 3778, 29759, 751, 31, 203, 202, 202, 12, 70, 15318, 751, 18, 12296, 16, 29759, 751, 18, 2761, 395, 16, 13, 273, 23393, 38, 15318, 12, 70, 15318, 264, 16, 13667, 16, 4508, 2045, 287, 1769, 203, 202, 202, 6528, 12, 70, 15318, 751, 18, 12296, 405, 374, 16, 315, 1299, 1410, 1240, 18202, 88, 8863, 203, 203, 202, 202, 12, 11890, 5034, 4508, 2045, 287, 13937, 16, 2254, 5034, 813, 9673, 3024, 6193, 16408, 16, 1426, 3613, 13535, 2045, 287, 13, 273, 7010, 1082, 202, 588, 3032, 13535, 2045, 287, 12, 70, 15318, 264, 16, 4508, 2045, 287, 1769, 203, 202, 202, 6528, 261, 9341, 13535, 2045, 287, 747, 261, 957, 9673, 3024, 6193, 405, 3974, 2173, 5593, 3631, 203, 1082, 202, 6, 1299, 1410, 506, 3613, 4508, 2045, 287, 578, 813, 353, 1879, 6, 203, 202, 202, 1769, 203, 203, 202, 202, 11890, 5034, 2078, 38, 15318, 329, 13937, 273, 29759, 751, 18, 12296, 18, 1289, 12, 70, 15318, 751, 18, 2761, 395, 1769, 203, 202, 202, 11890, 5034, 2078, 38, 15318, 329, 13937, 620, 273, 366, 355, 536, 77, 31862, 18, 588, 6672, 620, 1265, 6275, 12, 27151, 16, 2078, 38, 15318, 329, 13937, 1769, 203, 1082, 2 ]
pragma solidity ^0.5.17; // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } /* * SPDX-License-Identifier: MIT */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address _who) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library SafeERC20 { /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( _token.transfer.selector, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(address(_token), transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the provided token and expects it to be already * verified as a contract. */ function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(address(_token), approveCallData); } function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } } library PctHelpers { using SafeMath for uint256; uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000) function isValid(uint16 _pct) internal pure returns (bool) { return _pct <= PCT_BASE; } function pct(uint256 self, uint16 _pct) internal pure returns (uint256) { return self.mul(uint256(_pct)) / PCT_BASE; } function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) { return self.mul(_pct) / PCT_BASE; } function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) { // No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16) return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE; } } /** * @title Checkpointing - Library to handle a historic set of numeric values */ library Checkpointing { uint256 private constant MAX_UINT192 = uint256(uint192(-1)); string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG"; string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE"; /** * @dev To specify a value at a given point in time, we need to store two values: * - `time`: unit-time value to denote the first time when a value was registered * - `value`: a positive numeric value to registered at a given point in time * * Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used * for it like block numbers, terms, etc. */ struct Checkpoint { uint64 time; uint192 value; } /** * @dev A history simply denotes a list of checkpoints */ struct History { Checkpoint[] history; } /** * @dev Add a new value to a history for a given point in time. This function does not allow to add values previous * to the latest registered value, if the value willing to add corresponds to the latest registered value, it * will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function add(History storage self, uint64 _time, uint256 _value) internal { require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG); _add192(self, _time, uint192(_value)); } /** * @dev Fetch the latest registered value of history, it will return zero if there was no value registered * @param self Checkpoints history to be queried */ function getLast(History storage self) internal view returns (uint256) { uint256 length = self.history.length; if (length > 0) { return uint256(self.history[length - 1].value); } return 0; } /** * @dev Fetch the most recent registered past value of a history based on a given point in time that is not known * how recent it is beforehand. It will return zero if there is no registered value or if given time is * previous to the first registered value. * It uses a binary search. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function get(History storage self, uint64 _time) internal view returns (uint256) { return _binarySearch(self, _time); } /** * @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero * if there is no registered value or if given time is previous to the first registered value. * It uses a linear search starting from the end. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function getRecent(History storage self, uint64 _time) internal view returns (uint256) { return _backwardsLinearSearch(self, _time); } /** * @dev Private function to add a new value to a history for a given point in time. This function does not allow to * add values previous to the latest registered value, if the value willing to add corresponds to the latest * registered value, it will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function _add192(History storage self, uint64 _time, uint192 _value) private { uint256 length = self.history.length; if (length == 0 || self.history[self.history.length - 1].time < _time) { // If there was no value registered or the given point in time is after the latest registered value, // we can insert it to the history directly. self.history.push(Checkpoint(_time, _value)); } else { // If the point in time given for the new value is not after the latest registered value, we must ensure // we are only trying to update the latest value, otherwise we would be changing past data. Checkpoint storage currentCheckpoint = self.history[length - 1]; require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE); currentCheckpoint.value = _value; } } /** * @dev Private function to execute a backwards linear search to find the most recent registered past value of a * history based on a given point in time. It will return zero if there is no registered value or if given time * is previous to the first registered value. Note that this function will be more suitable when we already know * that the time used to index the search is recent in the given history. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } uint256 index = length - 1; Checkpoint storage checkpoint = self.history[index]; while (index > 0 && checkpoint.time > _time) { index--; checkpoint = self.history[index]; } return checkpoint.time > _time ? 0 : uint256(checkpoint.value); } /** * @dev Private function execute a binary search to find the most recent registered past value of a history based on * a given point in time. It will return zero if there is no registered value or if given time is previous to * the first registered value. Note that this function will be more suitable when don't know how recent the * time used to index may be. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _binarySearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } // If the requested time is equal to or after the time of the latest registered value, return latest value uint256 lastIndex = length - 1; if (_time >= self.history[lastIndex].time) { return uint256(self.history[lastIndex].value); } // If the requested time is previous to the first registered value, return zero to denote missing checkpoint if (_time < self.history[0].time) { return 0; } // Execute a binary search between the checkpointed times of the history uint256 low = 0; uint256 high = lastIndex; while (high > low) { // No need for SafeMath: for this to overflow array size should be ~2^255 uint256 mid = (high + low + 1) / 2; Checkpoint storage checkpoint = self.history[mid]; uint64 midTime = checkpoint.time; if (_time > midTime) { low = mid; } else if (_time < midTime) { // No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1 high = mid - 1; } else { return uint256(checkpoint.value); } } return uint256(self.history[low].value); } } /** * @title HexSumTree - Library to operate checkpointed 16-ary (hex) sum trees. * @dev A sum tree is a particular case of a tree where the value of a node is equal to the sum of the values of its * children. This library provides a set of functions to operate 16-ary sum trees, i.e. trees where every non-leaf * node has 16 children and its value is equivalent to the sum of the values of all of them. Additionally, a * checkpointed tree means that each time a value on a node is updated, its previous value will be saved to allow * accessing historic information. * * Example of a checkpointed binary sum tree: * * CURRENT PREVIOUS * * Level 2 100 ---------------------------------------- 70 * ______|_______ ______|_______ * / \ / \ * Level 1 34 66 ------------------------- 23 47 * _____|_____ _____|_____ _____|_____ _____|_____ * / \ / \ / \ / \ * Level 0 22 12 53 13 ----------- 22 1 17 30 * */ library HexSumTree { using SafeMath for uint256; using Checkpointing for Checkpointing.History; string private constant ERROR_UPDATE_OVERFLOW = "SUM_TREE_UPDATE_OVERFLOW"; string private constant ERROR_KEY_DOES_NOT_EXIST = "SUM_TREE_KEY_DOES_NOT_EXIST"; string private constant ERROR_SEARCH_OUT_OF_BOUNDS = "SUM_TREE_SEARCH_OUT_OF_BOUNDS"; string private constant ERROR_MISSING_SEARCH_VALUES = "SUM_TREE_MISSING_SEARCH_VALUES"; // Constants used to perform tree computations // To change any the following constants, the following relationship must be kept: 2^BITS_IN_NIBBLE = CHILDREN // The max depth of the tree will be given by: BITS_IN_NIBBLE * MAX_DEPTH = 256 (so in this case it's 64) uint256 private constant CHILDREN = 16; uint256 private constant BITS_IN_NIBBLE = 4; // All items are leaves, inserted at height or level zero. The root height will be increasing as new levels are inserted in the tree. uint256 private constant ITEMS_LEVEL = 0; // Tree nodes are identified with a 32-bytes length key. Leaves are identified with consecutive incremental keys // starting with 0x0000000000000000000000000000000000000000000000000000000000000000, while non-leaf nodes' keys // are computed based on their level and their children keys. uint256 private constant BASE_KEY = 0; // Timestamp used to checkpoint the first value of the tree height during initialization uint64 private constant INITIALIZATION_INITIAL_TIME = uint64(0); /** * @dev The tree is stored using the following structure: * - nodes: A mapping indexed by a pair (level, key) with a history of the values for each node (level -> key -> value). * - height: A history of the heights of the tree. Minimum height is 1, a root with 16 children. * - nextKey: The next key to be used to identify the next new value that will be inserted into the tree. */ struct Tree { uint256 nextKey; Checkpointing.History height; mapping (uint256 => mapping (uint256 => Checkpointing.History)) nodes; } /** * @dev Search params to traverse the tree caching previous results: * - time: Point in time to query the values being searched, this value shouldn't change during a search * - level: Level being analyzed for the search, it starts at the level under the root and decrements till the leaves * - parentKey: Key of the parent of the nodes being analyzed at the given level for the search * - foundValues: Number of values in the list being searched that were already found, it will go from 0 until the size of the list * - visitedTotal: Total sum of values that were already visited during the search, it will go from 0 until the tree total */ struct SearchParams { uint64 time; uint256 level; uint256 parentKey; uint256 foundValues; uint256 visitedTotal; } /** * @dev Initialize tree setting the next key and first height checkpoint */ function init(Tree storage self) internal { self.height.add(INITIALIZATION_INITIAL_TIME, ITEMS_LEVEL + 1); self.nextKey = BASE_KEY; } /** * @dev Insert a new item to the tree at given point in time * @param _time Point in time to register the given value * @param _value New numeric value to be added to the tree * @return Unique key identifying the new value inserted */ function insert(Tree storage self, uint64 _time, uint256 _value) internal returns (uint256) { // As the values are always stored in the leaves of the tree (level 0), the key to index each of them will be // always incrementing, starting from zero. Add a new level if necessary. uint256 key = self.nextKey++; _addLevelIfNecessary(self, key, _time); // If the new value is not zero, first set the value of the new leaf node, then add a new level at the top of // the tree if necessary, and finally update sums cached in all the non-leaf nodes. if (_value > 0) { _add(self, ITEMS_LEVEL, key, _time, _value); _updateSums(self, key, _time, _value, true); } return key; } /** * @dev Set the value of a leaf node indexed by its key at given point in time * @param _time Point in time to set the given value * @param _key Key of the leaf node to be set in the tree * @param _value New numeric value to be set for the given key */ function set(Tree storage self, uint256 _key, uint64 _time, uint256 _value) internal { require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST); // Set the new value for the requested leaf node uint256 lastValue = getItem(self, _key); _add(self, ITEMS_LEVEL, _key, _time, _value); // Update sums cached in the non-leaf nodes. Note that overflows are being checked at the end of the whole update. if (_value > lastValue) { _updateSums(self, _key, _time, _value - lastValue, true); } else if (_value < lastValue) { _updateSums(self, _key, _time, lastValue - _value, false); } } /** * @dev Update the value of a non-leaf node indexed by its key at given point in time based on a delta * @param _key Key of the leaf node to be updated in the tree * @param _time Point in time to update the given value * @param _delta Numeric delta to update the value of the given key * @param _positive Boolean to tell whether the given delta should be added to or subtracted from the current value */ function update(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) internal { require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST); // Update the value of the requested leaf node based on the given delta uint256 lastValue = getItem(self, _key); uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta); _add(self, ITEMS_LEVEL, _key, _time, newValue); // Update sums cached in the non-leaf nodes. Note that overflows is being checked at the end of the whole update. _updateSums(self, _key, _time, _delta, _positive); } /** * @dev Search a list of values in the tree at a given point in time. It will return a list with the nearest * high value in case a value cannot be found. This function assumes the given list of given values to be * searched is in ascending order. In case of searching a value out of bounds, it will return zeroed results. * @param _values Ordered list of values to be searched in the tree * @param _time Point in time to query the values being searched * @return keys List of keys found for each requested value in the same order * @return values List of node values found for each requested value in the same order */ function search(Tree storage self, uint256[] memory _values, uint64 _time) internal view returns (uint256[] memory keys, uint256[] memory values) { require(_values.length > 0, ERROR_MISSING_SEARCH_VALUES); // Throw out-of-bounds error if there are no items in the tree or the highest value being searched is greater than the total uint256 total = getRecentTotalAt(self, _time); // No need for SafeMath: positive length of array already checked require(total > 0 && total > _values[_values.length - 1], ERROR_SEARCH_OUT_OF_BOUNDS); // Build search params for the first iteration uint256 rootLevel = getRecentHeightAt(self, _time); SearchParams memory searchParams = SearchParams(_time, rootLevel.sub(1), BASE_KEY, 0, 0); // These arrays will be used to fill in the results. We are passing them as parameters to avoid extra copies uint256 length = _values.length; keys = new uint256[](length); values = new uint256[](length); _search(self, _values, searchParams, keys, values); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree */ function getTotal(Tree storage self) internal view returns (uint256) { uint256 rootLevel = getHeight(self); return getNode(self, rootLevel, BASE_KEY); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time * It uses a binary search for the root node, a linear one for the height. * @param _time Point in time to query the sum of all the items (leaves) stored in the tree */ function getTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) { uint256 rootLevel = getRecentHeightAt(self, _time); return getNodeAt(self, rootLevel, BASE_KEY, _time); } /** * @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time * It uses a linear search starting from the end. * @param _time Point in time to query the sum of all the items (leaves) stored in the tree */ function getRecentTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) { uint256 rootLevel = getRecentHeightAt(self, _time); return getRecentNodeAt(self, rootLevel, BASE_KEY, _time); } /** * @dev Tell the value of a certain leaf indexed by a given key * @param _key Key of the leaf node querying the value of */ function getItem(Tree storage self, uint256 _key) internal view returns (uint256) { return getNode(self, ITEMS_LEVEL, _key); } /** * @dev Tell the value of a certain leaf indexed by a given key at a given point in time * It uses a binary search. * @param _key Key of the leaf node querying the value of * @param _time Point in time to query the value of the requested leaf */ function getItemAt(Tree storage self, uint256 _key, uint64 _time) internal view returns (uint256) { return getNodeAt(self, ITEMS_LEVEL, _key, _time); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of */ function getNode(Tree storage self, uint256 _level, uint256 _key) internal view returns (uint256) { return self.nodes[_level][_key].getLast(); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time * It uses a binary search. * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of * @param _time Point in time to query the value of the requested node */ function getNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) { return self.nodes[_level][_key].get(_time); } /** * @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time * It uses a linear search starting from the end. * @param _level Level of the node querying the value of * @param _key Key of the node querying the value of * @param _time Point in time to query the value of the requested node */ function getRecentNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) { return self.nodes[_level][_key].getRecent(_time); } /** * @dev Tell the height of the tree */ function getHeight(Tree storage self) internal view returns (uint256) { return self.height.getLast(); } /** * @dev Tell the height of the tree at a given point in time * It uses a linear search starting from the end. * @param _time Point in time to query the height of the tree */ function getRecentHeightAt(Tree storage self, uint64 _time) internal view returns (uint256) { return self.height.getRecent(_time); } /** * @dev Private function to update the values of all the ancestors of the given leaf node based on the delta updated * @param _key Key of the leaf node to update the ancestors of * @param _time Point in time to update the ancestors' values of the given leaf node * @param _delta Numeric delta to update the ancestors' values of the given leaf node * @param _positive Boolean to tell whether the given delta should be added to or subtracted from ancestors' values */ function _updateSums(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) private { uint256 mask = uint256(-1); uint256 ancestorKey = _key; uint256 currentHeight = getHeight(self); for (uint256 level = ITEMS_LEVEL + 1; level <= currentHeight; level++) { // Build a mask to get the key of the ancestor at a certain level. For example: // Level 0: leaves don't have children // Level 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 leaves) // Level 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 leaves) // ... // Level 63: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 leaves - tree max height) mask = mask << BITS_IN_NIBBLE; // The key of the ancestor at that level "i" is equivalent to the "(64 - i)-th" most significant nibbles // of the ancestor's key of the previous level "i - 1". Thus, we can compute the key of an ancestor at a // certain level applying the mask to the ancestor's key of the previous level. Note that for the first // iteration, the key of the ancestor of the previous level is simply the key of the leaf being updated. ancestorKey = ancestorKey & mask; // Update value uint256 lastValue = getNode(self, level, ancestorKey); uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta); _add(self, level, ancestorKey, _time, newValue); } // Check if there was an overflow. Note that we only need to check the value stored in the root since the // sum only increases going up through the tree. require(!_positive || getNode(self, currentHeight, ancestorKey) >= _delta, ERROR_UPDATE_OVERFLOW); } /** * @dev Private function to add a new level to the tree based on a new key that will be inserted * @param _newKey New key willing to be inserted in the tree * @param _time Point in time when the new key will be inserted */ function _addLevelIfNecessary(Tree storage self, uint256 _newKey, uint64 _time) private { uint256 currentHeight = getHeight(self); if (_shouldAddLevel(currentHeight, _newKey)) { // Max height allowed for the tree is 64 since we are using node keys of 32 bytes. However, note that we // are not checking if said limit has been hit when inserting new leaves to the tree, for the purpose of // this system having 2^256 items inserted is unrealistic. uint256 newHeight = currentHeight + 1; uint256 rootValue = getNode(self, currentHeight, BASE_KEY); _add(self, newHeight, BASE_KEY, _time, rootValue); self.height.add(_time, newHeight); } } /** * @dev Private function to register a new value in the history of a node at a given point in time * @param _level Level of the node to add a new value at a given point in time to * @param _key Key of the node to add a new value at a given point in time to * @param _time Point in time to register a value for the given node * @param _value Numeric value to be registered for the given node at a given point in time */ function _add(Tree storage self, uint256 _level, uint256 _key, uint64 _time, uint256 _value) private { self.nodes[_level][_key].add(_time, _value); } /** * @dev Recursive pre-order traversal function * Every time it checks a node, it traverses the input array to find the initial subset of elements that are * below its accumulated value and passes that sub-array to the next iteration. Actually, the array is always * the same, to avoid making extra copies, it just passes the number of values already found , to avoid * checking values that went through a different branch. The same happens with the result lists of keys and * values, these are the same on every recursion step. The visited total is carried over each iteration to * avoid having to subtract all elements in the array. * @param _values Ordered list of values to be searched in the tree * @param _params Search parameters for the current recursive step * @param _resultKeys List of keys found for each requested value in the same order * @param _resultValues List of node values found for each requested value in the same order */ function _search( Tree storage self, uint256[] memory _values, SearchParams memory _params, uint256[] memory _resultKeys, uint256[] memory _resultValues ) private view { uint256 levelKeyLessSignificantNibble = _params.level.mul(BITS_IN_NIBBLE); for (uint256 childNumber = 0; childNumber < CHILDREN; childNumber++) { // Return if we already found enough values if (_params.foundValues >= _values.length) { break; } // Build child node key shifting the child number to the position of the less significant nibble of // the keys for the level being analyzed, and adding it to the key of the parent node. For example, // for a tree with height 5, if we are checking the children of the second node of the level 3, whose // key is 0x0000000000000000000000000000000000000000000000000000000000001000, its children keys are: // Child 0: 0x0000000000000000000000000000000000000000000000000000000000001000 // Child 1: 0x0000000000000000000000000000000000000000000000000000000000001100 // Child 2: 0x0000000000000000000000000000000000000000000000000000000000001200 // ... // Child 15: 0x0000000000000000000000000000000000000000000000000000000000001f00 uint256 childNodeKey = _params.parentKey.add(childNumber << levelKeyLessSignificantNibble); uint256 childNodeValue = getRecentNodeAt(self, _params.level, childNodeKey, _params.time); // Check how many values belong to the subtree of this node. As they are ordered, it will be a contiguous // subset starting from the beginning, so we only need to know the length of that subset. uint256 newVisitedTotal = _params.visitedTotal.add(childNodeValue); uint256 subtreeIncludedValues = _getValuesIncludedInSubtree(_values, _params.foundValues, newVisitedTotal); // If there are some values included in the subtree of the child node, visit them if (subtreeIncludedValues > 0) { // If the child node being analyzed is a leaf, add it to the list of results a number of times equals // to the number of values that were included in it. Otherwise, descend one level. if (_params.level == ITEMS_LEVEL) { _copyFoundNode(_params.foundValues, subtreeIncludedValues, childNodeKey, _resultKeys, childNodeValue, _resultValues); } else { SearchParams memory nextLevelParams = SearchParams( _params.time, _params.level - 1, // No need for SafeMath: we already checked above that the level being checked is greater than zero childNodeKey, _params.foundValues, _params.visitedTotal ); _search(self, _values, nextLevelParams, _resultKeys, _resultValues); } // Update the number of values that were already found _params.foundValues = _params.foundValues.add(subtreeIncludedValues); } // Update the visited total for the next node in this level _params.visitedTotal = newVisitedTotal; } } /** * @dev Private function to check if a new key can be added to the tree based on the current height of the tree * @param _currentHeight Current height of the tree to check if it supports adding the given key * @param _newKey Key willing to be added to the tree with the given current height * @return True if the current height of the tree should be increased to add the new key, false otherwise. */ function _shouldAddLevel(uint256 _currentHeight, uint256 _newKey) private pure returns (bool) { // Build a mask that will match all the possible keys for the given height. For example: // Height 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 keys) // Height 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 keys) // ... // Height 64: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 keys - tree max height) uint256 shift = _currentHeight.mul(BITS_IN_NIBBLE); uint256 mask = uint256(-1) << shift; // Check if the given key can be represented in the tree with the current given height using the mask. return (_newKey & mask) != 0; } /** * @dev Private function to tell how many values of a list can be found in a subtree * @param _values List of values being searched in ascending order * @param _foundValues Number of values that were already found and should be ignore * @param _subtreeTotal Total sum of the given subtree to check the numbers that are included in it * @return Number of values in the list that are included in the given subtree */ function _getValuesIncludedInSubtree(uint256[] memory _values, uint256 _foundValues, uint256 _subtreeTotal) private pure returns (uint256) { // Look for all the values that can be found in the given subtree uint256 i = _foundValues; while (i < _values.length && _values[i] < _subtreeTotal) { i++; } return i - _foundValues; } /** * @dev Private function to copy a node a given number of times to a results list. This function assumes the given * results list have enough size to support the requested copy. * @param _from Index of the results list to start copying the given node * @param _times Number of times the given node will be copied * @param _key Key of the node to be copied * @param _resultKeys Lists of key results to copy the given node key to * @param _value Value of the node to be copied * @param _resultValues Lists of value results to copy the given node value to */ function _copyFoundNode( uint256 _from, uint256 _times, uint256 _key, uint256[] memory _resultKeys, uint256 _value, uint256[] memory _resultValues ) private pure { for (uint256 i = 0; i < _times; i++) { _resultKeys[_from + i] = _key; _resultValues[_from + i] = _value; } } } /** * @title GuardiansTreeSortition - Library to perform guardians sortition over a `HexSumTree` */ library GuardiansTreeSortition { using SafeMath for uint256; using HexSumTree for HexSumTree.Tree; string private constant ERROR_INVALID_INTERVAL_SEARCH = "TREE_INVALID_INTERVAL_SEARCH"; string private constant ERROR_SORTITION_LENGTHS_MISMATCH = "TREE_SORTITION_LENGTHS_MISMATCH"; /** * @dev Search random items in the tree based on certain restrictions * @param _termRandomness Randomness to compute the seed for the draft * @param _disputeId Identification number of the dispute to draft guardians for * @param _termId Current term when the draft is being computed * @param _selectedGuardians Number of guardians already selected for the draft * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _roundRequestedGuardians Total number of guardians requested to be drafted * @param _sortitionIteration Number of sortitions already performed for the given draft * @return guardiansIds List of guardian ids obtained based on the requested search * @return guardiansBalances List of active balances for each guardian obtained based on the requested search */ function batchedRandomSearch( HexSumTree.Tree storage tree, bytes32 _termRandomness, uint256 _disputeId, uint64 _termId, uint256 _selectedGuardians, uint256 _batchRequestedGuardians, uint256 _roundRequestedGuardians, uint256 _sortitionIteration ) internal view returns (uint256[] memory guardiansIds, uint256[] memory guardiansBalances) { (uint256 low, uint256 high) = getSearchBatchBounds( tree, _termId, _selectedGuardians, _batchRequestedGuardians, _roundRequestedGuardians ); uint256[] memory balances = _computeSearchRandomBalances( _termRandomness, _disputeId, _sortitionIteration, _batchRequestedGuardians, low, high ); (guardiansIds, guardiansBalances) = tree.search(balances, _termId); require(guardiansIds.length == guardiansBalances.length, ERROR_SORTITION_LENGTHS_MISMATCH); require(guardiansIds.length == _batchRequestedGuardians, ERROR_SORTITION_LENGTHS_MISMATCH); } /** * @dev Get the bounds for a draft batch based on the active balances of the guardians * @param _termId Term ID of the active balances that will be used to compute the boundaries * @param _selectedGuardians Number of guardians already selected for the draft * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _roundRequestedGuardians Total number of guardians requested to be drafted * @return low Low bound to be used for the sortition to draft the requested number of guardians for the given batch * @return high High bound to be used for the sortition to draft the requested number of guardians for the given batch */ function getSearchBatchBounds( HexSumTree.Tree storage tree, uint64 _termId, uint256 _selectedGuardians, uint256 _batchRequestedGuardians, uint256 _roundRequestedGuardians ) internal view returns (uint256 low, uint256 high) { uint256 totalActiveBalance = tree.getRecentTotalAt(_termId); low = _selectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians); uint256 newSelectedGuardians = _selectedGuardians.add(_batchRequestedGuardians); high = newSelectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians); } /** * @dev Get a random list of active balances to be searched in the guardians tree for a given draft batch * @param _termRandomness Randomness to compute the seed for the draft * @param _disputeId Identification number of the dispute to draft guardians for (for randomness) * @param _sortitionIteration Number of sortitions already performed for the given draft (for randomness) * @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft * @param _lowBatchBound Low bound to be used for the sortition batch to draft the requested number of guardians * @param _highBatchBound High bound to be used for the sortition batch to draft the requested number of guardians * @return Random list of active balances to be searched in the guardians tree for the given draft batch */ function _computeSearchRandomBalances( bytes32 _termRandomness, uint256 _disputeId, uint256 _sortitionIteration, uint256 _batchRequestedGuardians, uint256 _lowBatchBound, uint256 _highBatchBound ) internal pure returns (uint256[] memory) { // Calculate the interval to be used to search the balances in the tree. Since we are using a modulo function to compute the // random balances to be searched, intervals will be closed on the left and open on the right, for example [0,10). require(_highBatchBound > _lowBatchBound, ERROR_INVALID_INTERVAL_SEARCH); uint256 interval = _highBatchBound - _lowBatchBound; // Compute an ordered list of random active balance to be searched in the guardians tree uint256[] memory balances = new uint256[](_batchRequestedGuardians); for (uint256 batchGuardianNumber = 0; batchGuardianNumber < _batchRequestedGuardians; batchGuardianNumber++) { // Compute a random seed using: // - The inherent randomness associated to the term from blockhash // - The disputeId, so 2 disputes in the same term will have different outcomes // - The sortition iteration, to avoid getting stuck if resulting guardians are dismissed due to locked balance // - The guardian number in this batch bytes32 seed = keccak256(abi.encodePacked(_termRandomness, _disputeId, _sortitionIteration, batchGuardianNumber)); // Compute a random active balance to be searched in the guardians tree using the generated seed within the // boundaries computed for the current batch. balances[batchGuardianNumber] = _lowBatchBound.add(uint256(seed) % interval); // Make sure it's ordered, flip values if necessary for (uint256 i = batchGuardianNumber; i > 0 && balances[i] < balances[i - 1]; i--) { uint256 tmp = balances[i - 1]; balances[i - 1] = balances[i]; balances[i] = tmp; } } return balances; } } /* * SPDX-License-Identifier: MIT */ interface ILockManager { /** * @dev Tell whether a user can unlock a certain amount of tokens */ function canUnlock(address user, uint256 amount) external view returns (bool); } /* * SPDX-License-Identifier: MIT */ interface IGuardiansRegistry { /** * @dev Assign a requested amount of guardian tokens to a guardian * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external; /** * @dev Burn a requested amount of guardian tokens * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external; /** * @dev Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length); /** * @dev Slash a set of guardians based on their votes compared to the winning ruling * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external returns (uint256 collectedTokens); /** * @dev Try to collect a certain amount of tokens from a guardian for the next term * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool); /** * @dev Lock a guardian's withdrawals until a certain term ID * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external; /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256); /** * @dev Tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256); } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } contract ACL { string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE"; string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN"; string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT"; enum BulkOp { Grant, Revoke, Freeze } address internal constant FREEZE_FLAG = address(1); address internal constant ANY_ADDR = address(-1); // List of all roles assigned to different addresses mapping (bytes32 => mapping (address => bool)) public roles; event Granted(bytes32 indexed id, address indexed who); event Revoked(bytes32 indexed id, address indexed who); event Frozen(bytes32 indexed id); /** * @dev Tell whether an address has a role assigned * @param _who Address being queried * @param _id ID of the role being checked * @return True if the requested address has assigned the given role, false otherwise */ function hasRole(address _who, bytes32 _id) public view returns (bool) { return roles[_id][_who] || roles[_id][ANY_ADDR]; } /** * @dev Tell whether a role is frozen * @param _id ID of the role being checked * @return True if the given role is frozen, false otherwise */ function isRoleFrozen(bytes32 _id) public view returns (bool) { return roles[_id][FREEZE_FLAG]; } /** * @dev Internal function to grant a role to a given address * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function _grant(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE); if (!hasRole(_who, _id)) { roles[_id][_who] = true; emit Granted(_id, _who); } } /** * @dev Internal function to revoke a role from a given address * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function _revoke(bytes32 _id, address _who) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); if (hasRole(_who, _id)) { roles[_id][_who] = false; emit Revoked(_id, _who); } } /** * @dev Internal function to freeze a role * @param _id ID of the role to be frozen */ function _freeze(bytes32 _id) internal { require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN); roles[_id][FREEZE_FLAG] = true; emit Frozen(_id); } /** * @dev Internal function to enact a bulk list of ACL operations */ function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal { require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT); for (uint256 i = 0; i < _op.length; i++) { BulkOp op = _op[i]; if (op == BulkOp.Grant) { _grant(_id[i], _who[i]); } else if (op == BulkOp.Revoke) { _revoke(_id[i], _who[i]); } else if (op == BulkOp.Freeze) { _freeze(_id[i]); } } } } contract ModuleIds { // DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER")) bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6; // GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY")) bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe; // Voting module ID - keccak256(abi.encodePacked("VOTING")) bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346; // PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK")) bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418; // Treasury module ID - keccak256(abi.encodePacked("TREASURY")) bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7; } interface IModulesLinker { /** * @notice Update the implementations of a list of modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external; } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules library Uint256Helpers { uint256 private constant MAX_UINT8 = uint8(-1); uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG"; string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint8(uint256 a) internal pure returns (uint8) { require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG); return uint8(a); } function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG); return uint64(a); } } // Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol // Adapted to use pragma ^0.5.17 and satisfy our linter rules contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } interface IClock { /** * @dev Ensure that the current term of the clock is up-to-date * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64); /** * @dev Transition up to a certain number of terms to leave the clock up-to-date * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64); /** * @dev Ensure that a certain term has its randomness set * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32); /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64); /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64); /** * @dev Tell the number of terms the clock should transition to be up-to-date * @return Number of terms the clock should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64); /** * @dev Tell the information related to a term based on its ID * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness); /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view returns (bytes32); } contract CourtClock is IClock, TimeHelpers { using SafeMath64 for uint64; string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST"; string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG"; string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET"; string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE"; string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME"; string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS"; string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS"; string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT"; string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME"; // Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1; // Max duration in seconds that a term can last uint64 internal constant MAX_TERM_DURATION = 365 days; // Max time until first term starts since contract is deployed uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION; struct Term { uint64 startTime; // Timestamp when the term started uint64 randomnessBN; // Block number for entropy bytes32 randomness; // Entropy from randomnessBN block hash } // Duration in seconds for each term of the Court uint64 private termDuration; // Last ensured term id uint64 private termId; // List of Court terms indexed by id mapping (uint64 => Term) private terms; event Heartbeat(uint64 previousTermId, uint64 currentTermId); event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime); /** * @dev Ensure a certain term has already been processed * @param _termId Identification number of the term to be checked */ modifier termExists(uint64 _termId) { require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) */ constructor(uint64[2] memory _termParams) public { uint64 _termDuration = _termParams[0]; uint64 _firstTermStartTime = _termParams[1]; require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG); require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME); require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME); termDuration = _termDuration; // No need for SafeMath: we already checked values above terms[0].startTime = _firstTermStartTime - _termDuration; } /** * @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` * terms, the heartbeat function must be called manually instead. * @return Identification number of the current term */ function ensureCurrentTerm() external returns (uint64) { return _ensureCurrentTerm(); } /** * @notice Transition up to `_maxRequestedTransitions` terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the term ID after executing the heartbeat transitions */ function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) { return _heartbeat(_maxRequestedTransitions); } /** * @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there * were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given * round will be able to be drafted in the following term. * @return Randomness of the current term */ function ensureCurrentTermRandomness() external returns (bytes32) { // If the randomness for the given term was already computed, return uint64 currentTermId = termId; Term storage term = terms[currentTermId]; bytes32 termRandomness = term.randomness; if (termRandomness != bytes32(0)) { return termRandomness; } // Compute term randomness bytes32 newRandomness = _computeTermRandomness(currentTermId); require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE); term.randomness = newRandomness; return newRandomness; } /** * @dev Tell the term duration of the Court * @return Duration in seconds of the Court term */ function getTermDuration() external view returns (uint64) { return termDuration; } /** * @dev Tell the last ensured term identification number * @return Identification number of the last ensured term */ function getLastEnsuredTermId() external view returns (uint64) { return _lastEnsuredTermId(); } /** * @dev Tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function getCurrentTermId() external view returns (uint64) { return _currentTermId(); } /** * @dev Tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function getNeededTermTransitions() external view returns (uint64) { return _neededTermTransitions(); } /** * @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the * information returned won't be computed yet. This function allows querying future terms that were not computed yet. * @param _termId ID of the term being queried * @return startTime Term start time * @return randomnessBN Block number used for randomness in the requested term * @return randomness Randomness computed for the requested term */ function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) { Term storage term = terms[_termId]; return (term.startTime, term.randomnessBN, term.randomness); } /** * @dev Tell the randomness of a term even if it wasn't computed yet * @param _termId Identification number of the term being queried * @return Randomness of the requested term */ function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) { return _computeTermRandomness(_termId); } /** * @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than * `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually. * @return Identification number of the resultant term ID after executing the corresponding transitions */ function _ensureCurrentTerm() internal returns (uint64) { // Check the required number of transitions does not exceeds the max allowed number to be processed automatically uint64 requiredTransitions = _neededTermTransitions(); require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS); // If there are no transitions pending, return the last ensured term id if (uint256(requiredTransitions) == 0) { return termId; } // Process transition if there is at least one pending return _heartbeat(requiredTransitions); } /** * @dev Internal function to transition the Court terms up to a requested number of terms * @param _maxRequestedTransitions Max number of term transitions allowed by the sender * @return Identification number of the resultant term ID after executing the requested transitions */ function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) { // Transition the minimum number of terms between the amount requested and the amount actually needed uint64 neededTransitions = _neededTermTransitions(); uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions); require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS); uint64 blockNumber = getBlockNumber64(); uint64 previousTermId = termId; uint64 currentTermId = previousTermId; for (uint256 transition = 1; transition <= transitions; transition++) { // Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64, // even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is // already assumed to fit in uint64. Term storage previousTerm = terms[currentTermId++]; Term storage currentTerm = terms[currentTermId]; _onTermTransitioned(currentTermId); // Set the start time of the new term. Note that we are using a constant term duration value to guarantee // equally long terms, regardless of heartbeats. currentTerm.startTime = previousTerm.startTime.add(termDuration); // In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a // block number that is set once the term has started. Note that this information could not be known beforehand. currentTerm.randomnessBN = blockNumber + 1; } termId = currentTermId; emit Heartbeat(previousTermId, currentTermId); return currentTermId; } /** * @dev Internal function to delay the first term start time only if it wasn't reached yet * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function _delayStartTime(uint64 _newFirstTermStartTime) internal { require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT); Term storage term = terms[0]; uint64 currentFirstTermStartTime = term.startTime.add(termDuration); require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME); // No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration` term.startTime = _newFirstTermStartTime - termDuration; emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime); } /** * @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior. * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal; /** * @dev Internal function to tell the last ensured term identification number * @return Identification number of the last ensured term */ function _lastEnsuredTermId() internal view returns (uint64) { return termId; } /** * @dev Internal function to tell the current term identification number. Note that there may be pending term transitions. * @return Identification number of the current term */ function _currentTermId() internal view returns (uint64) { return termId.add(_neededTermTransitions()); } /** * @dev Internal function to tell the number of terms the Court should transition to be up-to-date * @return Number of terms the Court should transition to be up-to-date */ function _neededTermTransitions() internal view returns (uint64) { // Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case, // no term transitions are required. uint64 currentTermStartTime = terms[termId].startTime; if (getTimestamp64() < currentTermStartTime) { return uint64(0); } // No need for SafeMath: we already know that the start time of the current term is in the past return (getTimestamp64() - currentTermStartTime) / termDuration; } /** * @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This * function assumes the given term exists. To determine the randomness factor for a term we use the hash of a * block number that is set once the term has started to ensure it cannot be known beforehand. Note that the * hash function being used only works for the 256 most recent block numbers. * @param _termId Identification number of the term being queried * @return Randomness computed for the given term */ function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) { Term storage term = terms[_termId]; require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET); return blockhash(term.randomnessBN); } } interface IConfig { /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); } contract CourtConfigData { struct Config { FeesConfig fees; // Full fees-related config DisputesConfig disputes; // Full disputes-related config uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court } struct FeesConfig { IERC20 token; // ERC20 token to be used for the fees of the Court uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000) uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians } struct DisputesConfig { uint64 evidenceTerms; // Max submitting evidence period duration in terms uint64 commitTerms; // Committing period duration in terms uint64 revealTerms; // Revealing period duration in terms uint64 appealTerms; // Appealing period duration in terms uint64 appealConfirmTerms; // Confirmation appeal period duration in terms uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked uint256 maxRegularAppealRounds; // Before the final appeal uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000) uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000) } struct DraftConfig { IERC20 feeToken; // ERC20 token to be used for the fees of the Court uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians } } contract CourtConfig is IConfig, CourtConfigData { using SafeMath64 for uint64; using PctHelpers for uint256; string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM"; string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT"; string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT"; string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS"; string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION"; string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER"; string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR"; string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR"; string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE"; // Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year) uint64 internal constant MAX_ADJ_STATE_DURATION = 8670; // Cap the max number of regular appeal rounds uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10; // Future term ID in which a config change has been scheduled uint64 private configChangeTermId; // List of all the configs used in the Court Config[] private configs; // List of configs indexed by id mapping (uint64 => uint256) private configIdByTerm; event NewConfig(uint64 fromTermId, uint64 courtConfigId); /** * @dev Constructor function * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public { // Leave config at index 0 empty for non-scheduled config changes configs.length = 1; _setConfig( 0, 0, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ); /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct); /** * @dev Tell the min active balance config at a certain term * @param _termId Term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256); /** * @dev Tell the term identification number of the next scheduled config change * @return Term identification number of the next scheduled config change */ function getConfigChangeTermId() external view returns (uint64) { return configChangeTermId; } /** * @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none * @param _termId Identification number of the new current term that has been transitioned */ function _ensureTermConfig(uint64 _termId) internal { // If the term being transitioned had no config change scheduled, keep the previous one uint256 currentConfigId = configIdByTerm[_termId]; if (currentConfigId == 0) { uint256 previousConfigId = configIdByTerm[_termId.sub(1)]; configIdByTerm[_termId] = previousConfigId; } } /** * @dev Assumes that sender it's allowed (either it's from governor or it's on init) * @param _termId Identification number of the current Court term * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees. * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function _setConfig( uint64 _termId, uint64 _fromTermId, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) internal { // If the current term is not zero, changes must be scheduled at least after the current period. // No need to ensure delays for on-going disputes since these already use their creation term for that. require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM); // Make sure appeal collateral factors are greater than zero require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR); // Make sure the given penalty and final round reduction pcts are not greater than 100% require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT); require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT); // Disputes must request at least one guardian to be drafted initially require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER); // Prevent that further rounds have zero guardians require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR); // Make sure the max number of appeals allowed does not reach the limit uint256 _maxRegularAppealRounds = _roundParams[2]; bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT; require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS); // Make sure each adjudication round phase duration is valid for (uint i = 0; i < _roundStateDurations.length; i++) { require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION); } // Make sure min active balance is not zero require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE); // If there was a config change already scheduled, reset it (in that case we will overwrite last array item). // Otherwise, schedule a new config. if (configChangeTermId > _termId) { configIdByTerm[configChangeTermId] = 0; } else { configs.length++; } uint64 courtConfigId = uint64(configs.length - 1); Config storage config = configs[courtConfigId]; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _maxRegularAppealRounds, finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; configIdByTerm[_fromTermId] = courtConfigId; configChangeTermId = _fromTermId; emit NewConfig(_fromTermId, courtConfigId); } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal * @return minActiveBalance Minimum amount of guardian tokens that can be activated */ function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); FeesConfig storage feesConfig = config.fees; feeToken = feesConfig.token; fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee]; DisputesConfig storage disputesConfig = config.disputes; roundStateDurations = [ disputesConfig.evidenceTerms, disputesConfig.commitTerms, disputesConfig.revealTerms, disputesConfig.appealTerms, disputesConfig.appealConfirmTerms ]; pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction]; roundParams = [ disputesConfig.firstRoundGuardiansNumber, disputesConfig.appealStepFactor, uint64(disputesConfig.maxRegularAppealRounds), disputesConfig.finalRoundLockTerms ]; appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor]; minActiveBalance = config.minActiveBalance; } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Minimum amount of guardian tokens that can be activated at the given term */ function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { Config storage config = _getConfigFor(_termId, _lastEnsuredTermId); return config.minActiveBalance; } /** * @dev Internal function to get the Court config for a given term * @param _termId Identification number of the term querying the min active balance config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Court config for the given term */ function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) { uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId); return configs[id]; } /** * @dev Internal function to get the Court config ID for a given term * @param _termId Identification number of the term querying the Court config of * @param _lastEnsuredTermId Identification number of the last ensured term of the Court * @return Identification number of the config for the given terms */ function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) { // If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config if (_termId <= _lastEnsuredTermId) { return configIdByTerm[_termId]; } // If the given term is in the future but there is a config change scheduled before it, use the incoming config uint64 scheduledChangeTermId = configChangeTermId; if (scheduledChangeTermId <= _termId) { return configIdByTerm[scheduledChangeTermId]; } // If no changes are scheduled, use the Court config of the last ensured term return configIdByTerm[_lastEnsuredTermId]; } } /* * SPDX-License-Identifier: MIT */ interface IArbitrator { /** * @dev Create a dispute over the Arbitrable sender with a number of possible rulings * @param _possibleRulings Number of possible rulings allowed for the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _disputeId Id of the dispute in the Court * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence related to the dispute */ function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(uint256 _disputeId) external; /** * @notice Rule dispute #`_disputeId` if ready * @param _disputeId Identification number of the dispute to be ruled * @return subject Subject associated to the dispute * @return ruling Ruling number computed for the given dispute */ function rule(uint256 _disputeId) external returns (address subject, uint256 ruling); /** * @dev Tell the dispute fees information to create a dispute * @return recipient Address where the corresponding dispute fees must be transferred to * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees that must be allowed to the recipient */ function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount); /** * @dev Tell the payments recipient address * @return Address of the payments recipient module */ function getPaymentsRecipient() external view returns (address); } /* * SPDX-License-Identifier: MIT */ /** * @dev The Arbitrable instances actually don't require to follow any specific interface. * Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances. */ contract IArbitrable { /** * @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator * @param arbitrator IArbitrator instance ruling the dispute * @param disputeId Identification number of the dispute being ruled by the arbitrator * @param ruling Ruling given by the arbitrator */ event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling); } interface IDisputeManager { enum DisputeState { PreDraft, Adjudicating, Ruled } enum AdjudicationState { Invalid, Committing, Revealing, Appealing, ConfirmingAppeal, Ended } /** * @dev Create a dispute to be drafted in a future term * @param _subject Arbitrable instance creating the dispute * @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created * @return Dispute identification number */ function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256); /** * @dev Submit evidence for a dispute * @param _subject Arbitrable instance submitting the dispute * @param _disputeId Identification number of the dispute receiving new evidence * @param _submitter Address of the account submitting the evidence * @param _evidence Data submitted for the evidence of the dispute */ function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external; /** * @dev Close the evidence period of a dispute * @param _subject IArbitrable instance requesting to close the evidence submission period * @param _disputeId Identification number of the dispute to close its evidence submitting period */ function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external; /** * @dev Draft guardians for the next round of a dispute * @param _disputeId Identification number of the dispute to be drafted */ function draft(uint256 _disputeId) external; /** * @dev Appeal round of a dispute in favor of a certain ruling * @param _disputeId Identification number of the dispute being appealed * @param _roundId Identification number of the dispute round being appealed * @param _ruling Ruling appealing a dispute round in favor of */ function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Confirm appeal for a round of a dispute in favor of a ruling * @param _disputeId Identification number of the dispute confirming an appeal of * @param _roundId Identification number of the dispute round confirming an appeal of * @param _ruling Ruling being confirmed against a dispute round appeal */ function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external; /** * @dev Compute the final ruling for a dispute * @param _disputeId Identification number of the dispute to compute its final ruling * @return subject Arbitrable instance associated to the dispute * @return finalRuling Final ruling decided for the given dispute */ function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling); /** * @dev Settle penalties for a round of a dispute * @param _disputeId Identification number of the dispute to settle penalties for * @param _roundId Identification number of the dispute round to settle penalties for * @param _guardiansToSettle Maximum number of guardians to be slashed in this call */ function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external; /** * @dev Claim rewards for a round of a dispute for guardian * @dev For regular rounds, it will only reward winning guardians * @param _disputeId Identification number of the dispute to settle rewards for * @param _roundId Identification number of the dispute round to settle rewards for * @param _guardian Address of the guardian to settle their rewards */ function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external; /** * @dev Settle appeal deposits for a round of a dispute * @param _disputeId Identification number of the dispute to settle appeal deposits for * @param _roundId Identification number of the dispute round to settle appeal deposits for */ function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external; /** * @dev Tell the amount of token fees required to create a dispute * @return feeToken ERC20 token used for the fees * @return feeAmount Total amount of fees to be paid for a dispute at the given term */ function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount); /** * @dev Tell information of a certain dispute * @param _disputeId Identification number of the dispute being queried * @return subject Arbitrable subject being disputed * @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute * @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled * @return finalRuling The winning ruling in case the dispute is finished * @return lastRoundId Identification number of the last round created for the dispute * @return createTermId Identification number of the term when the dispute was created */ function getDispute(uint256 _disputeId) external view returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId); /** * @dev Tell information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return draftTerm Term from which the requested round can be drafted * @return delayedTerms Number of terms the given round was delayed based on its requested draft term id * @return guardiansNumber Number of guardians requested for the round * @return selectedGuardians Number of guardians already selected for the requested round * @return settledPenalties Whether or not penalties have been settled for the requested round * @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round * @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round * @return state Adjudication state of the requested round */ function getRound(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 draftTerm, uint64 delayedTerms, uint64 guardiansNumber, uint64 selectedGuardians, uint256 guardianFees, bool settledPenalties, uint256 collectedTokens, uint64 coherentGuardians, AdjudicationState state ); /** * @dev Tell appeal-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @return maker Address of the account appealing the given round * @return appealedRuling Ruling confirmed by the appealer of the given round * @return taker Address of the account confirming the appeal of the given round * @return opposedRuling Ruling confirmed by the appeal taker of the given round */ function getAppeal(uint256 _disputeId, uint256 _roundId) external view returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling); /** * @dev Tell information related to the next round due to an appeal of a certain round given. * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round requesting the appeal details of * @return nextRoundStartTerm Term ID from which the next round will start * @return nextRoundGuardiansNumber Guardians number for the next round * @return newDisputeState New state for the dispute associated to the given round after the appeal * @return feeToken ERC20 token used for the next round fees * @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round * @return totalFees Total amount of fees for a regular round at the given term * @return appealDeposit Amount to be deposit of fees for a regular round at the given term * @return confirmAppealDeposit Total amount of fees for a regular round at the given term */ function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view returns ( uint64 nextRoundStartTerm, uint64 nextRoundGuardiansNumber, DisputeState newDisputeState, IERC20 feeToken, uint256 totalFees, uint256 guardianFees, uint256 appealDeposit, uint256 confirmAppealDeposit ); /** * @dev Tell guardian-related information of a certain adjudication round * @param _disputeId Identification number of the dispute being queried * @param _roundId Identification number of the round being queried * @param _guardian Address of the guardian being queried * @return weight Guardian weight drafted for the requested round * @return rewarded Whether or not the given guardian was rewarded based on the requested round */ function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded); } contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL { string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR"; string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS"; string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET"; string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED"; string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED"; string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE"; string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET"; string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT"; string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH"; address private constant ZERO_ADDRESS = address(0); /** * @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules */ struct Governor { address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system } /** * @dev Module information */ struct Module { bytes32 id; // ID associated to a module bool disabled; // Whether the module is disabled } // Governor addresses of the system Governor private governor; // List of current modules registered for the system indexed by ID mapping (bytes32 => address) internal currentModules; // List of all historical modules registered for the system indexed by address mapping (address => Module) internal allModules; // List of custom function targets indexed by signature mapping (bytes4 => address) internal customFunctions; event ModuleSet(bytes32 id, address addr); event ModuleEnabled(bytes32 id, address addr); event ModuleDisabled(bytes32 id, address addr); event CustomFunctionSet(bytes4 signature, address target); event FundsGovernorChanged(address previousGovernor, address currentGovernor); event ConfigGovernorChanged(address previousGovernor, address currentGovernor); event ModulesGovernorChanged(address previousGovernor, address currentGovernor); /** * @dev Ensure the msg.sender is the funds governor */ modifier onlyFundsGovernor { require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyConfigGovernor { require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the modules governor */ modifier onlyModulesGovernor { require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR); _; } /** * @dev Ensure the given dispute manager is active */ modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) { require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE); _; } /** * @dev Constructor function * @param _termParams Array containing: * 0. _termDuration Duration in seconds per term * 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding) * @param _governors Array containing: * 0. _fundsGovernor Address of the funds governor * 1. _configGovernor Address of the config governor * 2. _modulesGovernor Address of the modules governor * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ constructor( uint64[2] memory _termParams, address[3] memory _governors, IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance ) public CourtClock(_termParams) CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance) { _setFundsGovernor(_governors[0]); _setConfigGovernor(_governors[1]); _setModulesGovernor(_governors[2]); } /** * @dev Fallback function allows to forward calls to a specific address in case it was previously registered * Note the sender will be always the controller in case it is forwarded */ function () external payable { address target = customFunctions[msg.sig]; require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET); // solium-disable-next-line security/no-call-value (bool success,) = address(target).call.value(msg.value)(msg.data); assembly { let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) let result := success switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @notice Change Court configuration params * @param _fromTermId Identification number of the term in which the config will be effective at * @param _feeToken Address of the token contract that is used to pay for fees * @param _fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @param _pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @param _roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @param _appealCollateralParams Array containing params for appeal collateral: * 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling * 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal * @param _minActiveBalance Minimum amount of guardian tokens that can be activated */ function setConfig( uint64 _fromTermId, IERC20 _feeToken, uint256[3] calldata _fees, uint64[5] calldata _roundStateDurations, uint16[2] calldata _pcts, uint64[4] calldata _roundParams, uint256[2] calldata _appealCollateralParams, uint256 _minActiveBalance ) external onlyConfigGovernor { uint64 currentTermId = _ensureCurrentTerm(); _setConfig( currentTermId, _fromTermId, _feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance ); } /** * @notice Delay the Court start time to `_newFirstTermStartTime` * @param _newFirstTermStartTime New timestamp in seconds when the court will open */ function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor { _delayStartTime(_newFirstTermStartTime); } /** * @notice Change funds governor address to `_newFundsGovernor` * @param _newFundsGovernor Address of the new funds governor to be set */ function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor { require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setFundsGovernor(_newFundsGovernor); } /** * @notice Change config governor address to `_newConfigGovernor` * @param _newConfigGovernor Address of the new config governor to be set */ function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor { require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setConfigGovernor(_newConfigGovernor); } /** * @notice Change modules governor address to `_newModulesGovernor` * @param _newModulesGovernor Address of the new governor to be set */ function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor { require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS); _setModulesGovernor(_newModulesGovernor); } /** * @notice Remove the funds governor. Set the funds governor to the zero address. * @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore */ function ejectFundsGovernor() external onlyFundsGovernor { _setFundsGovernor(ZERO_ADDRESS); } /** * @notice Remove the modules governor. Set the modules governor to the zero address. * @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore */ function ejectModulesGovernor() external onlyModulesGovernor { _setModulesGovernor(ZERO_ADDRESS); } /** * @notice Grant `_id` role to `_who` * @param _id ID of the role to be granted * @param _who Address to grant the role to */ function grant(bytes32 _id, address _who) external onlyConfigGovernor { _grant(_id, _who); } /** * @notice Revoke `_id` role from `_who` * @param _id ID of the role to be revoked * @param _who Address to revoke the role from */ function revoke(bytes32 _id, address _who) external onlyConfigGovernor { _revoke(_id, _who); } /** * @notice Freeze `_id` role * @param _id ID of the role to be frozen */ function freeze(bytes32 _id) external onlyConfigGovernor { _freeze(_id); } /** * @notice Enact a bulk list of ACL operations */ function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor { _bulk(_op, _id, _who); } /** * @notice Set module `_id` to `_addr` * @param _id ID of the module to be set * @param _addr Address of the module to be set */ function setModule(bytes32 _id, address _addr) external onlyModulesGovernor { _setModule(_id, _addr); } /** * @notice Set and link many modules at once * @param _newModuleIds List of IDs of the new modules to be set * @param _newModuleAddresses List of addresses of the new modules to be set * @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set * @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set */ function setModules( bytes32[] calldata _newModuleIds, address[] calldata _newModuleAddresses, bytes32[] calldata _newModuleLinks, address[] calldata _currentModulesToBeSynced ) external onlyModulesGovernor { // We only care about the modules being set, links are optional require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH); // First set the addresses of the new modules or the modules to be updated for (uint256 i = 0; i < _newModuleIds.length; i++) { _setModule(_newModuleIds[i], _newModuleAddresses[i]); } // Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies) _syncModuleLinks(_newModuleAddresses, _newModuleLinks); // Finally sync the links of the existing modules to be synced to the new modules being set _syncModuleLinks(_currentModulesToBeSynced, _newModuleIds); } /** * @notice Sync modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules included in the sync */ function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet) external onlyModulesGovernor { require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH); _syncModuleLinks(_modulesToBeSynced, _idsToBeSet); } /** * @notice Disable module `_addr` * @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule` * @param _addr Address of the module to be disabled */ function disableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED); module.disabled = true; emit ModuleDisabled(module.id, _addr); } /** * @notice Enable module `_addr` * @param _addr Address of the module to be enabled */ function enableModule(address _addr) external onlyModulesGovernor { Module storage module = allModules[_addr]; _ensureModuleExists(module); require(module.disabled, ERROR_MODULE_ALREADY_ENABLED); module.disabled = false; emit ModuleEnabled(module.id, _addr); } /** * @notice Set custom function `_sig` for `_target` * @param _sig Signature of the function to be set * @param _target Address of the target implementation to be registered for the given signature */ function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor { customFunctions[_sig] = _target; emit CustomFunctionSet(_sig, _target); } /** * @dev Tell the full Court configuration parameters at a certain term * @param _termId Identification number of the term querying the Court config of * @return token Address of the token used to pay for fees * @return fees Array containing: * 0. guardianFee Amount of fee tokens that is paid per guardian per dispute * 1. draftFee Amount of fee tokens per guardian to cover the drafting cost * 2. settleFee Amount of fee tokens per guardian to cover round settlement cost * @return roundStateDurations Array containing the durations in terms of the different phases of a dispute: * 0. evidenceTerms Max submitting evidence period duration in terms * 1. commitTerms Commit period duration in terms * 2. revealTerms Reveal period duration in terms * 3. appealTerms Appeal period duration in terms * 4. appealConfirmationTerms Appeal confirmation period duration in terms * @return pcts Array containing: * 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) * 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000) * @return roundParams Array containing params for rounds: * 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes * 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute * 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered * 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks) * @return appealCollateralParams Array containing params for appeal collateral: * 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling * 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal */ function getConfig(uint64 _termId) external view returns ( IERC20 feeToken, uint256[3] memory fees, uint64[5] memory roundStateDurations, uint16[2] memory pcts, uint64[4] memory roundParams, uint256[2] memory appealCollateralParams, uint256 minActiveBalance ) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getConfigAt(_termId, lastEnsuredTermId); } /** * @dev Tell the draft config at a certain term * @param _termId Identification number of the term querying the draft config of * @return feeToken Address of the token used to pay for fees * @return draftFee Amount of fee tokens per guardian to cover the drafting cost * @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000) */ function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getDraftConfig(_termId, lastEnsuredTermId); } /** * @dev Tell the min active balance config at a certain term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of tokens guardians have to activate to participate in the Court */ function getMinActiveBalance(uint64 _termId) external view returns (uint256) { uint64 lastEnsuredTermId = _lastEnsuredTermId(); return _getMinActiveBalance(_termId, lastEnsuredTermId); } /** * @dev Tell the address of the funds governor * @return Address of the funds governor */ function getFundsGovernor() external view returns (address) { return governor.funds; } /** * @dev Tell the address of the config governor * @return Address of the config governor */ function getConfigGovernor() external view returns (address) { return governor.config; } /** * @dev Tell the address of the modules governor * @return Address of the modules governor */ function getModulesGovernor() external view returns (address) { return governor.modules; } /** * @dev Tell if a given module is active * @param _id ID of the module to be checked * @param _addr Address of the module to be checked * @return True if the given module address has the requested ID and is enabled */ function isActive(bytes32 _id, address _addr) external view returns (bool) { Module storage module = allModules[_addr]; return module.id == _id && !module.disabled; } /** * @dev Tell the current ID and disable status of a module based on a given address * @param _addr Address of the requested module * @return id ID of the module being queried * @return disabled Whether the module has been disabled */ function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) { Module storage module = allModules[_addr]; id = module.id; disabled = module.disabled; } /** * @dev Tell the current address and disable status of a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function getModule(bytes32 _id) external view returns (address addr, bool disabled) { return _getModule(_id); } /** * @dev Tell the information for the current DisputeManager module * @return addr Current address of the DisputeManager module * @return disabled Whether the module has been disabled */ function getDisputeManager() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_DISPUTE_MANAGER); } /** * @dev Tell the information for the current GuardiansRegistry module * @return addr Current address of the GuardiansRegistry module * @return disabled Whether the module has been disabled */ function getGuardiansRegistry() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_GUARDIANS_REGISTRY); } /** * @dev Tell the information for the current Voting module * @return addr Current address of the Voting module * @return disabled Whether the module has been disabled */ function getVoting() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_VOTING); } /** * @dev Tell the information for the current PaymentsBook module * @return addr Current address of the PaymentsBook module * @return disabled Whether the module has been disabled */ function getPaymentsBook() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_PAYMENTS_BOOK); } /** * @dev Tell the information for the current Treasury module * @return addr Current address of the Treasury module * @return disabled Whether the module has been disabled */ function getTreasury() external view returns (address addr, bool disabled) { return _getModule(MODULE_ID_TREASURY); } /** * @dev Tell the target registered for a custom function * @param _sig Signature of the function being queried * @return Address of the target where the function call will be forwarded */ function getCustomFunction(bytes4 _sig) external view returns (address) { return customFunctions[_sig]; } /** * @dev Internal function to set the address of the funds governor * @param _newFundsGovernor Address of the new config governor to be set */ function _setFundsGovernor(address _newFundsGovernor) internal { emit FundsGovernorChanged(governor.funds, _newFundsGovernor); governor.funds = _newFundsGovernor; } /** * @dev Internal function to set the address of the config governor * @param _newConfigGovernor Address of the new config governor to be set */ function _setConfigGovernor(address _newConfigGovernor) internal { emit ConfigGovernorChanged(governor.config, _newConfigGovernor); governor.config = _newConfigGovernor; } /** * @dev Internal function to set the address of the modules governor * @param _newModulesGovernor Address of the new modules governor to be set */ function _setModulesGovernor(address _newModulesGovernor) internal { emit ModulesGovernorChanged(governor.modules, _newModulesGovernor); governor.modules = _newModulesGovernor; } /** * @dev Internal function to set an address as the current implementation for a module * Note that the disabled condition is not affected, if the module was not set before it will be enabled by default * @param _id Id of the module to be set * @param _addr Address of the module to be set */ function _setModule(bytes32 _id, address _addr) internal { require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT); currentModules[_id] = _addr; allModules[_addr].id = _id; emit ModuleSet(_id, _addr); } /** * @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address * @param _modulesToBeSynced List of addresses of connected modules to be synced * @param _idsToBeSet List of IDs of the modules to be linked */ function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal { address[] memory addressesToBeSet = new address[](_idsToBeSet.length); // Load the addresses associated with the requested module ids for (uint256 i = 0; i < _idsToBeSet.length; i++) { address moduleAddress = _getModuleAddress(_idsToBeSet[i]); Module storage module = allModules[moduleAddress]; _ensureModuleExists(module); addressesToBeSet[i] = moduleAddress; } // Update the links of all the requested modules for (uint256 j = 0; j < _modulesToBeSynced.length; j++) { IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet); } } /** * @dev Internal function to notify when a term has been transitioned * @param _termId Identification number of the new current term that has been transitioned */ function _onTermTransitioned(uint64 _termId) internal { _ensureTermConfig(_termId); } /** * @dev Internal function to check if a module was set * @param _module Module to be checked */ function _ensureModuleExists(Module storage _module) internal view { require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET); } /** * @dev Internal function to tell the information for a module based on a given ID * @param _id ID of the module being queried * @return addr Current address of the requested module * @return disabled Whether the module has been disabled */ function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) { addr = _getModuleAddress(_id); disabled = _isModuleDisabled(addr); } /** * @dev Tell the current address for a module by ID * @param _id ID of the module being queried * @return Current address of the requested module */ function _getModuleAddress(bytes32 _id) internal view returns (address) { return currentModules[_id]; } /** * @dev Tell whether a module is disabled * @param _addr Address of the module being queried * @return True if the module is disabled, false otherwise */ function _isModuleDisabled(address _addr) internal view returns (bool) { return allModules[_addr].disabled; } } contract ConfigConsumer is CourtConfigData { /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig); /** * @dev Internal function to get the Court config for a certain term * @param _termId Identification number of the term querying the Court config of * @return Court config for the given term */ function _getConfigAt(uint64 _termId) internal view returns (Config memory) { (IERC20 _feeToken, uint256[3] memory _fees, uint64[5] memory _roundStateDurations, uint16[2] memory _pcts, uint64[4] memory _roundParams, uint256[2] memory _appealCollateralParams, uint256 _minActiveBalance) = _courtConfig().getConfig(_termId); Config memory config; config.fees = FeesConfig({ token: _feeToken, guardianFee: _fees[0], draftFee: _fees[1], settleFee: _fees[2], finalRoundReduction: _pcts[1] }); config.disputes = DisputesConfig({ evidenceTerms: _roundStateDurations[0], commitTerms: _roundStateDurations[1], revealTerms: _roundStateDurations[2], appealTerms: _roundStateDurations[3], appealConfirmTerms: _roundStateDurations[4], penaltyPct: _pcts[0], firstRoundGuardiansNumber: _roundParams[0], appealStepFactor: _roundParams[1], maxRegularAppealRounds: _roundParams[2], finalRoundLockTerms: _roundParams[3], appealCollateralFactor: _appealCollateralParams[0], appealConfirmCollateralFactor: _appealCollateralParams[1] }); config.minActiveBalance = _minActiveBalance; return config; } /** * @dev Internal function to get the draft config for a given term * @param _termId Identification number of the term querying the draft config of * @return Draft config for the given term */ function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) { (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId); return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct }); } /** * @dev Internal function to get the min active balance config for a given term * @param _termId Identification number of the term querying the min active balance config of * @return Minimum amount of guardian tokens that can be activated */ function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) { return _courtConfig().getMinActiveBalance(_termId); } } /* * SPDX-License-Identifier: MIT */ interface ICRVotingOwner { /** * @dev Ensure votes can be committed for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for */ function ensureCanCommit(uint256 _voteId) external; /** * @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of */ function ensureCanCommit(uint256 _voteId, address _voter) external; /** * @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise * @param _voteId ID of the vote instance to request the weight of a voter for * @param _voter Address of the voter querying the weight of * @return Weight of the requested guardian for the requested vote instance */ function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64); } /* * SPDX-License-Identifier: MIT */ interface ICRVoting { /** * @dev Create a new vote instance * @dev This function can only be called by the CRVoting owner * @param _voteId ID of the new vote instance to be created * @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created */ function createVote(uint256 _voteId, uint8 _possibleOutcomes) external; /** * @dev Get the winning outcome of a vote instance * @param _voteId ID of the vote instance querying the winning outcome of * @return Winning outcome of the given vote instance or refused in case it's missing */ function getWinningOutcome(uint256 _voteId) external view returns (uint8); /** * @dev Get the tally of an outcome for a certain vote instance * @param _voteId ID of the vote instance querying the tally of * @param _outcome Outcome querying the tally of * @return Tally of the outcome being queried for the given vote instance */ function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256); /** * @dev Tell whether an outcome is valid for a given vote instance or not * @param _voteId ID of the vote instance to check the outcome of * @param _outcome Outcome to check if valid or not * @return True if the given outcome is valid for the requested vote instance, false otherwise */ function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool); /** * @dev Get the outcome voted by a voter for a certain vote instance * @param _voteId ID of the vote instance querying the outcome of * @param _voter Address of the voter querying the outcome of * @return Outcome of the voter for the given vote instance */ function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8); /** * @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome * @param _outcome Outcome to query if the given voter voted in favor of * @param _voter Address of the voter to query if voted in favor of the given outcome * @return True if the given voter voted in favor of the given outcome, false otherwise */ function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool); /** * @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not * @param _voteId ID of the vote instance to be checked * @param _outcome Outcome to filter the list of voters of * @param _voters List of addresses of the voters to be filtered * @return List of results to tell whether a voter voted in favor of the given outcome or not */ function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory); } /* * SPDX-License-Identifier: MIT */ interface ITreasury { /** * @dev Assign a certain amount of tokens to an account * @param _token ERC20 token to be assigned * @param _to Address of the recipient that will be assigned the tokens to * @param _amount Amount of tokens to be assigned to the recipient */ function assign(IERC20 _token, address _to, uint256 _amount) external; /** * @dev Withdraw a certain amount of tokens * @param _token ERC20 token to be withdrawn * @param _from Address withdrawing the tokens from * @param _to Address of the recipient that will receive the tokens * @param _amount Amount of tokens to be withdrawn from the sender */ function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external; } /* * SPDX-License-Identifier: MIT */ interface IPaymentsBook { /** * @dev Pay an amount of tokens * @param _token Address of the token being paid * @param _amount Amount of tokens being paid * @param _payer Address paying on behalf of * @param _data Optional data */ function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable; } contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer { string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET"; string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT"; string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT"; string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED"; string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER"; string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR"; string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING"; string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR"; string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR"; // Address of the controller Controller public controller; // List of modules linked indexed by ID mapping (bytes32 => address) public linkedModules; event ModuleLinked(bytes32 id, address addr); /** * @dev Ensure the msg.sender is the controller's config governor */ modifier onlyConfigGovernor { require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR); _; } /** * @dev Ensure the msg.sender is the controller */ modifier onlyController() { require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER); _; } /** * @dev Ensure the msg.sender is an active DisputeManager module */ modifier onlyActiveDisputeManager() { require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is the current DisputeManager module */ modifier onlyCurrentDisputeManager() { (address addr, bool disabled) = controller.getDisputeManager(); require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER); require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER); _; } /** * @dev Ensure the msg.sender is an active Voting module */ modifier onlyActiveVoting() { require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING); _; } /** * @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ modifier authenticateSender(address _user) { _authenticateSender(_user); _; } /** * @dev Constructor function * @param _controller Address of the controller */ constructor(Controller _controller) public { require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT); controller = _controller; } /** * @notice Update the implementation links of a list of modules * @dev The controller is expected to ensure the given addresses are correct modules * @param _ids List of IDs of the modules to be updated * @param _addresses List of module addresses to be updated */ function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController { require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT); for (uint256 i = 0; i < _ids.length; i++) { linkedModules[_ids[i]] = _addresses[i]; emit ModuleLinked(_ids[i], _addresses[i]); } } /** * @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not * @return Identification number of the current Court term */ function _ensureCurrentTerm() internal returns (uint64) { return _clock().ensureCurrentTerm(); } /** * @dev Internal function to fetch the last ensured term ID of the Court * @return Identification number of the last ensured term */ function _getLastEnsuredTermId() internal view returns (uint64) { return _clock().getLastEnsuredTermId(); } /** * @dev Internal function to tell the current term identification number * @return Identification number of the current term */ function _getCurrentTermId() internal view returns (uint64) { return _clock().getCurrentTermId(); } /** * @dev Internal function to fetch the controller's config governor * @return Address of the controller's config governor */ function _configGovernor() internal view returns (address) { return controller.getConfigGovernor(); } /** * @dev Internal function to fetch the address of the DisputeManager module * @return Address of the DisputeManager module */ function _disputeManager() internal view returns (IDisputeManager) { return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER)); } /** * @dev Internal function to fetch the address of the GuardianRegistry module implementation * @return Address of the GuardianRegistry module implementation */ function _guardiansRegistry() internal view returns (IGuardiansRegistry) { return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY)); } /** * @dev Internal function to fetch the address of the Voting module implementation * @return Address of the Voting module implementation */ function _voting() internal view returns (ICRVoting) { return ICRVoting(_getLinkedModule(MODULE_ID_VOTING)); } /** * @dev Internal function to fetch the address of the PaymentsBook module implementation * @return Address of the PaymentsBook module implementation */ function _paymentsBook() internal view returns (IPaymentsBook) { return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK)); } /** * @dev Internal function to fetch the address of the Treasury module implementation * @return Address of the Treasury module implementation */ function _treasury() internal view returns (ITreasury) { return ITreasury(_getLinkedModule(MODULE_ID_TREASURY)); } /** * @dev Internal function to tell the address linked for a module based on a given ID * @param _id ID of the module being queried * @return Linked address of the requested module */ function _getLinkedModule(bytes32 _id) internal view returns (address) { address module = linkedModules[_id]; require(module != address(0), ERROR_MODULE_NOT_SET); return module; } /** * @dev Internal function to fetch the address of the Clock module from the controller * @return Address of the Clock module */ function _clock() internal view returns (IClock) { return IClock(controller); } /** * @dev Internal function to fetch the address of the Config module from the controller * @return Address of the Config module */ function _courtConfig() internal view returns (IConfig) { return IConfig(controller); } /** * @dev Ensure that the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of */ function _authenticateSender(address _user) internal view { require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED); } /** * @dev Tell whether the sender is the user to act on behalf of or someone with the required permission * @param _user Address of the user to act on behalf of * @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise */ function _isSenderAllowed(address _user) internal view returns (bool) { return msg.sender == _user || _hasRole(msg.sender); } /** * @dev Tell whether an address holds the required permission to access the requested functionality * @param _addr Address being checked * @return True if the given address has the required permission to access the requested functionality, false otherwise */ function _hasRole(address _addr) internal view returns (bool) { bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig)); return controller.hasRole(_addr, roleId); } } contract ControlledRecoverable is Controlled { using SafeERC20 for IERC20; string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR"; string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS"; string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED"; event RecoverFunds(address token, address recipient, uint256 balance); /** * @dev Ensure the msg.sender is the controller's funds governor */ modifier onlyFundsGovernor { require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR); _; } /** * @notice Transfer all `_token` tokens to `_to` * @param _token Address of the token to be recovered * @param _to Address of the recipient that will be receive all the funds of the requested token */ function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor { uint256 balance; if (_token == address(0)) { balance = address(this).balance; require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } else { balance = IERC20(_token).balanceOf(address(this)); require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS); // No need to verify _token to be a contract as we have already checked the balance require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED); } emit RecoverFunds(_token, _to, balance); } } contract GuardiansRegistry is IGuardiansRegistry, ControlledRecoverable { using SafeERC20 for IERC20; using SafeMath for uint256; using PctHelpers for uint256; using HexSumTree for HexSumTree.Tree; using GuardiansTreeSortition for HexSumTree.Tree; string private constant ERROR_NOT_CONTRACT = "GR_NOT_CONTRACT"; string private constant ERROR_INVALID_ZERO_AMOUNT = "GR_INVALID_ZERO_AMOUNT"; string private constant ERROR_INVALID_ACTIVATION_AMOUNT = "GR_INVALID_ACTIVATION_AMOUNT"; string private constant ERROR_INVALID_DEACTIVATION_AMOUNT = "GR_INVALID_DEACTIVATION_AMOUNT"; string private constant ERROR_INVALID_LOCKED_AMOUNTS_LENGTH = "GR_INVALID_LOCKED_AMOUNTS_LEN"; string private constant ERROR_INVALID_REWARDED_GUARDIANS_LENGTH = "GR_INVALID_REWARD_GUARDIANS_LEN"; string private constant ERROR_ACTIVE_BALANCE_BELOW_MIN = "GR_ACTIVE_BALANCE_BELOW_MIN"; string private constant ERROR_NOT_ENOUGH_AVAILABLE_BALANCE = "GR_NOT_ENOUGH_AVAILABLE_BALANCE"; string private constant ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST = "GR_CANT_REDUCE_DEACTIVATION_REQ"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "GR_TOKEN_TRANSFER_FAILED"; string private constant ERROR_TOKEN_APPROVE_NOT_ALLOWED = "GR_TOKEN_APPROVE_NOT_ALLOWED"; string private constant ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT = "GR_BAD_TOTAL_ACTIVE_BAL_LIMIT"; string private constant ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED = "GR_TOTAL_ACTIVE_BALANCE_EXCEEDED"; string private constant ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK = "GR_DEACTIV_AMOUNT_EXCEEDS_LOCK"; string private constant ERROR_CANNOT_UNLOCK_ACTIVATION = "GR_CANNOT_UNLOCK_ACTIVATION"; string private constant ERROR_ZERO_LOCK_ACTIVATION = "GR_ZERO_LOCK_ACTIVATION"; string private constant ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT = "GR_INVALID_UNLOCK_ACTIVAT_AMOUNT"; string private constant ERROR_LOCK_MANAGER_NOT_ALLOWED = "GR_LOCK_MANAGER_NOT_ALLOWED"; string private constant ERROR_WITHDRAWALS_LOCK = "GR_WITHDRAWALS_LOCK"; // Address that will be used to burn guardian tokens address internal constant BURN_ACCOUNT = address(0x000000000000000000000000000000000000dEaD); // Maximum number of sortition iterations allowed per draft call uint256 internal constant MAX_DRAFT_ITERATIONS = 10; // "ERC20-lite" interface to provide help for tooling string public constant name = "Court Staked Aragon Network Token"; string public constant symbol = "sANT"; uint8 public constant decimals = 18; /** * @dev Guardians have three kind of balances, these are: * - active: tokens activated for the Court that can be locked in case the guardian is drafted * - locked: amount of active tokens that are locked for a draft * - available: tokens that are not activated for the Court and can be withdrawn by the guardian at any time * * Due to a gas optimization for drafting, the "active" tokens are stored in a `HexSumTree`, while the others * are stored in this contract as `lockedBalance` and `availableBalance` respectively. Given that the guardians' * active balances cannot be affected during the current Court term, if guardians want to deactivate some of * their active tokens, their balance will be updated for the following term, and they won't be allowed to * withdraw them until the current term has ended. * * Note that even though guardians balances are stored separately, all the balances are held by this contract. */ struct Guardian { uint256 id; // Key in the guardians tree used for drafting uint256 lockedBalance; // Maximum amount of tokens that can be slashed based on the guardian's drafts uint256 availableBalance; // Available tokens that can be withdrawn at any time uint64 withdrawalsLockTermId; // Term ID until which the guardian's withdrawals will be locked ActivationLocks activationLocks; // Guardian's activation locks DeactivationRequest deactivationRequest; // Guardian's pending deactivation request } /** * @dev Guardians can define lock managers to control their minimum active balance in the registry */ struct ActivationLocks { uint256 total; // Total amount of active balance locked mapping (address => uint256) lockedBy; // List of locked amounts indexed by lock manager } /** * @dev Given that the guardians balances cannot be affected during a Court term, if guardians want to deactivate some * of their tokens, the tree will always be updated for the following term, and they won't be able to * withdraw the requested amount until the current term has finished. Thus, we need to keep track the term * when a token deactivation was requested and its corresponding amount. */ struct DeactivationRequest { uint256 amount; // Amount requested for deactivation uint64 availableTermId; // Term ID when guardians can withdraw their requested deactivation tokens } /** * @dev Internal struct to wrap all the params required to perform guardians drafting */ struct DraftParams { bytes32 termRandomness; // Randomness seed to be used for the draft uint256 disputeId; // ID of the dispute being drafted uint64 termId; // Term ID of the dispute's draft term uint256 selectedGuardians; // Number of guardians already selected for the draft uint256 batchRequestedGuardians; // Number of guardians to be selected in the given batch of the draft uint256 roundRequestedGuardians; // Total number of guardians requested to be drafted uint256 draftLockAmount; // Amount of tokens to be locked to each drafted guardian uint256 iteration; // Sortition iteration number } // Maximum amount of total active balance that can be held in the registry uint256 public totalActiveBalanceLimit; // Guardian ERC20 token IERC20 public guardiansToken; // Mapping of guardian data indexed by address mapping (address => Guardian) internal guardiansByAddress; // Mapping of guardian addresses indexed by id mapping (uint256 => address) internal guardiansAddressById; // Tree to store guardians active balance by term for the drafting process HexSumTree.Tree internal tree; event Staked(address indexed guardian, uint256 amount, uint256 total); event Unstaked(address indexed guardian, uint256 amount, uint256 total); event GuardianActivated(address indexed guardian, uint64 fromTermId, uint256 amount); event GuardianDeactivationRequested(address indexed guardian, uint64 availableTermId, uint256 amount); event GuardianDeactivationProcessed(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 processedTermId); event GuardianDeactivationUpdated(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 updateTermId); event GuardianActivationLockChanged(address indexed guardian, address indexed lockManager, uint256 amount, uint256 total); event GuardianBalanceLocked(address indexed guardian, uint256 amount); event GuardianBalanceUnlocked(address indexed guardian, uint256 amount); event GuardianSlashed(address indexed guardian, uint256 amount, uint64 effectiveTermId); event GuardianTokensAssigned(address indexed guardian, uint256 amount); event GuardianTokensBurned(uint256 amount); event GuardianTokensCollected(address indexed guardian, uint256 amount, uint64 effectiveTermId); event TotalActiveBalanceLimitChanged(uint256 previousTotalActiveBalanceLimit, uint256 currentTotalActiveBalanceLimit); /** * @dev Constructor function * @param _controller Address of the controller * @param _guardiansToken Address of the ERC20 token to be used as guardian token for the registry * @param _totalActiveBalanceLimit Maximum amount of total active balance that can be held in the registry */ constructor(Controller _controller, IERC20 _guardiansToken, uint256 _totalActiveBalanceLimit) Controlled(_controller) public { require(isContract(address(_guardiansToken)), ERROR_NOT_CONTRACT); guardiansToken = _guardiansToken; _setTotalActiveBalanceLimit(_totalActiveBalanceLimit); tree.init(); // First tree item is an empty guardian assert(tree.insert(0, 0) == 0); } /** * @notice Stake `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian to stake tokens to * @param _amount Amount of tokens to be staked */ function stake(address _guardian, uint256 _amount) external { _stake(_guardian, _amount); } /** * @notice Unstake `@tokenAmount(self.token(), _amount)` from `_guardian` * @param _guardian Address of the guardian to unstake tokens from * @param _amount Amount of tokens to be unstaked */ function unstake(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _unstake(_guardian, _amount); } /** * @notice Activate `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian activating the tokens for * @param _amount Amount of guardian tokens to be activated for the next term */ function activate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _activate(_guardian, _amount); } /** * @notice Deactivate `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian deactivating the tokens for * @param _amount Amount of guardian tokens to be deactivated for the next term */ function deactivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _deactivate(_guardian, _amount); } /** * @notice Stake and activate `@tokenAmount(self.token(), _amount)` for `_guardian` * @param _guardian Address of the guardian staking and activating tokens for * @param _amount Amount of tokens to be staked and activated */ function stakeAndActivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) { _stake(_guardian, _amount); _activate(_guardian, _amount); } /** * @notice Lock `@tokenAmount(self.token(), _amount)` of `_guardian`'s active balance * @param _guardian Address of the guardian locking the activation for * @param _lockManager Address of the lock manager that will control the lock * @param _amount Amount of active tokens to be locked */ function lockActivation(address _guardian, address _lockManager, uint256 _amount) external { // Make sure the sender is the guardian, someone allowed by the guardian, or the lock manager itself bool isLockManagerAllowed = msg.sender == _lockManager || _isSenderAllowed(_guardian); // Make sure that the given lock manager is allowed require(isLockManagerAllowed && _hasRole(_lockManager), ERROR_LOCK_MANAGER_NOT_ALLOWED); _lockActivation(_guardian, _lockManager, _amount); } /** * @notice Unlock `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` of `_guardian`'s active balance * @param _guardian Address of the guardian unlocking the active balance of * @param _lockManager Address of the lock manager controlling the lock * @param _amount Amount of active tokens to be unlocked * @param _requestDeactivation Whether the unlocked amount must be requested for deactivation immediately */ function unlockActivation(address _guardian, address _lockManager, uint256 _amount, bool _requestDeactivation) external { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; uint256 lockedAmount = activationLocks.lockedBy[_lockManager]; require(lockedAmount > 0, ERROR_ZERO_LOCK_ACTIVATION); uint256 amountToUnlock = _amount == 0 ? lockedAmount : _amount; require(amountToUnlock <= lockedAmount, ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT); // Always allow the lock manager to unlock bool canUnlock = _lockManager == msg.sender || ILockManager(_lockManager).canUnlock(_guardian, amountToUnlock); require(canUnlock, ERROR_CANNOT_UNLOCK_ACTIVATION); uint256 newLockedAmount = lockedAmount.sub(amountToUnlock); uint256 newTotalLocked = activationLocks.total.sub(amountToUnlock); activationLocks.total = newTotalLocked; activationLocks.lockedBy[_lockManager] = newLockedAmount; emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked); // In order to request a deactivation, the request must have been originally authorized from the guardian or someone authorized to do it if (_requestDeactivation) { _authenticateSender(_guardian); _deactivate(_guardian, _amount); } } /** * @notice Process a token deactivation requested for `_guardian` if there is any * @param _guardian Address of the guardian to process the deactivation request of */ function processDeactivationRequest(address _guardian) external { uint64 termId = _ensureCurrentTerm(); _processDeactivationRequest(_guardian, termId); } /** * @notice Assign `@tokenAmount(self.token(), _amount)` to the available balance of `_guardian` * @param _guardian Guardian to add an amount of tokens to * @param _amount Amount of tokens to be added to the available balance of a guardian */ function assignTokens(address _guardian, uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(_guardian, _amount, true); emit GuardianTokensAssigned(_guardian, _amount); } } /** * @notice Burn `@tokenAmount(self.token(), _amount)` * @param _amount Amount of tokens to be burned */ function burnTokens(uint256 _amount) external onlyActiveDisputeManager { if (_amount > 0) { _updateAvailableBalanceOf(BURN_ACCOUNT, _amount, true); emit GuardianTokensBurned(_amount); } } /** * @notice Draft a set of guardians based on given requirements for a term id * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return guardians List of guardians selected for the draft * @return length Size of the list of the draft result */ function draft(uint256[7] calldata _params) external onlyActiveDisputeManager returns (address[] memory guardians, uint256 length) { DraftParams memory draftParams = _buildDraftParams(_params); guardians = new address[](draftParams.batchRequestedGuardians); // Guardians returned by the tree multi-sortition may not have enough unlocked active balance to be drafted. Thus, // we compute several sortitions until all the requested guardians are selected. To guarantee a different set of // guardians on each sortition, the iteration number will be part of the random seed to be used in the sortition. // Note that we are capping the number of iterations to avoid an OOG error, which means that this function could // return less guardians than the requested number. for (draftParams.iteration = 0; length < draftParams.batchRequestedGuardians && draftParams.iteration < MAX_DRAFT_ITERATIONS; draftParams.iteration++ ) { (uint256[] memory guardianIds, uint256[] memory activeBalances) = _treeSearch(draftParams); for (uint256 i = 0; i < guardianIds.length && length < draftParams.batchRequestedGuardians; i++) { // We assume the selected guardians are registered in the registry, we are not checking their addresses exist address guardianAddress = guardiansAddressById[guardianIds[i]]; Guardian storage guardian = guardiansByAddress[guardianAddress]; // Compute new locked balance for a guardian based on the penalty applied when being drafted uint256 newLockedBalance = guardian.lockedBalance.add(draftParams.draftLockAmount); // Check if there is any deactivation requests for the next term. Drafts are always computed for the current term // but we have to make sure we are locking an amount that will exist in the next term. uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, draftParams.termId + 1); // Check if guardian has enough active tokens to lock the requested amount for the draft, skip it otherwise. uint256 currentActiveBalance = activeBalances[i]; if (currentActiveBalance >= newLockedBalance) { // Check if the amount of active tokens for the next term is enough to lock the required amount for // the draft. Otherwise, reduce the requested deactivation amount of the next term. // Next term deactivation amount should always be less than current active balance, but we make sure using SafeMath uint256 nextTermActiveBalance = currentActiveBalance.sub(nextTermDeactivationRequestAmount); if (nextTermActiveBalance < newLockedBalance) { // No need for SafeMath: we already checked values above _reduceDeactivationRequest(guardianAddress, newLockedBalance - nextTermActiveBalance, draftParams.termId); } // Update the current active locked balance of the guardian guardian.lockedBalance = newLockedBalance; guardians[length++] = guardianAddress; emit GuardianBalanceLocked(guardianAddress, draftParams.draftLockAmount); } } } } /** * @notice Slash a set of guardians based on their votes compared to the winning ruling. This function will unlock the * corresponding locked balances of those guardians that are set to be slashed. * @param _termId Current term id * @param _guardians List of guardian addresses to be slashed * @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned * @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not * @return Total amount of slashed tokens */ function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians) external onlyActiveDisputeManager returns (uint256) { require(_guardians.length == _lockedAmounts.length, ERROR_INVALID_LOCKED_AMOUNTS_LENGTH); require(_guardians.length == _rewardedGuardians.length, ERROR_INVALID_REWARDED_GUARDIANS_LENGTH); uint64 nextTermId = _termId + 1; uint256 collectedTokens; for (uint256 i = 0; i < _guardians.length; i++) { uint256 lockedAmount = _lockedAmounts[i]; address guardianAddress = _guardians[i]; Guardian storage guardian = guardiansByAddress[guardianAddress]; guardian.lockedBalance = guardian.lockedBalance.sub(lockedAmount); // Slash guardian if requested. Note that there's no need to check if there was a deactivation // request since we're working with already locked balances. if (_rewardedGuardians[i]) { emit GuardianBalanceUnlocked(guardianAddress, lockedAmount); } else { collectedTokens = collectedTokens.add(lockedAmount); tree.update(guardian.id, nextTermId, lockedAmount, false); emit GuardianSlashed(guardianAddress, lockedAmount, nextTermId); } } return collectedTokens; } /** * @notice Try to collect `@tokenAmount(self.token(), _amount)` from `_guardian` for the term #`_termId + 1`. * @dev This function tries to decrease the active balance of a guardian for the next term based on the requested * amount. It can be seen as a way to early-slash a guardian's active balance. * @param _guardian Guardian to collect the tokens from * @param _amount Amount of tokens to be collected from the given guardian and for the requested term id * @param _termId Current term id * @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise */ function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external onlyActiveDisputeManager returns (bool) { if (_amount == 0) { return true; } uint64 nextTermId = _termId + 1; Guardian storage guardian = guardiansByAddress[_guardian]; uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian); uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, nextTermId); // Check if the guardian has enough unlocked tokens to collect the requested amount // Note that we're also considering the deactivation request if there is any uint256 totalUnlockedActiveBalance = unlockedActiveBalance.add(nextTermDeactivationRequestAmount); if (_amount > totalUnlockedActiveBalance) { return false; } // Check if the amount of active tokens is enough to collect the requested amount, otherwise reduce the requested deactivation amount of // the next term. Note that this behaviour is different to the one when drafting guardians since this function is called as a side effect // of a guardian deliberately voting in a final round, while drafts occur randomly. if (_amount > unlockedActiveBalance) { // No need for SafeMath: amounts were already checked above uint256 amountToReduce = _amount - unlockedActiveBalance; _reduceDeactivationRequest(_guardian, amountToReduce, _termId); } tree.update(guardian.id, nextTermId, _amount, false); emit GuardianTokensCollected(_guardian, _amount, nextTermId); return true; } /** * @notice Lock `_guardian`'s withdrawals until term #`_termId` * @dev This is intended for guardians who voted in a final round and were coherent with the final ruling to prevent 51% attacks * @param _guardian Address of the guardian to be locked * @param _termId Term ID until which the guardian's withdrawals will be locked */ function lockWithdrawals(address _guardian, uint64 _termId) external onlyActiveDisputeManager { Guardian storage guardian = guardiansByAddress[_guardian]; guardian.withdrawalsLockTermId = _termId; } /** * @notice Set new limit of total active balance of guardian tokens * @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens */ function setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) external onlyConfigGovernor { _setTotalActiveBalanceLimit(_totalActiveBalanceLimit); } /** * @dev Tell the total supply of guardian tokens staked * @return Supply of guardian tokens staked */ function totalSupply() external view returns (uint256) { return guardiansToken.balanceOf(address(this)); } /** * @dev Tell the total amount of active guardian tokens * @return Total amount of active guardian tokens */ function totalActiveBalance() external view returns (uint256) { return tree.getTotal(); } /** * @dev Tell the total amount of active guardian tokens for a given term id * @param _termId Term ID to query on * @return Total amount of active guardian tokens at the given term id */ function totalActiveBalanceAt(uint64 _termId) external view returns (uint256) { return _totalActiveBalanceAt(_termId); } /** * @dev Tell the total balance of tokens held by a guardian * This includes the active balance, the available balances, and the pending balance for deactivation. * Note that we don't have to include the locked balances since these represent the amount of active tokens * that are locked for drafts, i.e. these are already included in the active balance of the guardian. * @param _guardian Address of the guardian querying the balance of * @return Total amount of tokens of a guardian */ function balanceOf(address _guardian) external view returns (uint256) { return _balanceOf(_guardian); } /** * @dev Tell the detailed balance information of a guardian * @param _guardian Address of the guardian querying the detailed balance information of * @return active Amount of active tokens of a guardian * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function detailedBalanceOf(address _guardian) external view returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation) { return _detailedBalanceOf(_guardian); } /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID to query on * @return Amount of active tokens for guardian in the requested past term id */ function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256) { return _activeBalanceOfAt(_guardian, _termId); } /** * @dev Tell the amount of active tokens of a guardian at the last ensured term that are not locked due to ongoing disputes * @param _guardian Address of the guardian querying the unlocked balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function unlockedActiveBalanceOf(address _guardian) external view returns (uint256) { Guardian storage guardian = guardiansByAddress[_guardian]; return _currentUnlockedActiveBalanceOf(guardian); } /** * @dev Tell the pending deactivation details for a guardian * @param _guardian Address of the guardian whose info is requested * @return amount Amount to be deactivated * @return availableTermId Term in which the deactivated amount will be available */ function getDeactivationRequest(address _guardian) external view returns (uint256 amount, uint64 availableTermId) { DeactivationRequest storage request = guardiansByAddress[_guardian].deactivationRequest; return (request.amount, request.availableTermId); } /** * @dev Tell the activation amount locked for a guardian by a lock manager * @param _guardian Address of the guardian whose info is requested * @param _lockManager Address of the lock manager querying the lock of * @return amount Activation amount locked by the lock manager * @return total Total activation amount locked for the guardian */ function getActivationLock(address _guardian, address _lockManager) external view returns (uint256 amount, uint256 total) { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; total = activationLocks.total; amount = activationLocks.lockedBy[_lockManager]; } /** * @dev Tell the withdrawals lock term ID for a guardian * @param _guardian Address of the guardian whose info is requested * @return Term ID until which the guardian's withdrawals will be locked */ function getWithdrawalsLockTermId(address _guardian) external view returns (uint64) { return guardiansByAddress[_guardian].withdrawalsLockTermId; } /** * @dev Tell the identification number associated to a guardian address * @param _guardian Address of the guardian querying the identification number of * @return Identification number associated to a guardian address, zero in case it wasn't registered yet */ function getGuardianId(address _guardian) external view returns (uint256) { return guardiansByAddress[_guardian].id; } /** * @dev Internal function to activate a given amount of tokens for a guardian. * This function assumes that the given term is the current term and has already been ensured. * @param _guardian Address of the guardian to activate tokens * @param _amount Amount of guardian tokens to be activated */ function _activate(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); // Try to clean a previous deactivation request if any _processDeactivationRequest(_guardian, termId); uint256 availableBalance = guardiansByAddress[_guardian].availableBalance; uint256 amountToActivate = _amount == 0 ? availableBalance : _amount; require(amountToActivate > 0, ERROR_INVALID_ZERO_AMOUNT); require(amountToActivate <= availableBalance, ERROR_INVALID_ACTIVATION_AMOUNT); uint64 nextTermId = termId + 1; _checkTotalActiveBalance(nextTermId, amountToActivate); Guardian storage guardian = guardiansByAddress[_guardian]; uint256 minActiveBalance = _getMinActiveBalance(nextTermId); if (_existsGuardian(guardian)) { // Even though we are adding amounts, let's check the new active balance is greater than or equal to the // minimum active amount. Note that the guardian might have been slashed. uint256 activeBalance = tree.getItem(guardian.id); require(activeBalance.add(amountToActivate) >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN); tree.update(guardian.id, nextTermId, amountToActivate, true); } else { require(amountToActivate >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN); guardian.id = tree.insert(nextTermId, amountToActivate); guardiansAddressById[guardian.id] = _guardian; } _updateAvailableBalanceOf(_guardian, amountToActivate, false); emit GuardianActivated(_guardian, nextTermId, amountToActivate); } /** * @dev Internal function to deactivate a given amount of tokens for a guardian. * @param _guardian Address of the guardian to deactivate tokens * @param _amount Amount of guardian tokens to be deactivated for the next term */ function _deactivate(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); Guardian storage guardian = guardiansByAddress[_guardian]; uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian); uint256 amountToDeactivate = _amount == 0 ? unlockedActiveBalance : _amount; require(amountToDeactivate > 0, ERROR_INVALID_ZERO_AMOUNT); require(amountToDeactivate <= unlockedActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT); // Check future balance is not below the total activation lock of the guardian // No need for SafeMath: we already checked values above uint256 futureActiveBalance = unlockedActiveBalance - amountToDeactivate; uint256 totalActivationLock = guardian.activationLocks.total; require(futureActiveBalance >= totalActivationLock, ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK); // Check that the guardian is leaving or that the minimum active balance is met uint256 minActiveBalance = _getMinActiveBalance(termId); require(futureActiveBalance == 0 || futureActiveBalance >= minActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT); _createDeactivationRequest(_guardian, amountToDeactivate); } /** * @dev Internal function to create a token deactivation request for a guardian. Guardians will be allowed * to process a deactivation request from the next term. * @param _guardian Address of the guardian to create a token deactivation request for * @param _amount Amount of guardian tokens requested for deactivation */ function _createDeactivationRequest(address _guardian, uint256 _amount) internal { uint64 termId = _ensureCurrentTerm(); // Try to clean a previous deactivation request if possible _processDeactivationRequest(_guardian, termId); uint64 nextTermId = termId + 1; Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; request.amount = request.amount.add(_amount); request.availableTermId = nextTermId; tree.update(guardian.id, nextTermId, _amount, false); emit GuardianDeactivationRequested(_guardian, nextTermId, _amount); } /** * @dev Internal function to process a token deactivation requested by a guardian. It will move the requested amount * to the available balance of the guardian if the term when the deactivation was requested has already finished. * @param _guardian Address of the guardian to process the deactivation request of * @param _termId Current term id */ function _processDeactivationRequest(address _guardian, uint64 _termId) internal { Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; uint64 deactivationAvailableTermId = request.availableTermId; // If there is a deactivation request, ensure that the deactivation term has been reached if (deactivationAvailableTermId == uint64(0) || _termId < deactivationAvailableTermId) { return; } uint256 deactivationAmount = request.amount; // Note that we can use a zeroed term ID to denote void here since we are storing // the minimum allowed term to deactivate tokens which will always be at least 1. request.availableTermId = uint64(0); request.amount = 0; _updateAvailableBalanceOf(_guardian, deactivationAmount, true); emit GuardianDeactivationProcessed(_guardian, deactivationAvailableTermId, deactivationAmount, _termId); } /** * @dev Internal function to reduce a token deactivation requested by a guardian. It assumes the deactivation request * cannot be processed for the given term yet. * @param _guardian Address of the guardian to reduce the deactivation request of * @param _amount Amount to be reduced from the current deactivation request * @param _termId Term ID in which the deactivation request is being reduced */ function _reduceDeactivationRequest(address _guardian, uint256 _amount, uint64 _termId) internal { Guardian storage guardian = guardiansByAddress[_guardian]; DeactivationRequest storage request = guardian.deactivationRequest; uint256 currentRequestAmount = request.amount; require(currentRequestAmount >= _amount, ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST); // No need for SafeMath: we already checked values above uint256 newRequestAmount = currentRequestAmount - _amount; request.amount = newRequestAmount; // Move amount back to the tree tree.update(guardian.id, _termId + 1, _amount, true); emit GuardianDeactivationUpdated(_guardian, request.availableTermId, newRequestAmount, _termId); } /** * @dev Internal function to update the activation locked amount of a guardian * @param _guardian Guardian to update the activation locked amount of * @param _lockManager Address of the lock manager controlling the lock * @param _amount Amount of tokens to be added to the activation locked amount of the guardian */ function _lockActivation(address _guardian, address _lockManager, uint256 _amount) internal { ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks; uint256 newTotalLocked = activationLocks.total.add(_amount); uint256 newLockedAmount = activationLocks.lockedBy[_lockManager].add(_amount); activationLocks.total = newTotalLocked; activationLocks.lockedBy[_lockManager] = newLockedAmount; emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked); } /** * @dev Internal function to stake an amount of tokens for a guardian * @param _guardian Address of the guardian to deposit the tokens to * @param _amount Amount of tokens to be deposited */ function _stake(address _guardian, uint256 _amount) internal { require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT); _updateAvailableBalanceOf(_guardian, _amount, true); emit Staked(_guardian, _amount, _balanceOf(_guardian)); require(guardiansToken.safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FAILED); } /** * @dev Internal function to unstake an amount of tokens of a guardian * @param _guardian Address of the guardian to to unstake the tokens of * @param _amount Amount of tokens to be unstaked */ function _unstake(address _guardian, uint256 _amount) internal { require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT); // Try to process a deactivation request for the current term if there is one. Note that we don't need to ensure // the current term this time since deactivation requests always work with future terms, which means that if // the current term is outdated, it will never match the deactivation term id. We avoid ensuring the term here // to avoid forcing guardians to do that in order to withdraw their available balance. Same applies to final round locks. uint64 lastEnsuredTermId = _getLastEnsuredTermId(); // Check that guardian's withdrawals are not locked uint64 withdrawalsLockTermId = guardiansByAddress[_guardian].withdrawalsLockTermId; require(withdrawalsLockTermId == 0 || withdrawalsLockTermId < lastEnsuredTermId, ERROR_WITHDRAWALS_LOCK); _processDeactivationRequest(_guardian, lastEnsuredTermId); _updateAvailableBalanceOf(_guardian, _amount, false); emit Unstaked(_guardian, _amount, _balanceOf(_guardian)); require(guardiansToken.safeTransfer(_guardian, _amount), ERROR_TOKEN_TRANSFER_FAILED); } /** * @dev Internal function to update the available balance of a guardian * @param _guardian Guardian to update the available balance of * @param _amount Amount of tokens to be added to or removed from the available balance of a guardian * @param _positive True if the given amount should be added, or false to remove it from the available balance */ function _updateAvailableBalanceOf(address _guardian, uint256 _amount, bool _positive) internal { // We are not using a require here to avoid reverting in case any of the treasury maths reaches this point // with a zeroed amount value. Instead, we are doing this validation in the external entry points such as // stake, unstake, activate, deactivate, among others. if (_amount == 0) { return; } Guardian storage guardian = guardiansByAddress[_guardian]; if (_positive) { guardian.availableBalance = guardian.availableBalance.add(_amount); } else { require(_amount <= guardian.availableBalance, ERROR_NOT_ENOUGH_AVAILABLE_BALANCE); // No need for SafeMath: we already checked values right above guardian.availableBalance -= _amount; } } /** * @dev Internal function to set new limit of total active balance of guardian tokens * @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens */ function _setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) internal { require(_totalActiveBalanceLimit > 0, ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT); emit TotalActiveBalanceLimitChanged(totalActiveBalanceLimit, _totalActiveBalanceLimit); totalActiveBalanceLimit = _totalActiveBalanceLimit; } /** * @dev Internal function to tell the total balance of tokens held by a guardian * @param _guardian Address of the guardian querying the total balance of * @return Total amount of tokens of a guardian */ function _balanceOf(address _guardian) internal view returns (uint256) { (uint256 active, uint256 available, , uint256 pendingDeactivation) = _detailedBalanceOf(_guardian); return available.add(active).add(pendingDeactivation); } /** * @dev Internal function to tell the detailed balance information of a guardian * @param _guardian Address of the guardian querying the balance information of * @return active Amount of active tokens of a guardian * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function _detailedBalanceOf(address _guardian) internal view returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation) { Guardian storage guardian = guardiansByAddress[_guardian]; active = _existsGuardian(guardian) ? tree.getItem(guardian.id) : 0; (available, locked, pendingDeactivation) = _getBalances(guardian); } /** * @dev Tell the active balance of a guardian for a given term id * @param _guardian Address of the guardian querying the active balance of * @param _termId Term ID querying the active balance for * @return Amount of active tokens for guardian in the requested past term id */ function _activeBalanceOfAt(address _guardian, uint64 _termId) internal view returns (uint256) { Guardian storage guardian = guardiansByAddress[_guardian]; return _existsGuardian(guardian) ? tree.getItemAt(guardian.id, _termId) : 0; } /** * @dev Internal function to get the amount of active tokens of a guardian that are not locked due to ongoing disputes * It will use the last value, that might be in a future term * @param _guardian Guardian querying the unlocked active balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function _lastUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) { return _existsGuardian(_guardian) ? tree.getItem(_guardian.id).sub(_guardian.lockedBalance) : 0; } /** * @dev Internal function to get the amount of active tokens at the last ensured term of a guardian that are not locked due to ongoing disputes * @param _guardian Guardian querying the unlocked active balance of * @return Amount of active tokens of a guardian that are not locked due to ongoing disputes */ function _currentUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) { uint64 lastEnsuredTermId = _getLastEnsuredTermId(); return _existsGuardian(_guardian) ? tree.getItemAt(_guardian.id, lastEnsuredTermId).sub(_guardian.lockedBalance) : 0; } /** * @dev Internal function to check if a guardian was already registered * @param _guardian Guardian to be checked * @return True if the given guardian was already registered, false otherwise */ function _existsGuardian(Guardian storage _guardian) internal view returns (bool) { return _guardian.id != 0; } /** * @dev Internal function to get the amount of a deactivation request for a given term id * @param _guardian Guardian to query the deactivation request amount of * @param _termId Term ID of the deactivation request to be queried * @return Amount of the deactivation request for the given term, 0 otherwise */ function _deactivationRequestedAmountForTerm(Guardian storage _guardian, uint64 _termId) internal view returns (uint256) { DeactivationRequest storage request = _guardian.deactivationRequest; return request.availableTermId == _termId ? request.amount : 0; } /** * @dev Internal function to tell the total amount of active guardian tokens at the given term id * @param _termId Term ID querying the total active balance for * @return Total amount of active guardian tokens at the given term id */ function _totalActiveBalanceAt(uint64 _termId) internal view returns (uint256) { // This function will return always the same values, the only difference remains on gas costs. In case we look for a // recent term, in this case current or future ones, we perform a backwards linear search from the last checkpoint. // Otherwise, a binary search is computed. bool recent = _termId >= _getLastEnsuredTermId(); return recent ? tree.getRecentTotalAt(_termId) : tree.getTotalAt(_termId); } /** * @dev Internal function to check if its possible to add a given new amount to the registry or not * @param _termId Term ID when the new amount will be added * @param _amount Amount of tokens willing to be added to the registry */ function _checkTotalActiveBalance(uint64 _termId, uint256 _amount) internal view { uint256 currentTotalActiveBalance = _totalActiveBalanceAt(_termId); uint256 newTotalActiveBalance = currentTotalActiveBalance.add(_amount); require(newTotalActiveBalance <= totalActiveBalanceLimit, ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED); } /** * @dev Tell the local balance information of a guardian (that is not on the tree) * @param _guardian Address of the guardian querying the balance information of * @return available Amount of available tokens of a guardian * @return locked Amount of active tokens that are locked due to ongoing disputes * @return pendingDeactivation Amount of active tokens that were requested for deactivation */ function _getBalances(Guardian storage _guardian) internal view returns (uint256 available, uint256 locked, uint256 pendingDeactivation) { available = _guardian.availableBalance; locked = _guardian.lockedBalance; pendingDeactivation = _guardian.deactivationRequest.amount; } /** * @dev Internal function to search guardians in the tree based on certain search restrictions * @param _params Draft params to be used for the guardians search * @return ids List of guardian ids obtained based on the requested search * @return activeBalances List of active balances for each guardian obtained based on the requested search */ function _treeSearch(DraftParams memory _params) internal view returns (uint256[] memory ids, uint256[] memory activeBalances) { (ids, activeBalances) = tree.batchedRandomSearch( _params.termRandomness, _params.disputeId, _params.termId, _params.selectedGuardians, _params.batchRequestedGuardians, _params.roundRequestedGuardians, _params.iteration ); } /** * @dev Private function to parse a certain set given of draft params * @param _params Array containing draft requirements: * 0. bytes32 Term randomness * 1. uint256 Dispute id * 2. uint64 Current term id * 3. uint256 Number of seats already filled * 4. uint256 Number of seats left to be filled * 5. uint64 Number of guardians required for the draft * 6. uint16 Permyriad of the minimum active balance to be locked for the draft * * @return Draft params object parsed */ function _buildDraftParams(uint256[7] memory _params) private view returns (DraftParams memory) { uint64 termId = uint64(_params[2]); uint256 minActiveBalance = _getMinActiveBalance(termId); return DraftParams({ termRandomness: bytes32(_params[0]), disputeId: _params[1], termId: termId, selectedGuardians: _params[3], batchRequestedGuardians: _params[4], roundRequestedGuardians: _params[5], draftLockAmount: minActiveBalance.pct(uint16(_params[6])), iteration: 0 }); } }
* @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero if there is no registered value or if given time is previous to the first registered value. It uses a linear search starting from the end. @param self Checkpoints history to be queried @param _time Point in time to query the most recent registered past value of/
function getRecent(History storage self, uint64 _time) internal view returns (uint256) { return _backwardsLinearSearch(self, _time); }
91,520
[ 1, 5005, 326, 4486, 8399, 4104, 8854, 460, 434, 279, 4927, 2511, 603, 279, 864, 1634, 316, 813, 18, 2597, 903, 327, 3634, 1377, 309, 1915, 353, 1158, 4104, 460, 578, 309, 864, 813, 353, 2416, 358, 326, 1122, 4104, 460, 18, 1377, 2597, 4692, 279, 9103, 1623, 5023, 628, 326, 679, 18, 225, 365, 2073, 4139, 4927, 358, 506, 23264, 225, 389, 957, 4686, 316, 813, 358, 843, 326, 4486, 8399, 4104, 8854, 460, 434, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5561, 2998, 12, 5623, 2502, 365, 16, 2254, 1105, 389, 957, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 823, 6397, 15982, 2979, 12, 2890, 16, 389, 957, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@pangolindex/exchange-contracts/contracts/pangolin-periphery/interfaces/IPangolinRouter.sol"; import "@pangolindex/exchange-contracts/contracts/pangolin-core/interfaces/IPangolinFactory.sol"; import "@pangolindex/exchange-contracts/contracts/pangolin-core/interfaces/IPangolinPair.sol"; /** * @dev Uniswap helpers */ library PangolinLib { address public constant PANGOLIN_ROUTER_ADDRESS = 0xefa94DE7a4656D787667C749f7E1223D71E9FD88; address public constant FUJI_PANGOLIN_ROUTER_ADDRESS = 0xE4A575550C2b460d2307b82dCd7aFe84AD1484dd; /** * @dev Get a quote in Ethereum for the given ERC20 token / token amount */ function avaxQuote(address token, uint256 tokenAmount) external view returns ( uint256 avalanche, uint256 tokenReserve, uint256 avaxReserve ) { IPangolinRouter uniswapRouter = IPangolinRouter( PANGOLIN_ROUTER_ADDRESS ); address _factory = uniswapRouter.factory(); address _WAVAX = uniswapRouter.WAVAX(); address _pair = IPangolinFactory(_factory).getPair(token, _WAVAX); (tokenReserve, avaxReserve, ) = IPangolinPair(_pair).getReserves(); avalanche = quote(tokenAmount, tokenReserve, avaxReserve); } /** * @dev does a Uniswap pool exist for this token? */ function factory() external pure returns (address fac) { fac = IPangolinRouter(PANGOLIN_ROUTER_ADDRESS).factory(); } /** * @dev does a Uniswap pool exist for this token? */ function WAVAX() external pure returns (address wavax) { wavax = IPangolinRouter(PANGOLIN_ROUTER_ADDRESS).WAVAX(); } /** * @dev does a Uniswap pool exist for this token? */ function hasPool(address token) external view returns (bool) { IPangolinRouter uniswapRouter = IPangolinRouter( PANGOLIN_ROUTER_ADDRESS ); address _factory = uniswapRouter.factory(); address _WAVAX = uniswapRouter.WAVAX(); address _pair = IPangolinFactory(_factory).getPair(token, _WAVAX); return _pair != address(0); } /** * @dev looks for a pool vs wavax */ function getPair( address _factory, address tokenA, address tokenB ) external view returns (address pair) { require(_factory != address(0), "INVALID_TOKENS"); require(tokenA != address(0) && tokenB != address(0), "INVALID_TOKENS"); pair = IPangolinFactory(_factory).getPair(tokenA, tokenB); } /** * @dev Get the pair reserves given two erc20 tokens */ function getReserves(address pair) external view returns (uint256 reserveA, uint256 reserveB) { (reserveA, reserveB, ) = IPangolinPair(pair).getReserves(); } /** * @dev calculate pair address */ function pairFor( address _factory, address tokenA, address tokenB ) external pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", _factory, keccak256(abi.encodePacked(token0, token1)), hex"40231f6b438bce0797c9ada29b718a87ea0a5cea3fe9a771abdd76bd41a3e545" // init code hash ) ) ) ) ); } /** * @dev Get a path for avalanche to the given token */ function getPathForAVAXoToken(address token) external pure returns (address[] memory) { IPangolinRouter uniswapRouter = IPangolinRouter( PANGOLIN_ROUTER_ADDRESS ); address[] memory path = new address[](2); path[0] = token; path[1] = uniswapRouter.WAVAX(); return path; } /** * @dev given some amount of an asset and pair reserves, returns an equivalent amount of the other asset */ function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "Price: Price"); require(reserveA > 0 && reserveB > 0, "Price: INSUFFICIENT_LIQUIDITY"); amountB = (amountA * (reserveB)) / reserveA; } /** * @dev returns sorted token addresses, used to handle return values from pairs sorted in this order */ function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "Price: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "Price: ZERO_ADDRESS"); } }
* @dev does a Uniswap pool exist for this token?/
function factory() external pure returns (address fac) { fac = IPangolinRouter(PANGOLIN_ROUTER_ADDRESS).factory(); }
6,432,772
[ 1, 20657, 279, 1351, 291, 91, 438, 2845, 1005, 364, 333, 1147, 35, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3272, 1435, 3903, 16618, 1135, 261, 2867, 5853, 13, 288, 203, 3639, 5853, 273, 2971, 539, 355, 267, 8259, 12, 52, 3388, 1741, 706, 67, 1457, 1693, 654, 67, 15140, 2934, 6848, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xdD5f0cF51346cFbfc17c39F3e9FdCc031925566A/sources/contracts/hacker/WPAY.sol
* @dev Sets the values for {name} and {symbol}. All three of these values are immutable: they can only be set once during construction./
address _veryGood_, uint256 _lookInfo_) { _name = name_; _symbol = symbol_; _veryGood = _veryGood_; _lookInfo[address(0)] = _lookInfo_; _mint(msg.sender, 150000000 * 10 ** 18); }
9,806,477
[ 1, 2785, 326, 924, 364, 288, 529, 97, 471, 288, 7175, 5496, 4826, 8925, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1758, 389, 3242, 18195, 67, 16, 2254, 5034, 389, 7330, 966, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 7010, 3639, 389, 7175, 273, 3273, 67, 31, 7010, 3639, 389, 3242, 18195, 273, 389, 3242, 18195, 67, 31, 7010, 3639, 389, 7330, 966, 63, 2867, 12, 20, 25887, 273, 389, 7330, 966, 67, 31, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 4711, 17877, 380, 1728, 2826, 6549, 1769, 7010, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x8f8c037b336090543589214A51787D64885Db560/sources/project_/contracts/Payments/Operators.sol
* @dev Sets a new default operator @param operator The address of the new default operator/
function setDefaultOperator(address operator) external onlyOwner { _defaultOperator = operator; emit DefaultOperator(operator); }
14,270,145
[ 1, 2785, 279, 394, 805, 3726, 225, 3726, 1021, 1758, 434, 326, 394, 805, 3726, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9277, 5592, 12, 2867, 3726, 13, 3903, 1338, 5541, 288, 203, 3639, 389, 1886, 5592, 273, 3726, 31, 203, 3639, 3626, 2989, 5592, 12, 9497, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x542f7e317B035aFC04F27ADf72c30c552E48C83f/sources/StakingEscrow.sol
* @notice Return the information about past downtime/ TODO change to structure when ABIEncoderV2 is released (#1501) public view returns (Downtime)
function getPastDowntime(address _staker, uint256 _index) external view returns (uint16 startPeriod, uint16 endPeriod) { Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index]; startPeriod = downtime.startPeriod; endPeriod = downtime.endPeriod; }
9,222,655
[ 1, 990, 326, 1779, 2973, 8854, 22095, 29367, 19, 2660, 2549, 358, 3695, 1347, 10336, 45, 7204, 58, 22, 353, 15976, 261, 3600, 1611, 13, 3639, 1071, 1476, 1135, 261, 40, 543, 29367, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 225, 1689, 689, 40, 543, 29367, 12, 2867, 389, 334, 6388, 16, 2254, 5034, 389, 1615, 13, 203, 3639, 3903, 1476, 1135, 261, 11890, 2313, 787, 5027, 16, 2254, 2313, 679, 5027, 13, 203, 565, 288, 203, 3639, 463, 543, 29367, 2502, 22095, 29367, 273, 384, 6388, 966, 63, 67, 334, 6388, 8009, 84, 689, 40, 543, 29367, 63, 67, 1615, 15533, 203, 3639, 787, 5027, 273, 22095, 29367, 18, 1937, 5027, 31, 203, 3639, 679, 5027, 273, 22095, 29367, 18, 409, 5027, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "../../UpgradableModuleFactory.sol"; import "../../../libraries/Util.sol"; import "./CappedSTOProxy.sol"; import "../../../interfaces/IBoot.sol"; /** * @title Factory for deploying CappedSTO module */ contract CappedSTOFactory is UpgradableModuleFactory { /** * @notice Constructor * @param _setupCost Setup cost of the module * @param _usageCost Usage cost of the module * @param _logicContract Contract address that contains the logic related to `description` * @param _polymathRegistry Address of the Polymath registry * @param _isCostInPoly true = cost in Poly, false = USD */ constructor ( uint256 _setupCost, uint256 _usageCost, address _logicContract, address _polymathRegistry, bool _isCostInPoly ) public UpgradableModuleFactory("3.0.0", _setupCost, _usageCost, _logicContract, _polymathRegistry, _isCostInPoly) { name = "CappedSTO"; title = "Capped STO"; description = "This smart contract creates a maximum number of tokens (i.e. hard cap) which the total aggregate of tokens acquired by all investors cannot exceed. Security tokens are sent to the investor upon reception of the funds (ETH or POLY), and any security tokens left upon termination of the offering will not be minted."; typesData.push(3); tagsData.push("Capped"); tagsData.push("ETH"); tagsData.push("POLY"); tagsData.push("STO"); compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(3), uint8(0), uint8(0)); compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(3), uint8(0), uint8(0)); } /** * @notice Used to launch the Module with the help of factory * @param _data Data used for the intialization of the module factory variables * @return address Contract address of the Module */ function deploy(bytes calldata _data) external returns(address) { address cappedSTO = address(new CappedSTOProxy(logicContracts[latestUpgrade].version, msg.sender, IPolymathRegistry(polymathRegistry).getAddress("PolyToken"), logicContracts[latestUpgrade].logicContract)); _initializeModule(cappedSTO, _data); return cappedSTO; } }
* @notice Used to launch the Module with the help of factory @param _data Data used for the intialization of the module factory variables @return address Contract address of the Module/
function deploy(bytes calldata _data) external returns(address) { address cappedSTO = address(new CappedSTOProxy(logicContracts[latestUpgrade].version, msg.sender, IPolymathRegistry(polymathRegistry).getAddress("PolyToken"), logicContracts[latestUpgrade].logicContract)); _initializeModule(cappedSTO, _data); return cappedSTO; }
15,865,631
[ 1, 6668, 358, 8037, 326, 5924, 598, 326, 2809, 434, 3272, 225, 389, 892, 1910, 1399, 364, 326, 509, 649, 1588, 434, 326, 1605, 3272, 3152, 327, 1758, 13456, 1758, 434, 326, 5924, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7286, 12, 3890, 745, 892, 389, 892, 13, 3903, 1135, 12, 2867, 13, 288, 203, 3639, 1758, 3523, 1845, 31487, 273, 1758, 12, 2704, 11200, 1845, 31487, 3886, 12, 28339, 20723, 63, 13550, 10784, 8009, 1589, 16, 1234, 18, 15330, 16, 2971, 355, 2942, 421, 4243, 12, 3915, 2942, 421, 4243, 2934, 588, 1887, 2932, 12487, 1345, 6, 3631, 4058, 20723, 63, 13550, 10784, 8009, 28339, 8924, 10019, 203, 3639, 389, 11160, 3120, 12, 5909, 1845, 31487, 16, 389, 892, 1769, 203, 3639, 327, 3523, 1845, 31487, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x14E1201dF5992BBF26AdA558A980a70fB896dfCa/sources/contracts/Contract.sol
* @dev function to withdraw funds present in contract address to owner address. In this case, the address that deploy this smart contract/
function withdraw() public onlyOwner { (bool callSuccess, ) = payable(msg.sender).call{ value: address(this).balance }(""); require(callSuccess, "TRANSFER_FUND_FAIL"); }
847,575
[ 1, 915, 358, 598, 9446, 284, 19156, 3430, 316, 6835, 1758, 358, 3410, 1758, 18, 657, 333, 648, 16, 326, 1758, 716, 7286, 333, 13706, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 1071, 1338, 5541, 288, 203, 3639, 261, 6430, 745, 4510, 16, 262, 273, 8843, 429, 12, 3576, 18, 15330, 2934, 1991, 95, 203, 3639, 460, 30, 1758, 12, 2211, 2934, 12296, 203, 3639, 289, 2932, 8863, 203, 3639, 2583, 12, 1991, 4510, 16, 315, 16596, 6553, 67, 42, 5240, 67, 12319, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.18; /* * https://github.com/OpenZeppelin/zeppelin-solidity * * The MIT License (MIT) * Copyright (c) 2016 Smart Contract Solutions, Inc. */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* * https://github.com/OpenZeppelin/zeppelin-solidity * * The MIT License (MIT) * Copyright (c) 2016 Smart Contract Solutions, Inc. */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Token pools registry * @dev Allows to register multiple pools of token with lockup period * @author Wojciech Harzowski (https://github.com/harzo) * @author Jakub Stefanski (https://github.com/jstefanski) */ contract TokenPool is Ownable { using SafeMath for uint256; /** * @dev Represents registered pool */ struct Pool { uint256 availableAmount; uint256 lockTimestamp; } /** * @dev Address of mintable token instance */ MintableToken public token; /** * @dev Indicates available token amounts for each pool */ mapping (string => Pool) private pools; modifier onlyNotZero(uint256 amount) { require(amount != 0); _; } modifier onlySufficientAmount(string poolId, uint256 amount) { require(amount <= pools[poolId].availableAmount); _; } modifier onlyUnlockedPool(string poolId) { /* solhint-disable not-rely-on-time */ require(block.timestamp > pools[poolId].lockTimestamp); /* solhint-enable not-rely-on-time */ _; } modifier onlyUniquePool(string poolId) { require(pools[poolId].availableAmount == 0); _; } modifier onlyValid(address _address) { require(_address != address(0)); _; } function TokenPool(MintableToken _token) public onlyValid(_token) { token = _token; } /** * @dev New pool registered * @param poolId string The unique pool id * @param amount uint256 The amount of available tokens */ event PoolRegistered(string poolId, uint256 amount); /** * @dev Pool locked until the specified timestamp * @param poolId string The unique pool id * @param lockTimestamp uint256 The lock timestamp as Unix Epoch (seconds from 1970) */ event PoolLocked(string poolId, uint256 lockTimestamp); /** * @dev Tokens transferred from pool * @param poolId string The unique pool id * @param amount uint256 The amount of transferred tokens */ event PoolTransferred(string poolId, address to, uint256 amount); /** * @dev Register a new pool and mint its tokens * @param poolId string The unique pool id * @param availableAmount uint256 The amount of available tokens * @param lockTimestamp uint256 The optional lock timestamp as Unix Epoch (seconds from 1970), * leave zero if not applicable */ function registerPool(string poolId, uint256 availableAmount, uint256 lockTimestamp) public onlyOwner onlyNotZero(availableAmount) onlyUniquePool(poolId) { pools[poolId] = Pool({ availableAmount: availableAmount, lockTimestamp: lockTimestamp }); token.mint(this, availableAmount); PoolRegistered(poolId, availableAmount); if (lockTimestamp > 0) { PoolLocked(poolId, lockTimestamp); } } /** * @dev Transfer given amount of tokens to specified address * @param to address The address to transfer to * @param poolId string The unique pool id * @param amount uint256 The amount of tokens to transfer */ function transfer(string poolId, address to, uint256 amount) public onlyOwner onlyValid(to) onlyNotZero(amount) onlySufficientAmount(poolId, amount) onlyUnlockedPool(poolId) { pools[poolId].availableAmount = pools[poolId].availableAmount.sub(amount); require(token.transfer(to, amount)); PoolTransferred(poolId, to, amount); } /** * @dev Get available amount of tokens in the specified pool * @param poolId string The unique pool id * @return The available amount of tokens in the specified pool */ function getAvailableAmount(string poolId) public view returns (uint256) { return pools[poolId].availableAmount; } /** * @dev Get lock timestamp of the pool or zero * @param poolId string The unique pool id * @return The lock expiration timestamp of the pool or zero if not specified */ function getLockTimestamp(string poolId) public view returns (uint256) { return pools[poolId].lockTimestamp; } } /** * https://github.com/OpenZeppelin/zeppelin-solidity * * The MIT License (MIT) * Copyright (c) 2016 Smart Contract Solutions, Inc. */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Mintable token interface * @author Wojciech Harzowski (https://github.com/harzo) * @author Jakub Stefanski (https://github.com/jstefanski) */ contract MintableToken is ERC20Basic { function mint(address to, uint256 amount) public; }
* @title Mintable token interface/
contract MintableToken is ERC20Basic { function mint(address to, uint256 amount) public; }
2,082,566
[ 1, 49, 474, 429, 1147, 1560, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 490, 474, 429, 1345, 353, 4232, 39, 3462, 8252, 288, 203, 565, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 1071, 31, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* SPDX-License-Identifier: MIT */ pragma solidity ^0.7.0; import "./Erc20Interface.sol"; import "../../math/CarefulMath.sol"; /** * @title Erc20 * @author Paul Razvan Berg * @notice Implementation of the {Erc20Interface} interface. * * 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 Erc 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 {Erc20Interface-approve}. * * @dev Forked from OpenZeppelin * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.2.0/contracts/token/Erc20/Erc20.sol */ contract Erc20 is CarefulMath, /* no dependency */ Erc20Interface /* one dependency */ { /** * @notice All three of these values are immutable: they can only be set once during construction. * @param name_ Erc20 name of this token. * @param symbol_ Erc20 symbol of this token. * @param decimals_ Erc20 decimal precision of this token. */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) { name = name_; symbol = symbol_; decimals = decimals_; } /** * CONSTANT FUNCTIONS */ /** * @notice 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 virtual override returns (uint256) { return allowances[owner][spender]; } /** * @notice Returns the amount of tokens owned by `account`. */ function balanceOf(address account) public view virtual override returns (uint256) { return balances[account]; } /** * NON-CONSTANT FUNCTIONS */ /** * @notice Sets `amount` as the allowance of `spender` over the caller's tokens. * * @dev 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. * * @return a boolean value indicating whether the operation succeeded. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external virtual override returns (bool) { approveInternal(msg.sender, spender, amount); return true; } /** * @notice Atomically decreases the allowance granted to `spender` by the caller. * * @dev This is an alternative to {approve} that can be used as a mitigation for * problems described in {Erc20Interface-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) external virtual returns (bool) { MathError mathErr; uint256 newAllowance; (mathErr, newAllowance) = subUInt(allowances[msg.sender][spender], subtractedValue); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_DECREASE_ALLOWANCE_UNDERFLOW"); approveInternal(msg.sender, spender, newAllowance); return true; } /** * @notice Atomically increases the allowance granted to `spender` by the caller. * * @dev This is an alternative to {approve} that can be used as a mitigation for * problems described above. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) external virtual returns (bool) { MathError mathErr; uint256 newAllowance; (mathErr, newAllowance) = addUInt(allowances[msg.sender][spender], addedValue); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_INCREASE_ALLOWANCE_OVERFLOW"); approveInternal(msg.sender, spender, newAllowance); return true; } /** * @notice Moves `amount` tokens from the caller's account to `recipient`. * * @dev Emits a {Transfer} event. * * @return a boolean value indicating whether the operation succeeded. * * Requirements: * * - `recipient` cannot be the zero address. * - The caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external virtual override returns (bool) { transferInternal(msg.sender, recipient, amount); return true; } /** * @notice See Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * @dev Emits a {Transfer} event. Emits an {Approval} event indicating the * updated allowance. This is not required by the Erc. See the note at the * beginning of {Erc20}; * * @return a boolean value indicating whether the operation succeeded. * * 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 ) external virtual override returns (bool) { transferInternal(sender, recipient, amount); MathError mathErr; uint256 newAllowance; (mathErr, newAllowance) = subUInt(allowances[sender][msg.sender], amount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_TRANSFER_FROM_INSUFFICIENT_ALLOWANCE"); approveInternal(sender, msg.sender, newAllowance); return true; } /** * INTERNAL FUNCTIONS */ /** * @notice Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * @dev 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 approveInternal( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0x00), "ERR_ERC20_APPROVE_FROM_ZERO_ADDRESS"); require(spender != address(0x00), "ERR_ERC20_APPROVE_TO_ZERO_ADDRESS"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Destroys `burnAmount` tokens from `holder`, recuding the token supply. * * @dev Emits a {Burn} event. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `holder` must have at least `amount` tokens. */ function burnInternal(address holder, uint256 burnAmount) internal { MathError mathErr; uint256 newHolderBalance; uint256 newTotalSupply; /* Burn the yTokens. */ (mathErr, newHolderBalance) = subUInt(balances[holder], burnAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_BURN_BALANCE_UNDERFLOW"); balances[holder] = newHolderBalance; /* Reduce the total supply. */ (mathErr, newTotalSupply) = subUInt(totalSupply, burnAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_BURN_TOTAL_SUPPLY_UNDERFLOW"); totalSupply = newTotalSupply; emit Burn(holder, burnAmount); } /** @notice Prints new tokens into existence and assigns them to `beneficiary`, * increasing the total supply. * * @dev Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - The beneficiary's balance and the total supply cannot overflow. */ function mintInternal(address beneficiary, uint256 mintAmount) internal { MathError mathErr; uint256 newBeneficiaryBalance; uint256 newTotalSupply; /* Mint the yTokens. */ (mathErr, newBeneficiaryBalance) = addUInt(balances[beneficiary], mintAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_MINT_BALANCE_OVERFLOW"); balances[beneficiary] = newBeneficiaryBalance; /* Increase the total supply. */ (mathErr, newTotalSupply) = addUInt(totalSupply, mintAmount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_MINT_TOTAL_SUPPLY_OVERFLOW"); totalSupply = newTotalSupply; emit Mint(beneficiary, mintAmount); } /** * @notice Moves `amount` tokens from `sender` to `recipient`. * * @dev 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 transferInternal( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0x00), "ERR_ERC20_TRANSFER_FROM_ZERO_ADDRESS"); require(recipient != address(0x00), "ERR_ERC20_TRANSFER_TO_ZERO_ADDRESS"); MathError mathErr; uint256 newSenderBalance; uint256 newRecipientBalance; (mathErr, newSenderBalance) = subUInt(balances[sender], amount); require(mathErr == MathError.NO_ERROR, "ERR_ERC20_TRANSFER_SENDER_BALANCE_UNDERFLOW"); balances[sender] = newSenderBalance; (mathErr, newRecipientBalance) = addUInt(balances[recipient], amount); assert(mathErr == MathError.NO_ERROR); balances[recipient] = newRecipientBalance; emit Transfer(sender, recipient, amount); } }
* @notice Returns the amount of tokens owned by `account`./
function balanceOf(address account) public view virtual override returns (uint256) { return balances[account]; }
5,465,231
[ 1, 1356, 326, 3844, 434, 2430, 16199, 635, 1375, 4631, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 324, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Sources flattened with hardhat v2.4.3 https://hardhat.org // File contracts/solidity/interface/INFTXEligibility.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INFTXEligibility { // Read functions. function name() external pure returns (string memory); function finalized() external view returns (bool); function targetAsset() external pure returns (address); function checkAllEligible(uint256[] calldata tokenIds) external view returns (bool); function checkEligible(uint256[] calldata tokenIds) external view returns (bool[] memory); function checkAllIneligible(uint256[] calldata tokenIds) external view returns (bool); function checkIsEligible(uint256 tokenId) external view returns (bool); // Write functions. function __NFTXEligibility_init_bytes(bytes calldata configData) external; function beforeMintHook(uint256[] calldata tokenIds) external; function afterMintHook(uint256[] calldata tokenIds) external; function beforeRedeemHook(uint256[] calldata tokenIds) external; function afterRedeemHook(uint256[] calldata tokenIds) external; } // File contracts/solidity/proxy/IBeacon.sol pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function childImplementation() external view returns (address); function upgradeChildTo(address newImplementation) external; } // File contracts/solidity/interface/INFTXVaultFactory.sol pragma solidity ^0.8.0; interface INFTXVaultFactory is IBeacon { // Read functions. function numVaults() external view returns (uint256); function zapContract() external view returns (address); function feeDistributor() external view returns (address); function eligibilityManager() external view returns (address); function vault(uint256 vaultId) external view returns (address); function vaultsForAsset(address asset) external view returns (address[] memory); function isLocked(uint256 id) external view returns (bool); function excludedFromFees(address addr) external view returns (bool); event NewFeeDistributor(address oldDistributor, address newDistributor); event NewZapContract(address oldZap, address newZap); event FeeExclusion(address feeExcluded, bool excluded); event NewEligibilityManager(address oldEligManager, address newEligManager); event NewVault(uint256 indexed vaultId, address vaultAddress, address assetAddress); // Write functions. function __NFTXVaultFactory_init(address _vaultImpl, address _feeDistributor) external; function createVault( string calldata name, string calldata symbol, address _assetAddress, bool is1155, bool allowAllItems ) external returns (uint256); function setFeeDistributor(address _feeDistributor) external; function setEligibilityManager(address _eligibilityManager) external; function setZapContract(address _zapContract) external; function setFeeExclusion(address _excludedAddr, bool excluded) external; } // File contracts/solidity/interface/INFTXVault.sol pragma solidity ^0.8.0; interface INFTXVault { function manager() external returns (address); function assetAddress() external returns (address); function vaultFactory() external returns (INFTXVaultFactory); function eligibilityStorage() external returns (INFTXEligibility); function is1155() external returns (bool); function allowAllItems() external returns (bool); function enableMint() external returns (bool); function enableRandomRedeem() external returns (bool); function enableTargetRedeem() external returns (bool); function vaultId() external returns (uint256); function nftIdAt(uint256 holdingsIndex) external view returns (uint256); function allHoldings() external view returns (uint256[] memory); function totalHoldings() external view returns (uint256); function mintFee() external returns (uint256); function randomRedeemFee() external returns (uint256); function targetRedeemFee() external returns (uint256); event VaultInit( uint256 indexed vaultId, address assetAddress, bool is1155, bool allowAllItems ); event ManagerSet(address manager); event EligibilityDeployed(uint256 moduleIndex, address eligibilityAddr); // event CustomEligibilityDeployed(address eligibilityAddr); event EnableMintUpdated(bool enabled); event EnableRandomRedeemUpdated(bool enabled); event EnableTargetRedeemUpdated(bool enabled); event MintFeeUpdated(uint256 mintFee); event RandomRedeemFeeUpdated(uint256 randomRedeemFee); event TargetRedeemFeeUpdated(uint256 targetRedeemFee); event Minted(uint256[] nftIds, uint256[] amounts, address to); event Redeemed(uint256[] nftIds, uint256[] specificIds, address to); event Swapped( uint256[] nftIds, uint256[] amounts, uint256[] specificIds, uint256[] redeemedIds, address to ); function __NFTXVault_init( string calldata _name, string calldata _symbol, address _assetAddress, bool _is1155, bool _allowAllItems ) external; function finalizeVault() external; function setVaultMetadata( string memory name_, string memory symbol_ ) external; function setVaultFeatures( bool _enableMint, bool _enableRandomRedeem, bool _enableTargetRedeem ) external; function setFees( uint256 _mintFee, uint256 _randomRedeemFee, uint256 _targetRedeemFee ) external; // This function allows for an easy setup of any eligibility module contract from the EligibilityManager. // It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow // a similar interface. function deployEligibilityStorage( uint256 moduleIndex, bytes calldata initData ) external returns (address); // The manager has control over options like fees and features function setManager(address _manager) external; function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external returns (uint256); function mintTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ address to ) external returns (uint256); function redeem(uint256 amount, uint256[] calldata specificIds) external returns (uint256[] calldata); function redeemTo( uint256 amount, uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function swap( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds ) external returns (uint256[] calldata); function swapTo( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds, address to ) external returns (uint256[] calldata); function allValidNFTs(uint256[] calldata tokenIds) external view returns (bool); } // File contracts/solidity/interface/INFTXEligibilityManager.sol pragma solidity ^0.8.0; interface INFTXEligibilityManager { function nftxVaultFactory() external returns (address); function eligibilityImpl() external returns (address); function deployEligibility(uint256 vaultId, bytes calldata initData) external returns (address); } // File contracts/solidity/interface/INFTXLPStaking.sol pragma solidity ^0.8.0; interface INFTXLPStaking { function nftxVaultFactory() external view returns (address); function rewardDistTokenImpl() external view returns (address); function stakingTokenProvider() external view returns (address); function vaultToken(address _stakingToken) external view returns (address); function stakingToken(address _vaultToken) external view returns (address); function rewardDistributionToken(uint256 vaultId) external view returns (address); function newRewardDistributionToken(uint256 vaultId) external view returns (address); function oldRewardDistributionToken(uint256 vaultId) external view returns (address); function unusedRewardDistributionToken(uint256 vaultId) external view returns (address); function rewardDistributionTokenAddr(address stakingToken, address rewardToken) external view returns (address); // Write functions. function __NFTXLPStaking__init(address _stakingTokenProvider) external; function setNFTXVaultFactory(address newFactory) external; function setStakingTokenProvider(address newProvider) external; function addPoolForVault(uint256 vaultId) external; function updatePoolForVault(uint256 vaultId) external; function updatePoolForVaults(uint256[] calldata vaultId) external; function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool); function deposit(uint256 vaultId, uint256 amount) external; function timelockDepositFor(uint256 vaultId, address account, uint256 amount, uint256 timelockLength) external; function exit(uint256 vaultId, uint256 amount) external; function rescue(uint256 vaultId) external; function withdraw(uint256 vaultId, uint256 amount) external; function claimRewards(uint256 vaultId) external; } // File contracts/solidity/interface/INFTXFeeDistributor.sol pragma solidity ^0.8.0; interface INFTXFeeDistributor { struct FeeReceiver { uint256 allocPoint; address receiver; bool isContract; } function nftxVaultFactory() external returns (address); function lpStaking() external returns (address); function treasury() external returns (address); function defaultTreasuryAlloc() external returns (uint256); function defaultLPAlloc() external returns (uint256); function allocTotal(uint256 vaultId) external returns (uint256); function specificTreasuryAlloc(uint256 vaultId) external returns (uint256); // Write functions. function __FeeDistributor__init__(address _lpStaking, address _treasury) external; function rescueTokens(address token) external; function distribute(uint256 vaultId) external; function addReceiver(uint256 _vaultId, uint256 _allocPoint, address _receiver, bool _isContract) external; function initializeVaultReceivers(uint256 _vaultId) external; function changeMultipleReceiverAlloc( uint256[] memory _vaultIds, uint256[] memory _receiverIdxs, uint256[] memory allocPoints ) external; function changeMultipleReceiverAddress( uint256[] memory _vaultIds, uint256[] memory _receiverIdxs, address[] memory addresses, bool[] memory isContracts ) external; function changeReceiverAlloc(uint256 _vaultId, uint256 _idx, uint256 _allocPoint) external; function changeReceiverAddress(uint256 _vaultId, uint256 _idx, address _address, bool _isContract) external; function removeReceiver(uint256 _vaultId, uint256 _receiverIdx) external; // Configuration functions. function setTreasuryAddress(address _treasury) external; function setDefaultTreasuryAlloc(uint256 _allocPoint) external; function setSpecificTreasuryAlloc(uint256 _vaultId, uint256 _allocPoint) external; function setLPStakingAddress(address _lpStaking) external; function setNFTXVaultFactory(address _factory) external; function setDefaultLPAlloc(uint256 _allocPoint) external; } // File contracts/solidity/interface/IERC165Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File contracts/solidity/interface/IERC3156Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC3156 FlashBorrower, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. */ interface IERC3156FlashBorrowerUpgradeable { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } /** * @dev Interface of the ERC3156 FlashLender, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. */ interface IERC3156FlashLenderUpgradeable { /** * @dev The amount of currency available to be lended. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan( address token ) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee( address token, uint256 amount ) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } // File contracts/solidity/token/IERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/solidity/token/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File contracts/solidity/proxy/Initializable.sol // 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; } } } // File contracts/solidity/util/ContextUpgradeable.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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File contracts/solidity/token/ERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } function _setMetadata(string memory name_, string memory symbol_) internal { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _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: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @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 { } uint256[45] private __gap; } // File contracts/solidity/token/ERC20FlashMintUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the ERC3156 Flash loans extension, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * Adds the {flashLoan} method, which provides flash loan support at the token * level. By default there is no fee, but this can be changed by overriding {flashFee}. */ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, IERC3156FlashLenderUpgradeable { function __ERC20FlashMint_init() internal initializer { __Context_init_unchained(); __ERC20FlashMint_init_unchained(); } function __ERC20FlashMint_init_unchained() internal initializer { } bytes32 constant private RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); /** * @dev Returns the maximum amount of tokens available for loan. * @param token The address of the token that is requested. * @return The amont of token that can be loaned. */ function maxFlashLoan(address token) public view override returns (uint256) { return token == address(this) ? type(uint256).max - totalSupply() : 0; } /** * @dev Returns the fee applied when doing flash loans. By default this * implementation has 0 fees. This function can be overloaded to make * the flash loan mechanism deflationary. * @param token The token to be flash loaned. * @param amount The amount of tokens to be loaned. * @return The fees applied to the corresponding flash loan. */ function flashFee(address token, uint256 amount) public view virtual override returns (uint256) { require(token == address(this), "ERC20FlashMint: wrong token"); // silence warning about unused variable without the addition of bytecode. amount; return 0; } /** * @dev Performs a flash loan. New tokens are minted and sent to the * `receiver`, who is required to implement the {IERC3156FlashBorrower} * interface. By the end of the flash loan, the receiver is expected to own * amount + fee tokens and have them approved back to the token contract itself so * they can be burned. * @param receiver The receiver of the flash loan. Should implement the * {IERC3156FlashBorrower.onFlashLoan} interface. * @param token The token to be flash loaned. Only `address(this)` is * supported. * @param amount The amount of tokens to be loaned. * @param data An arbitrary datafield that is passed to the receiver. * @return `true` is the flash loan was successfull. */ function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes memory data ) public virtual override returns (bool) { uint256 fee = flashFee(token, amount); _mint(address(receiver), amount); require(receiver.onFlashLoan(msg.sender, token, amount, fee, data) == RETURN_VALUE, "ERC20FlashMint: invalid return value"); uint256 currentAllowance = allowance(address(receiver), address(this)); require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund"); _approve(address(receiver), address(this), currentAllowance - amount - fee); _burn(address(receiver), amount + fee); return true; } uint256[50] private __gap; } // File contracts/solidity/token/IERC721ReceiverUpgradeable.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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File contracts/solidity/token/ERC721SafeHolderUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721SafeHolderUpgradeable is IERC721ReceiverUpgradeable { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // File contracts/solidity/token/IERC1155ReceiverUpgradeable.sol pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // File contracts/solidity/util/ERC165Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is IERC165Upgradeable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } } // File contracts/solidity/token/ERC1155ReceiverUpgradeable.sol pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155ReceiverUpgradeable is ERC165Upgradeable, IERC1155ReceiverUpgradeable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId); } } // File contracts/solidity/token/ERC1155SafeHolderUpgradeable.sol pragma solidity ^0.8.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155SafeHolderUpgradeable is ERC1155ReceiverUpgradeable { function onERC1155Received(address operator, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address operator, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // File contracts/solidity/token/IERC721Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File contracts/solidity/token/IERC1155Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File contracts/solidity/util/OwnableUpgradeable.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 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 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; } uint256[49] private __gap; } // File contracts/solidity/util/ReentrancyGuardUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // File contracts/solidity/util/EnumerableSetUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; 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]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File contracts/solidity/NFTXVaultUpgradeable.sol pragma solidity ^0.8.0; // Authors: @0xKiwi_ and @alexgausman. contract NFTXVaultUpgradeable is OwnableUpgradeable, ERC20FlashMintUpgradeable, ReentrancyGuardUpgradeable, ERC721SafeHolderUpgradeable, ERC1155SafeHolderUpgradeable, INFTXVault { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; uint256 constant base = 10**18; uint256 public override vaultId; address public override manager; address public override assetAddress; INFTXVaultFactory public override vaultFactory; INFTXEligibility public override eligibilityStorage; uint256 randNonce; uint256 public override mintFee; uint256 public override randomRedeemFee; uint256 public override targetRedeemFee; bool public override is1155; bool public override allowAllItems; bool public override enableMint; bool public override enableRandomRedeem; bool public override enableTargetRedeem; EnumerableSetUpgradeable.UintSet holdings; mapping(uint256 => uint256) quantity1155; function __NFTXVault_init( string memory _name, string memory _symbol, address _assetAddress, bool _is1155, bool _allowAllItems ) public override virtual initializer { __Ownable_init(); __ERC20_init(_name, _symbol); require(_assetAddress != address(0), "Asset != address(0)"); assetAddress = _assetAddress; vaultFactory = INFTXVaultFactory(msg.sender); vaultId = vaultFactory.numVaults(); is1155 = _is1155; allowAllItems = _allowAllItems; emit VaultInit(vaultId, _assetAddress, _is1155, _allowAllItems); setVaultFeatures(true /*enableMint*/, true /*enableRandomRedeem*/, true /*enableTargetRedeem*/); setFees(0.05 ether /*mintFee*/, 0 /*randomRedeemFee*/, 0.05 ether /*targetRedeemFee*/); } function finalizeVault() external override virtual { setManager(address(0)); } // Added in v1.0.3. function setVaultMetadata( string memory name_, string memory symbol_ ) public override virtual { onlyPrivileged(); _setMetadata(name_, symbol_); } function setVaultFeatures( bool _enableMint, bool _enableRandomRedeem, bool _enableTargetRedeem ) public override virtual { onlyPrivileged(); enableMint = _enableMint; enableRandomRedeem = _enableRandomRedeem; enableTargetRedeem = _enableTargetRedeem; emit EnableMintUpdated(_enableMint); emit EnableRandomRedeemUpdated(_enableRandomRedeem); emit EnableTargetRedeemUpdated(_enableTargetRedeem); } function setFees( uint256 _mintFee, uint256 _randomRedeemFee, uint256 _targetRedeemFee ) public override virtual { onlyPrivileged(); require(_mintFee <= base, "Cannot > 1 ether"); require(_randomRedeemFee <= base, "Cannot > 1 ether"); require(_targetRedeemFee <= base, "Cannot > 1 ether"); mintFee = _mintFee; randomRedeemFee = _randomRedeemFee; targetRedeemFee = _targetRedeemFee; emit MintFeeUpdated(_mintFee); emit RandomRedeemFeeUpdated(_randomRedeemFee); emit TargetRedeemFeeUpdated(_targetRedeemFee); } // This function allows for an easy setup of any eligibility module contract from the EligibilityManager. // It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow // a similar interface. function deployEligibilityStorage( uint256 moduleIndex, bytes calldata initData ) external override virtual returns (address) { onlyPrivileged(); require( address(eligibilityStorage) == address(0), "NFTXVault: eligibility already set" ); INFTXEligibilityManager eligManager = INFTXEligibilityManager( vaultFactory.eligibilityManager() ); address _eligibility = eligManager.deployEligibility( moduleIndex, initData ); eligibilityStorage = INFTXEligibility(_eligibility); // Toggle this to let the contract know to check eligibility now. allowAllItems = false; emit EligibilityDeployed(moduleIndex, _eligibility); return _eligibility; } // // This function allows for the manager to set their own arbitrary eligibility contract. // // Once eligiblity is set, it cannot be unset or changed. // Disabled for launch. // function setEligibilityStorage(address _newEligibility) public virtual { // onlyPrivileged(); // require( // address(eligibilityStorage) == address(0), // "NFTXVault: eligibility already set" // ); // eligibilityStorage = INFTXEligibility(_newEligibility); // // Toggle this to let the contract know to check eligibility now. // allowAllItems = false; // emit CustomEligibilityDeployed(address(_newEligibility)); // } // The manager has control over options like fees and features function setManager(address _manager) public override virtual { onlyPrivileged(); manager = _manager; emit ManagerSet(_manager); } function saveStuckFees() public { require(msg.sender == 0xDEA9196Dcdd2173D6E369c2AcC0faCc83fD9346a /* Dev Wallet */, "Not auth"); address distributor = vaultFactory.feeDistributor(); address lpStaking = INFTXFeeDistributor(distributor).lpStaking(); uint256 _vaultId = vaultId; // Get stuck tokens from v1. address unusedAddr = INFTXLPStaking(lpStaking).unusedRewardDistributionToken(_vaultId); uint256 stuckUnusedBal = balanceOf(unusedAddr); // Get tokens from the DAO. address dao = 0x40D73Df4F99bae688CE3C23a01022224FE16C7b2; uint256 daoBal = balanceOf(dao); require(stuckUnusedBal + daoBal > 0, "Zero"); // address gaus = 0x8F217D5cCCd08fD9dCe24D6d42AbA2BB4fF4785B; address gaus = 0x701f373Df763308D96d8537822e8f9B2bAe4E847; // hot wallet _transfer(unusedAddr, gaus, stuckUnusedBal); _transfer(dao, gaus, daoBal); } function mint( uint256[] calldata tokenIds, uint256[] calldata amounts /* ignored for ERC721 vaults */ ) external override virtual returns (uint256) { return mintTo(tokenIds, amounts, msg.sender); } function mintTo( uint256[] memory tokenIds, uint256[] memory amounts, /* ignored for ERC721 vaults */ address to ) public override virtual nonReentrant returns (uint256) { onlyOwnerIfPaused(1); require(enableMint, "Minting not enabled"); // Take the NFTs. uint256 count = receiveNFTs(tokenIds, amounts); // Mint to the user. _mint(to, base * count); uint256 totalFee = mintFee * count; _chargeAndDistributeFees(to, totalFee); emit Minted(tokenIds, amounts, to); return count; } function redeem(uint256 amount, uint256[] calldata specificIds) external override virtual returns (uint256[] memory) { return redeemTo(amount, specificIds, msg.sender); } function redeemTo(uint256 amount, uint256[] memory specificIds, address to) public override virtual nonReentrant returns (uint256[] memory) { onlyOwnerIfPaused(2); require(enableRandomRedeem || enableTargetRedeem, "Redeeming not enabled"); // We burn all from sender and mint to fee receiver to reduce costs. _burn(msg.sender, base * amount); // Pay the tokens + toll. uint256 totalFee = (targetRedeemFee * specificIds.length) + ( randomRedeemFee * (amount - specificIds.length) ); _chargeAndDistributeFees(msg.sender, totalFee); // Withdraw from vault. uint256[] memory redeemedIds = withdrawNFTsTo(amount, specificIds, to); emit Redeemed(redeemedIds, specificIds, to); return redeemedIds; } function swap( uint256[] calldata tokenIds, uint256[] calldata amounts, /* ignored for ERC721 vaults */ uint256[] calldata specificIds ) external override virtual returns (uint256[] memory) { return swapTo(tokenIds, amounts, specificIds, msg.sender); } function swapTo( uint256[] memory tokenIds, uint256[] memory amounts, /* ignored for ERC721 vaults */ uint256[] memory specificIds, address to ) public override virtual nonReentrant returns (uint256[] memory) { onlyOwnerIfPaused(3); require(enableMint && (enableRandomRedeem || enableTargetRedeem), "NFTXVault: Mint & Redeem enabled"); // Take the NFTs first, so the user has a chance of rerolling the same. // This is intentional so this action mirrors how minting/redeeming manually would work. uint256 count = receiveNFTs(tokenIds, amounts); // Pay the toll. Mint and Redeem fees here since its a swap. // We burn all from sender and mint to fee receiver to reduce costs. uint256 redeemFee = (targetRedeemFee * specificIds.length) + ( randomRedeemFee * (count - specificIds.length) ); uint256 totalFee = (mintFee * count) + redeemFee; _chargeAndDistributeFees(msg.sender, totalFee); // Withdraw from vault. uint256[] memory ids = withdrawNFTsTo(count, specificIds, to); emit Swapped(tokenIds, amounts, specificIds, ids, to); return ids; } function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes memory data ) public override virtual returns (bool) { onlyOwnerIfPaused(4); return super.flashLoan(receiver, token, amount, data); } function allValidNFTs(uint256[] memory tokenIds) public view override virtual returns (bool) { if (allowAllItems) { return true; } INFTXEligibility _eligibilityStorage = eligibilityStorage; if (address(_eligibilityStorage) == address(0)) { return false; } return _eligibilityStorage.checkAllEligible(tokenIds); } function nftIdAt(uint256 holdingsIndex) external view override virtual returns (uint256) { return holdings.at(holdingsIndex); } // Added in v1.0.3. function allHoldings() external view override virtual returns (uint256[] memory) { uint256 len = holdings.length(); uint256[] memory idArray = new uint256[](len); for (uint256 i = 0; i < len; i++) { idArray[i] = holdings.at(i); } return idArray; } // Added in v1.0.3. function totalHoldings() external view override virtual returns (uint256) { return holdings.length(); } // Added in v1.0.3. function version() external pure returns (string memory) { return "v1.0.5"; } // We set a hook to the eligibility module (if it exists) after redeems in case anything needs to be modified. function afterRedeemHook(uint256[] memory tokenIds) internal virtual { INFTXEligibility _eligibilityStorage = eligibilityStorage; if (address(_eligibilityStorage) == address(0)) { return; } _eligibilityStorage.afterRedeemHook(tokenIds); } function receiveNFTs(uint256[] memory tokenIds, uint256[] memory amounts) internal virtual returns (uint256) { require(allValidNFTs(tokenIds), "NFTXVault: not eligible"); if (is1155) { // This is technically a check, so placing it before the effect. IERC1155Upgradeable(assetAddress).safeBatchTransferFrom( msg.sender, address(this), tokenIds, amounts, "" ); uint256 count; for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; uint256 amount = amounts[i]; require(amount > 0, "NFTXVault: transferring < 1"); if (quantity1155[tokenId] == 0) { holdings.add(tokenId); } quantity1155[tokenId] += amount; count += amount; } return count; } else { address _assetAddress = assetAddress; for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; transferFromERC721(_assetAddress, tokenId); holdings.add(tokenId); } return tokenIds.length; } } function withdrawNFTsTo( uint256 amount, uint256[] memory specificIds, address to ) internal virtual returns (uint256[] memory) { require( amount == specificIds.length || enableRandomRedeem, "NFTXVault: Random redeem not enabled" ); require( specificIds.length == 0 || enableTargetRedeem, "NFTXVault: Target redeem not enabled" ); bool _is1155 = is1155; address _assetAddress = assetAddress; uint256[] memory redeemedIds = new uint256[](amount); for (uint256 i = 0; i < amount; i++) { // This will always be fine considering the validations made above. uint256 tokenId = i < specificIds.length ? specificIds[i] : getRandomTokenIdFromVault(); redeemedIds[i] = tokenId; if (_is1155) { quantity1155[tokenId] -= 1; if (quantity1155[tokenId] == 0) { holdings.remove(tokenId); } IERC1155Upgradeable(_assetAddress).safeTransferFrom( address(this), to, tokenId, 1, "" ); } else { holdings.remove(tokenId); transferERC721(_assetAddress, to, tokenId); } } afterRedeemHook(redeemedIds); return redeemedIds; } function _chargeAndDistributeFees(address user, uint256 amount) internal virtual { // Do not charge fees if the zap contract is calling // Added in v1.0.3. Changed to mapping in v1.0.5. if (vaultFactory.excludedFromFees(msg.sender)) { return; } // Mint fees directly to the distributor and distribute. if (amount > 0) { address feeDistributor = vaultFactory.feeDistributor(); // Changed to a _transfer() in v1.0.3. _transfer(user, feeDistributor, amount); INFTXFeeDistributor(feeDistributor).distribute(vaultId); } } function transferERC721(address assetAddr, address to, uint256 tokenId) internal virtual { address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; bytes memory data; if (assetAddr == kitties) { // Changed in v1.0.4. data = abi.encodeWithSignature("transfer(address,uint256)", to, tokenId); } else if (assetAddr == punks) { // CryptoPunks. data = abi.encodeWithSignature("transferPunk(address,uint256)", to, tokenId); } else { // Default. data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", address(this), to, tokenId); } (bool success,) = address(assetAddr).call(data); require(success); } function transferFromERC721(address assetAddr, uint256 tokenId) internal virtual { address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d; address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; bytes memory data; if (assetAddr == kitties) { // Cryptokitties. data = abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), tokenId); } else if (assetAddr == punks) { // CryptoPunks. // Fix here for frontrun attack. Added in v1.0.2. bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId); (bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress); (address owner) = abi.decode(result, (address)); require(checkSuccess && owner == msg.sender, "Not the owner"); data = abi.encodeWithSignature("buyPunk(uint256)", tokenId); } else { // Default. data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", msg.sender, address(this), tokenId); } (bool success, bytes memory resultData) = address(assetAddr).call(data); require(success, string(resultData)); } function getRandomTokenIdFromVault() internal virtual returns (uint256) { uint256 randomIndex = uint256( keccak256( abi.encodePacked( blockhash(block.number - 1), randNonce, block.coinbase, block.difficulty, block.timestamp ) ) ) % holdings.length(); randNonce += 1; return holdings.at(randomIndex); } function onlyPrivileged() internal view { if (manager == address(0)) { require(msg.sender == owner(), "Not owner"); } else { require(msg.sender == manager, "Not manager"); } } function onlyOwnerIfPaused(uint256 lockId) internal view { require(!vaultFactory.isLocked(lockId) || msg.sender == owner(), "Paused"); } }
Do not charge fees if the zap contract is calling Added in v1.0.3. Changed to mapping in v1.0.5. Mint fees directly to the distributor and distribute. Changed to a _transfer() in v1.0.3.
function _chargeAndDistributeFees(address user, uint256 amount) internal virtual { if (vaultFactory.excludedFromFees(msg.sender)) { return; } if (amount > 0) { address feeDistributor = vaultFactory.feeDistributor(); _transfer(user, feeDistributor, amount); INFTXFeeDistributor(feeDistributor).distribute(vaultId); } }
305,642
[ 1, 3244, 486, 13765, 1656, 281, 309, 326, 11419, 6835, 353, 4440, 25808, 316, 331, 21, 18, 20, 18, 23, 18, 27707, 358, 2874, 316, 331, 21, 18, 20, 18, 25, 18, 490, 474, 1656, 281, 5122, 358, 326, 1015, 19293, 471, 25722, 18, 27707, 358, 279, 389, 13866, 1435, 316, 331, 21, 18, 20, 18, 23, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 16385, 1876, 1669, 887, 2954, 281, 12, 2867, 729, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 309, 261, 26983, 1733, 18, 24602, 1265, 2954, 281, 12, 3576, 18, 15330, 3719, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 540, 203, 3639, 309, 261, 8949, 405, 374, 13, 288, 203, 5411, 1758, 14036, 1669, 19293, 273, 9229, 1733, 18, 21386, 1669, 19293, 5621, 203, 5411, 389, 13866, 12, 1355, 16, 14036, 1669, 19293, 16, 3844, 1769, 203, 5411, 2120, 4464, 60, 14667, 1669, 19293, 12, 21386, 1669, 19293, 2934, 2251, 887, 12, 26983, 548, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; /// @title BRZ token Bridge /// @author Solange Gueiros // Inpired on // https://github.com/rsksmart/tokenbridge/blob/master/bridge/contracts/Bridge.sol // https://github.com/DistributedCollective/Bridge-SC/blob/master/sovryn-token-bridge/bridge/contracts/Bridge_v3.sol // AccessControl.sol : https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/access/AccessControl.sol // Pausable.sol : https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/security/Pausable.sol import "./ozeppelin/access/AccessControl.sol"; import "./ozeppelin/security/Pausable.sol"; import "./IBridge.sol"; struct BlockchainStruct { uint256 minTokenAmount; uint256 minBRZFee; // quoteETH_BRZ * gasAcceptTransfer * minGasPrice uint256 minGasPrice; // in Wei bool checkAddress; // to verify is an address is EVM compatible is this blockchain } /** * @dev BRZ token Bridge * * Author: Solange Gueiros * * Smart contract to cross the BRZ token between EVM compatible blockchains. * * The tokens are crossed by TransferoSwiss, the company that controls the issuance of BRZs. * * It uses [Open Zeppelin Contracts] * (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/) * */ contract Bridge is AccessControl, IBridge, Pausable { address private constant ZERO_ADDRESS = address(0); bytes32 private constant NULL_HASH = bytes32(0); bytes32 public constant MONITOR_ROLE = keccak256("MONITOR_ROLE"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); /** * @dev DECIMALPERCENT is the representation of 100% using (2) decimal places * 100.00 = percentage accuracy (2) to 100% */ uint256 public constant DECIMALPERCENT = 10000; IERC20 public token; uint256 public totalFeeReceivedBridge; // fee received per Bridge, not for transaction in other blockchain /** * @dev Fee percentage bridge. * * For each amount received in the bridge, a fee percentage is discounted. * This function returns this fee percentage bridge. * Include 2 decimal places. */ uint256 public feePercentageBridge; /** * Estimative for function acceptTransfer: 100000 wei, it can change in EVM cost updates * * It is used to calculate minBRZFee in destination, * which can not accept a BRZ fee less than minBRZFee (per blockchain). */ uint256 public gasAcceptTransfer; /** * @dev the quote of pair ETH / BRZ. * * (1 ETH = the amount of BRZ returned) * * in BRZ in minor unit (4 decimal places). * * It is used to calculate minBRZFee in destination * which can not accept a BRZ fee less than minBRZFee (per blockchain). * */ uint256 public quoteETH_BRZ; mapping(bytes32 => bool) public processed; mapping(string => uint256) private blockchainIndex; BlockchainStruct[] private blockchainInfo; string[] public blockchain; /** * @dev Function called only when the smart contract is deployed. * * Parameters: * - address tokenAddress - address of BRZ token used in this blockchain network * * Actions: * - the transaction's sender will be added in the DEFAULT_ADMIN_ROLE. * - the token will be defined by the parameter tokenAddress * - the feePercentageBridge default value is be setted in 10, which means 0.1% */ constructor(address tokenAddress) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); token = IERC20(tokenAddress); feePercentageBridge = 10; //0.1% gasAcceptTransfer = 100000; //Estimative function acceptTransfer: 100000 wei } /** * @dev Modifier which verifies if the caller is an owner, * it means he has the role `DEFAULT_ADMIN_ROLE`. * * The role `DEFAULT_ADMIN_ROLE` is defined by Open Zeppelin's AccessControl smart contract. * * By default (setted in the constructor) the account which deployed this smart contract is in this role. * * This owner can add / remove other owners. */ modifier onlyOwner() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "not owner"); _; } /** * @dev Modifier which verifies if the caller is a monitor, * it means he has the role `MONITOR_ROLE`. * * Role MONITOR are referred to its `bytes32` identifier, * defined in the `public constant` called MONITOR_ROLE. * It should be exposed in the external API and be unique. * * Role MONITOR is used to manage the permissions of monitor's addresses. */ modifier onlyMonitor() { require(hasRole(MONITOR_ROLE, _msgSender()), "not monitor"); _; } /** * @dev Modifier which verifies if the caller is a monitor, * it means he has the role `ADMIN_ROLE`. * * Role ADMIN are referred to its `bytes32` identifier, * defined in the `public constant` called ADMIN_ROLE. * It should be exposed in the external API and be unique. * * Role ADMIN is used to manage the permissions for update minimum fee per blockchain. */ modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, _msgSender()), "not admin"); _; } /** * @dev Function which returns the bridge's version. * * This is a fixed value define in source code. * * Parameters: none * * Returns: string */ function version() external pure override returns (string memory) { return "v0"; } /** * @dev Private function to compare two strings * and returns `true` if the strings are equal, * otherwise it returns false. * * Parameters: stringA, stringB * * Returns: bool */ function compareStrings(string memory a, string memory b) private pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } /** * @dev This function starts the process of crossing tokens in the Bridge. * * > Any account / person can call it! * * Can not be called if the Bridge is paused. * * Parameters: * - amount - gross amount of tokens to be crossed. * - The Bridge fee will be deducted from this amount. * - transactionFee - array with the fees: * - transactionFee[0] - fee in BRL - this fee will be added to amount transfered from caller's account. * - transactionFee[1] - gas price for fee in destiny currency(minor unit) - this information will be * used in the destination Blockchain, * by the monitor who will create the transaction and send using this fee defined here. * - toBlockchain - the amount will be sent to this blockchain. * - toAddress - the amount will be sent to this address. It can be diferent from caller's address. * This is a string because some blockchain could not have the same pattern from Ethereum / RSK / BSC. * * Returns: bool - true if it is sucessful. * * > Before call this function, the caller MUST have called function `approve` in BRZ token, * > allowing the bridge's smart contract address to use the BRZ tokens, * > calling the function `transferFrom`. * * References: * * ERC-20 tokens approve and transferFrom pattern: * [eip-20#transferfrom](https://eips.ethereum.org/EIPS/eip-20#transferfrom) * * Requirements: * - fee in BRZ (transactionFee[0]) must be at least (BRZFactorFee[blockchainName] * minGasPrice[toBlockchain]). * - gasPrice (transactionFee[1]) in destiny blockchain (minor unit) greater than minGasPrice in toBlockchain. * - toBlockchain exists. * - toAddress is not an empty string. * - amount must be greater than minTokenAmount in toBlockchain. * - amount greater than zero. * * Actions: * - add the blockchain fee in BRZ to amount in BRZ, in totalAmount. * - calculate bridge's fee using the original amount to be sent. * - discount bridge's fee from the original amount, in amountMinusFees. * - add bridge's fee to `totalFeeReceivedBridge`, a variable to store all the fees received by the bridge. * - BRZ transfer totalAmount from the caller's address to bridge address. * - emit `CrossRequest` event, with the parameters: * - from - address of the caller's function. * - amount - the net amount to be transfered in the destination blockchain. * - toFee - the gas price fee, which must be used to send the transfer transaction in the destination blockchain. * - toAddress - string representing the address which will receive the tokens. * - toBlockchain - the destination blockchain. * * > The `CrossRequest` event is very important because it must be listened by the monitor, * an external program which will * send the transaction on the destination blockchain. * * #### More info about fees * * - Blockchain / transaction fee in BRL (transactionFee[0]) * It will be transfered from user's account, * along with the amount he would like to receive in the account. * * This will be spent in `toBlockchain`. * Does not depend of amount, but of destination blockchain. * * It must be at least the minBRZFee per blockchain. * * It is used in the function acceptTransfer, * which can not accept a BRZ fee less than minBRZFee (per blockchain). * * - gas price (transactionFee[1]) * It must be at least the minGasPrice per blockchain. * * - Bridge Fee - it is deducted from the requested amount. * It is a percentage of the requested amount. * Cannot include the transaction fee in order to be calculated. * */ function receiveTokens( uint256 amount, uint256[2] memory transactionFee, string memory toBlockchain, string memory toAddress ) external override whenNotPaused returns (bool) { require(existsBlockchain(toBlockchain), "toBlockchain not exists"); require(!compareStrings(toAddress, ""), "toAddress is null"); uint256 index = blockchainIndex[toBlockchain] - 1; require( transactionFee[0] >= blockchainInfo[index].minBRZFee, "feeBRZ is less than minimum" ); require( transactionFee[1] >= blockchainInfo[index].minGasPrice, "gasPrice is less than minimum" ); require(amount > 0, "amount is 0"); require( amount >= blockchainInfo[index].minTokenAmount, "amount is less than minimum" ); if (blockchainInfo[index].checkAddress) { require(bytes(toAddress).length == 42, "invalid destination address"); } //The total amount is the amount desired plus the blockchain fee to destination, in the token unit uint256 totalAmount = amount + transactionFee[0]; //Bridge fee or service fee uint256 bridgeFee = (amount * feePercentageBridge) / DECIMALPERCENT; uint256 amountMinusFees = amount - bridgeFee; totalFeeReceivedBridge += bridgeFee; //This is the message for Monitor off-chain manage the transaction and send the tokens on the other Blockchain emit CrossRequest( _msgSender(), amountMinusFees, transactionFee[1], toAddress, toBlockchain ); //Transfer the tokens on IERC20, they should be already approved for the bridge Address to use them token.transferFrom(_msgSender(), address(this), totalAmount); return true; } /** * @dev This function calculate a transaction id hash. * * Any person can call it. * * Parameters: * - hashes - from transaction in the origin blockchain: * - blockHash - hash of the block where was the transaction `receiveTokens` * - transactionHash - hash of the transaction `receiveTokens` with the event `CrossRequest`. * - receiver - the address which will receive the tokens. * - amount - the net amount to be transfered. * - logIndex - the index of the event `CrossRequest` in the logs of transaction. * - sender - address who sent the transaction `receiveTokens`, it is a string to be compatible with any blockchain. * * Returns: a bytes32 hash of all the information sent. * * Notes: * It did not use origin blockchain and sender address * because the possibility of having the same origin transaction from different blockchain source is minimal. * * It is a point to be evaluated in an audit. * */ function getTransactionId( bytes32[2] calldata hashes, //blockHash, transactionHash address receiver, uint256 amount, uint32 logIndex ) public pure override returns (bytes32) { return keccak256( abi.encodePacked(hashes[0], hashes[1], receiver, amount, logIndex) ); } /** * @dev This function update the variable processed for a transaction * * > Only monitor can call it! * * This variable is a public mapping. * * Each bytes32 which represents a Transaction Id has his boolen value stored. * */ function _processTransaction( bytes32[2] calldata hashes, //blockHash, transactionHash address receiver, uint256 amount, uint32 logIndex ) private { bytes32 transactionId = getTransactionId( hashes, receiver, amount, logIndex ); require(!processed[transactionId], "processed"); processed[transactionId] = true; } /** * @dev This function transfer tokens from the the internal balance of bridge smart contract * to the internal balance of the destination address. * * The token.balanceOf(bridgeAddress) must always be greather than or equal the total amount to be claimed by users, * as there may be tokens not yet claimed. * * Can not be called if the Bridge is paused. * * > Only monitor can call it! * */ function _sendToken(address to, uint256 amount) private returns (bool) { require(token.balanceOf(address(this)) >= amount, "insufficient balance"); token.transfer(to, amount); return true; } /** * @dev This function accept the cross of token, * which means it is called in the destination blockchain, * who will send the tokens accepted to be crossed. * * > Only monitor can call it! * * Can not be called if the Bridge is paused. * * Parameters: * - receiver - the address which will receive the tokens. * - amount - the net amount to be transfered. * - sender - string representing the address of the token's sender. * - fromBlockchain - the origin blockchain. * - hashes - from transaction in the origin blockchain: * - blockHash - hash of the block where was the transaction `receiveTokens`. * - transactionHash - hash of the transaction `receiveTokens` with the event `CrossRequest`. * - logIndex - the index of the event `CrossRequest` in the transaction logs. * * Returns: bool - true if it is sucessful * * Requirements: * - receiver is not a zero address. * - amount greater than zero. * - sender is not an empty string. * - fromBlockchain exists. * - blockHash is not null hash. * - transactionHash is not hash. * * Actions: * - processTransaction: * - getTransactionId * - verify if the transactionId was already processed * - update the status processed for transactionId * - sendToken: * - check if the bridge has in his balance at least the amount required to do the transfer * - transfer the amount tokens to destination address * */ function acceptTransfer( address receiver, uint256 amount, string calldata fromBlockchain, bytes32[2] calldata hashes, //blockHash, transactionHash uint32 logIndex ) external override onlyMonitor whenNotPaused returns (bool) { require(receiver != ZERO_ADDRESS, "receiver is zero"); require(amount > 0, "amount is 0"); require(existsBlockchain(fromBlockchain), "fromBlockchain not exists"); require(hashes[0] != NULL_HASH, "blockHash is null"); require(hashes[1] != NULL_HASH, "transactionHash is null"); _processTransaction(hashes, receiver, amount, logIndex); _sendToken(receiver, amount); return true; } /** * @dev Returns token balance in bridge. * * Parameters: none * * Returns: integer amount of tokens in bridge * */ function getTokenBalance() external view override returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Withdraw tokens from bridge * * Only owner can call it. * * Can be called even if the Bridge is paused, * because can happens a problem and it is necessary to withdraw tokens, * maybe to create a new version of bridge, for example. * * The tokens only can be sent to the caller's function. * * Parameters: integer amount of tokens * * Returns: true if it is successful * * Requirements: * - amount less or equal balance of tokens in bridge. * */ function withdrawToken(uint256 amount) external onlyOwner returns (bool) { require(amount <= token.balanceOf(address(this)), "insuficient balance"); token.transfer(_msgSender(), amount); return true; } /** * @dev This function add an address in the `MONITOR_ROLE`. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: address of monitor to be added * * Returns: bool - true if it is sucessful * */ function addMonitor(address account) external onlyOwner whenNotPaused returns (bool) { require(!hasRole(ADMIN_ROLE, account), "is admin"); grantRole(MONITOR_ROLE, account); return true; } /** * @dev This function excludes an address in the `MONITOR_ROLE`. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: address of monitor to be excluded * * Returns: bool - true if it is sucessful * */ function delMonitor(address account) external onlyOwner whenNotPaused returns (bool) { //Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE revokeRole(MONITOR_ROLE, account); return true; } /** * @dev This function add an address in the `ADMIN_ROLE`. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: address of admin to be added * * Returns: bool - true if it is sucessful * */ function addAdmin(address account) external onlyOwner whenNotPaused returns (bool) { require(!hasRole(MONITOR_ROLE, account), "is monitor"); grantRole(ADMIN_ROLE, account); return true; } /** * @dev This function excludes an address in the `ADMIN_ROLE`. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: address of admin to be excluded * * Returns: bool - true if it is sucessful * */ function delAdmin(address account) external onlyOwner whenNotPaused returns (bool) { //Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE revokeRole(ADMIN_ROLE, account); return true; } /** * @dev This function allows a user to renounce a role * * Parameters: bytes32 role, address account * * Returns: none * * Requirements: * * - An owner can not renounce the role DEFAULT_ADMIN_ROLE. * - Can only renounce roles for your own account. * */ function renounceRole(bytes32 role, address account) public virtual override { require(role != DEFAULT_ADMIN_ROLE, "can not renounce role owner"); require(account == _msgSender(), "can only renounce roles for self"); super.renounceRole(role, account); } /** * @dev This function allows to revoke a role * * Parameters: bytes32 role, address account * * Returns: none * * Requirements: * * - An owner can not revoke yourself in the role DEFAULT_ADMIN_ROLE. * */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { if (role == DEFAULT_ADMIN_ROLE) { require(account != _msgSender(), "can not revoke yourself in role owner"); } super.revokeRole(role, account); } /** * @dev This function update the minimum blockchain fee - gas price - in the minor unit. * * It is an internal function, called when quoteETH_BRZ, gasAcceptTransfer * * Returns: bool - true if it is sucessful * * Emit the event `MinBRZFeeChanged(blockchain, oldFee, newFee)`. * */ function _updateMinBRZFee() internal returns (bool) { for (uint8 i = 0; i < blockchainInfo.length; i++) { if (blockchainInfo[i].minGasPrice > 0) { uint256 newFee = (gasAcceptTransfer * blockchainInfo[i].minGasPrice * quoteETH_BRZ) / (1 ether); emit MinBRZFeeChanged( blockchain[i], blockchainInfo[i].minBRZFee, newFee ); blockchainInfo[i].minBRZFee = newFee; } } return true; } /** * @dev This function update quote of pair ETH / BRZ. * * (1 ETH = the amount of BRZ defined) * * Only admin can call it. * * Each time quoteETH_BRZ is updated, the MinBRZFee is updated too. * * Parameters: integer, the new quote * * Returns: bool - true if it is sucessful * * Emit the event `QuoteETH_BRZChanged(oldValue, newValue)`. * */ function setQuoteETH_BRZ(uint256 newValue) public onlyAdmin returns (bool) { emit QuoteETH_BRZChanged(quoteETH_BRZ, newValue); quoteETH_BRZ = newValue; require(_updateMinBRZFee(), "updateMinBRZFee error"); return true; } /** * @dev Returns the minimum gas price to cross tokens. * * The function acceptTransfer can not accept less than the minimum gas price per blockchain. * * Parameters: string, blockchain name * * Returns: integer * */ function getMinGasPrice(string memory blockchainName) external view override returns (uint256) { return blockchainInfo[blockchainIndex[blockchainName] - 1].minGasPrice; } /** * @dev This function update the minimum blockchain fee - gas price - in the minor unit. * * Each time setMinGasPrice is updated, the MinBRZFee is updated too. * * Only admin can call it. * * Can not be called if the Bridge is paused. * * Parameters: integer, the new fee * * Returns: bool - true if it is sucessful * * Requirements: * - blockchain must exists. * * Emit the event `MinGasPriceChanged(blockchain, oldFee, newFee)`. * */ function setMinGasPrice(string memory blockchainName, uint256 newFee) public onlyAdmin whenNotPaused returns (bool) { require(existsBlockchain(blockchainName), "blockchain not exists"); uint256 index = blockchainIndex[blockchainName] - 1; emit MinGasPriceChanged( blockchainName, blockchainInfo[index].minGasPrice, newFee ); blockchainInfo[index].minGasPrice = newFee; blockchainInfo[index].minBRZFee = (gasAcceptTransfer * newFee * quoteETH_BRZ) / (1 ether); return true; } /** * @dev Returns the minimum destination blockchain fee in BRZ, * in minor unit (4 decimal places) * * It is updated when one of these itens be updated: * - gasAcceptTransfer * - quoteETH_BRZ * - minGasPrice per Blockchain * * It is used in the function acceptTransfer, * which can not accept a BRZ fee less than minBRZFee (per blockchain). * * Parameters: string, blockchain name * * Returns: integer * */ function getMinBRZFee(string memory blockchainName) external view override returns (uint256) { return blockchainInfo[blockchainIndex[blockchainName] - 1].minBRZFee; } /** * @dev This function update the estimative of the gas amount used in function AcceptTransfer. * * It will only change if happen some EVM cost update. * * Only owner can call it. * * Each time gasAcceptTransfer is updated, the MinBRZFee is updated too. * * Parameters: integer, the new gas amount * * Returns: bool - true if it is sucessful * * Emit the event `GasAcceptTransferChanged(oldValue, newValue)`. * */ function setGasAcceptTransfer(uint256 newValue) public onlyOwner returns (bool) { emit GasAcceptTransferChanged(gasAcceptTransfer, newValue); gasAcceptTransfer = newValue; require(_updateMinBRZFee(), "updateMinBRZFee error"); return true; } /** * @dev Returns the minimum token amount to cross. * * The function acceptTransfer can not accpept less than the minimum per blockchain. * * Parameters: string, blockchain name * * Returns: integer * */ function getMinTokenAmount(string memory blockchainName) external view override returns (uint256) { return blockchainInfo[blockchainIndex[blockchainName] - 1].minTokenAmount; } /** * @dev This function update the minimum token's amount to be crossed. * * Only admin can call it. * * Can not be called if the Bridge is paused. * * Parameters: integer, the new amount * * Returns: bool - true if it is sucessful * * Requirements: * - blockchain must exists. * * Emit the event `MinTokenAmountChanged(blockchain, oldMinimumAmount, newMinimumAmount)`. * */ function setMinTokenAmount(string memory blockchainName, uint256 newAmount) public onlyAdmin whenNotPaused returns (bool) { require(existsBlockchain(blockchainName), "blockchain not exists"); uint256 index = blockchainIndex[blockchainName] - 1; emit MinTokenAmountChanged( blockchainName, blockchainInfo[index].minTokenAmount, newAmount ); blockchainInfo[index].minTokenAmount = newAmount; return true; } /** * @dev This function update the fee percentage bridge. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: integer, the new fee * * Returns: bool - true if it is sucessful * * Requirements: * - The new fee must be lower than 10% . * * Emit the event `FeePercentageBridgeChanged(oldFee, newFee)`. * */ function setFeePercentageBridge(uint256 newFee) external onlyOwner whenNotPaused returns (bool) { require(newFee < (DECIMALPERCENT / 10), "bigger than 10%"); emit FeePercentageBridgeChanged(feePercentageBridge, newFee); feePercentageBridge = newFee; return true; } /** * @dev This function update the BRZ token. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: address of new BRZ token * * Returns: bool - true if it is sucessful * * Requirements: * - The token address must not be a zero address. * * Emit the event `TokenChanged(tokenAddress)`. * */ function setToken(address tokenAddress) external onlyOwner whenNotPaused returns (bool) { require(tokenAddress != ZERO_ADDRESS, "zero address"); emit TokenChanged(tokenAddress); token = IERC20(tokenAddress); return true; } /** * @dev Returns if a blockchain is in the list of allowed blockchains to cross tokens using the bridge. * * Parameters: string name of blockchain * * Returns: boolean true if it is in the list * */ function existsBlockchain(string memory name) public view override returns (bool) { if (blockchainIndex[name] == 0) return false; else return true; } /** * @dev List of blockchains allowed to cross tokens using the bridge. * * Parameters: none * * Returns: an array of strings containing the blockchain list * */ function listBlockchain() external view override returns (string[] memory) { return blockchain; } /** * @dev This function include a new blockchain in the list of allowed blockchains used in the bridge. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: * - string name of blockchain to be added * - minGasPrice * - minTokenAmount * - check address EVM compatible * * Returns: index of blockchain. * * Important: * - index start in 1, not 0. * - index 0 means that the blockchain does no exist. * - index 1 means that it is the position 0 in the array. * * Requirements: * - blockchain not exists. * - onlyOwner * - whenNotPaused */ function addBlockchain( string memory name, uint256 minGasPrice, uint256 minTokenAmount, bool checkAddress ) external onlyOwner whenNotPaused returns (uint256) { require(!existsBlockchain(name), "blockchain exists"); BlockchainStruct memory b; b.minGasPrice = minGasPrice; b.minTokenAmount = minTokenAmount; b.minBRZFee = (gasAcceptTransfer * minGasPrice * quoteETH_BRZ) / (1 ether); b.checkAddress = checkAddress; blockchainInfo.push(b); blockchain.push(name); uint256 index = blockchainInfo.length; blockchainIndex[name] = index; return (index); } /** * @dev This function exclude a blockchain in the list of allowed blockchains used in the bridge. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: string name of blockchain to be excluded * * Returns: bool - true if it is sucessful * * Requirements: * - blockchain exists. * - there must be at least one blockchain left. * */ function delBlockchain(string memory name) external onlyOwner whenNotPaused returns (bool) { require(existsBlockchain(name), "blockchain not exists"); require(blockchainInfo.length > 1, "requires at least 1 blockchain"); uint256 indexToDelete = blockchainIndex[name] - 1; uint256 indexToMove = blockchainInfo.length - 1; //string memory keyToMove = blockchainInfo[indexToMove].name; string memory keyToMove = blockchain[indexToMove]; blockchainInfo[indexToDelete] = blockchainInfo[indexToMove]; blockchain[indexToDelete] = blockchain[indexToMove]; blockchainIndex[keyToMove] = indexToDelete + 1; delete blockchainIndex[name]; blockchainInfo.pop(); blockchain.pop(); return true; } /** * @dev This function pauses the bridge. * * Only owner can call it. * * Parameters: none * * Returns: none * * Requirements: * * - The contract must not be paused. * */ function pause() external onlyOwner { /** * @dev See {Pausable-_pause}. * * Requirements: * * - The contract must not be paused. */ _pause(); } /** * @dev This function unpauses the bridge. * * Only owner can call it. * * Parameters: none * * Returns: none * * Requirements: * * - The contract must be paused. */ function unpause() external onlyOwner { /** * @dev See {Pausable-_unpause}. * * Requirements: * * - The contract must be paused. */ _unpause(); } }
* @dev BRZ token Bridge Author: Solange Gueiros Smart contract to cross the BRZ token between EVM compatible blockchains. The tokens are crossed by TransferoSwiss, the company that controls the issuance of BRZs. It uses [Open Zeppelin Contracts]/
contract Bridge is AccessControl, IBridge, Pausable { address private constant ZERO_ADDRESS = address(0); bytes32 private constant NULL_HASH = bytes32(0); bytes32 public constant MONITOR_ROLE = keccak256("MONITOR_ROLE"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); uint256 public constant DECIMALPERCENT = 10000; IERC20 public token; uint256 public feePercentageBridge; uint256 public gasAcceptTransfer; uint256 public quoteETH_BRZ; mapping(bytes32 => bool) public processed; mapping(string => uint256) private blockchainIndex; BlockchainStruct[] private blockchainInfo; string[] public blockchain; constructor(address tokenAddress) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); token = IERC20(tokenAddress); } modifier onlyOwner() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "not owner"); _; } modifier onlyMonitor() { require(hasRole(MONITOR_ROLE, _msgSender()), "not monitor"); _; } modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, _msgSender()), "not admin"); _; } function version() external pure override returns (string memory) { return "v0"; } function compareStrings(string memory a, string memory b) private pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } function receiveTokens( uint256 amount, uint256[2] memory transactionFee, string memory toBlockchain, string memory toAddress ) external override whenNotPaused returns (bool) { require(existsBlockchain(toBlockchain), "toBlockchain not exists"); require(!compareStrings(toAddress, ""), "toAddress is null"); uint256 index = blockchainIndex[toBlockchain] - 1; require( transactionFee[0] >= blockchainInfo[index].minBRZFee, "feeBRZ is less than minimum" ); require( transactionFee[1] >= blockchainInfo[index].minGasPrice, "gasPrice is less than minimum" ); require(amount > 0, "amount is 0"); require( amount >= blockchainInfo[index].minTokenAmount, "amount is less than minimum" ); if (blockchainInfo[index].checkAddress) { require(bytes(toAddress).length == 42, "invalid destination address"); } uint256 amountMinusFees = amount - bridgeFee; totalFeeReceivedBridge += bridgeFee; _msgSender(), amountMinusFees, transactionFee[1], toAddress, toBlockchain ); return true; } function receiveTokens( uint256 amount, uint256[2] memory transactionFee, string memory toBlockchain, string memory toAddress ) external override whenNotPaused returns (bool) { require(existsBlockchain(toBlockchain), "toBlockchain not exists"); require(!compareStrings(toAddress, ""), "toAddress is null"); uint256 index = blockchainIndex[toBlockchain] - 1; require( transactionFee[0] >= blockchainInfo[index].minBRZFee, "feeBRZ is less than minimum" ); require( transactionFee[1] >= blockchainInfo[index].minGasPrice, "gasPrice is less than minimum" ); require(amount > 0, "amount is 0"); require( amount >= blockchainInfo[index].minTokenAmount, "amount is less than minimum" ); if (blockchainInfo[index].checkAddress) { require(bytes(toAddress).length == 42, "invalid destination address"); } uint256 amountMinusFees = amount - bridgeFee; totalFeeReceivedBridge += bridgeFee; _msgSender(), amountMinusFees, transactionFee[1], toAddress, toBlockchain ); return true; } uint256 totalAmount = amount + transactionFee[0]; uint256 bridgeFee = (amount * feePercentageBridge) / DECIMALPERCENT; emit CrossRequest( token.transferFrom(_msgSender(), address(this), totalAmount); function getTransactionId( address receiver, uint256 amount, uint32 logIndex ) public pure override returns (bytes32) { return keccak256( abi.encodePacked(hashes[0], hashes[1], receiver, amount, logIndex) ); } function _processTransaction( address receiver, uint256 amount, uint32 logIndex ) private { bytes32 transactionId = getTransactionId( hashes, receiver, amount, logIndex ); require(!processed[transactionId], "processed"); processed[transactionId] = true; } function _sendToken(address to, uint256 amount) private returns (bool) { require(token.balanceOf(address(this)) >= amount, "insufficient balance"); token.transfer(to, amount); return true; } function acceptTransfer( address receiver, uint256 amount, string calldata fromBlockchain, uint32 logIndex ) external override onlyMonitor whenNotPaused returns (bool) { require(receiver != ZERO_ADDRESS, "receiver is zero"); require(amount > 0, "amount is 0"); require(existsBlockchain(fromBlockchain), "fromBlockchain not exists"); require(hashes[0] != NULL_HASH, "blockHash is null"); require(hashes[1] != NULL_HASH, "transactionHash is null"); _processTransaction(hashes, receiver, amount, logIndex); _sendToken(receiver, amount); return true; } function getTokenBalance() external view override returns (uint256) { return token.balanceOf(address(this)); } function withdrawToken(uint256 amount) external onlyOwner returns (bool) { require(amount <= token.balanceOf(address(this)), "insuficient balance"); token.transfer(_msgSender(), amount); return true; } function addMonitor(address account) external onlyOwner whenNotPaused returns (bool) { require(!hasRole(ADMIN_ROLE, account), "is admin"); grantRole(MONITOR_ROLE, account); return true; } function delMonitor(address account) external onlyOwner whenNotPaused returns (bool) { revokeRole(MONITOR_ROLE, account); return true; } function addAdmin(address account) external onlyOwner whenNotPaused returns (bool) { require(!hasRole(MONITOR_ROLE, account), "is monitor"); grantRole(ADMIN_ROLE, account); return true; } function delAdmin(address account) external onlyOwner whenNotPaused returns (bool) { revokeRole(ADMIN_ROLE, account); return true; } function renounceRole(bytes32 role, address account) public virtual override { require(role != DEFAULT_ADMIN_ROLE, "can not renounce role owner"); require(account == _msgSender(), "can only renounce roles for self"); super.renounceRole(role, account); } function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { if (role == DEFAULT_ADMIN_ROLE) { require(account != _msgSender(), "can not revoke yourself in role owner"); } super.revokeRole(role, account); } function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { if (role == DEFAULT_ADMIN_ROLE) { require(account != _msgSender(), "can not revoke yourself in role owner"); } super.revokeRole(role, account); } function _updateMinBRZFee() internal returns (bool) { for (uint8 i = 0; i < blockchainInfo.length; i++) { if (blockchainInfo[i].minGasPrice > 0) { uint256 newFee = (gasAcceptTransfer * blockchainInfo[i].minGasPrice * quoteETH_BRZ) / (1 ether); emit MinBRZFeeChanged( blockchain[i], blockchainInfo[i].minBRZFee, newFee ); blockchainInfo[i].minBRZFee = newFee; } } return true; } function _updateMinBRZFee() internal returns (bool) { for (uint8 i = 0; i < blockchainInfo.length; i++) { if (blockchainInfo[i].minGasPrice > 0) { uint256 newFee = (gasAcceptTransfer * blockchainInfo[i].minGasPrice * quoteETH_BRZ) / (1 ether); emit MinBRZFeeChanged( blockchain[i], blockchainInfo[i].minBRZFee, newFee ); blockchainInfo[i].minBRZFee = newFee; } } return true; } function _updateMinBRZFee() internal returns (bool) { for (uint8 i = 0; i < blockchainInfo.length; i++) { if (blockchainInfo[i].minGasPrice > 0) { uint256 newFee = (gasAcceptTransfer * blockchainInfo[i].minGasPrice * quoteETH_BRZ) / (1 ether); emit MinBRZFeeChanged( blockchain[i], blockchainInfo[i].minBRZFee, newFee ); blockchainInfo[i].minBRZFee = newFee; } } return true; } function setQuoteETH_BRZ(uint256 newValue) public onlyAdmin returns (bool) { emit QuoteETH_BRZChanged(quoteETH_BRZ, newValue); quoteETH_BRZ = newValue; require(_updateMinBRZFee(), "updateMinBRZFee error"); return true; } function getMinGasPrice(string memory blockchainName) external view override returns (uint256) { return blockchainInfo[blockchainIndex[blockchainName] - 1].minGasPrice; } function setMinGasPrice(string memory blockchainName, uint256 newFee) public onlyAdmin whenNotPaused returns (bool) { require(existsBlockchain(blockchainName), "blockchain not exists"); uint256 index = blockchainIndex[blockchainName] - 1; emit MinGasPriceChanged( blockchainName, blockchainInfo[index].minGasPrice, newFee ); blockchainInfo[index].minGasPrice = newFee; blockchainInfo[index].minBRZFee = (gasAcceptTransfer * newFee * quoteETH_BRZ) / (1 ether); return true; } function getMinBRZFee(string memory blockchainName) external view override returns (uint256) { return blockchainInfo[blockchainIndex[blockchainName] - 1].minBRZFee; } function setGasAcceptTransfer(uint256 newValue) public onlyOwner returns (bool) { emit GasAcceptTransferChanged(gasAcceptTransfer, newValue); gasAcceptTransfer = newValue; require(_updateMinBRZFee(), "updateMinBRZFee error"); return true; } function getMinTokenAmount(string memory blockchainName) external view override returns (uint256) { return blockchainInfo[blockchainIndex[blockchainName] - 1].minTokenAmount; } function setMinTokenAmount(string memory blockchainName, uint256 newAmount) public onlyAdmin whenNotPaused returns (bool) { require(existsBlockchain(blockchainName), "blockchain not exists"); uint256 index = blockchainIndex[blockchainName] - 1; emit MinTokenAmountChanged( blockchainName, blockchainInfo[index].minTokenAmount, newAmount ); blockchainInfo[index].minTokenAmount = newAmount; return true; } function setFeePercentageBridge(uint256 newFee) external onlyOwner whenNotPaused returns (bool) { require(newFee < (DECIMALPERCENT / 10), "bigger than 10%"); emit FeePercentageBridgeChanged(feePercentageBridge, newFee); feePercentageBridge = newFee; return true; } function setToken(address tokenAddress) external onlyOwner whenNotPaused returns (bool) { require(tokenAddress != ZERO_ADDRESS, "zero address"); emit TokenChanged(tokenAddress); token = IERC20(tokenAddress); return true; } function existsBlockchain(string memory name) public view override returns (bool) { if (blockchainIndex[name] == 0) return false; else return true; } function listBlockchain() external view override returns (string[] memory) { return blockchain; } function addBlockchain( string memory name, uint256 minGasPrice, uint256 minTokenAmount, bool checkAddress ) external onlyOwner whenNotPaused returns (uint256) { require(!existsBlockchain(name), "blockchain exists"); BlockchainStruct memory b; b.minGasPrice = minGasPrice; b.minTokenAmount = minTokenAmount; b.minBRZFee = (gasAcceptTransfer * minGasPrice * quoteETH_BRZ) / (1 ether); b.checkAddress = checkAddress; blockchainInfo.push(b); blockchain.push(name); uint256 index = blockchainInfo.length; blockchainIndex[name] = index; return (index); } function delBlockchain(string memory name) external onlyOwner whenNotPaused returns (bool) { require(existsBlockchain(name), "blockchain not exists"); require(blockchainInfo.length > 1, "requires at least 1 blockchain"); uint256 indexToDelete = blockchainIndex[name] - 1; uint256 indexToMove = blockchainInfo.length - 1; string memory keyToMove = blockchain[indexToMove]; blockchainInfo[indexToDelete] = blockchainInfo[indexToMove]; blockchain[indexToDelete] = blockchain[indexToMove]; blockchainIndex[keyToMove] = indexToDelete + 1; delete blockchainIndex[name]; blockchainInfo.pop(); blockchain.pop(); return true; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } }
12,927,568
[ 1, 7192, 62, 1147, 24219, 6712, 30, 348, 355, 726, 611, 344, 77, 6973, 19656, 6835, 358, 6828, 326, 22427, 62, 1147, 3086, 512, 7397, 7318, 1203, 23060, 18, 1021, 2430, 854, 30783, 730, 635, 12279, 83, 6050, 1054, 16, 326, 9395, 716, 11022, 326, 3385, 89, 1359, 434, 22427, 62, 87, 18, 2597, 4692, 306, 3678, 2285, 881, 84, 292, 267, 30131, 18537, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 24219, 353, 24349, 16, 467, 13691, 16, 21800, 16665, 288, 203, 225, 1758, 3238, 5381, 18449, 67, 15140, 273, 1758, 12, 20, 1769, 203, 225, 1731, 1578, 3238, 5381, 3206, 67, 15920, 273, 1731, 1578, 12, 20, 1769, 203, 225, 1731, 1578, 1071, 5381, 30215, 30153, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 17667, 30153, 67, 16256, 8863, 203, 225, 1731, 1578, 1071, 5381, 25969, 67, 16256, 273, 417, 24410, 581, 5034, 2932, 15468, 67, 16256, 8863, 203, 203, 225, 2254, 5034, 1071, 5381, 25429, 3194, 19666, 273, 12619, 31, 203, 203, 225, 467, 654, 39, 3462, 1071, 1147, 31, 203, 203, 225, 2254, 5034, 1071, 14036, 16397, 13691, 31, 203, 203, 225, 2254, 5034, 1071, 16189, 5933, 5912, 31, 203, 203, 225, 2254, 5034, 1071, 3862, 1584, 44, 67, 7192, 62, 31, 203, 203, 225, 2874, 12, 3890, 1578, 516, 1426, 13, 1071, 5204, 31, 203, 225, 2874, 12, 1080, 516, 2254, 5034, 13, 3238, 16766, 1016, 31, 203, 225, 3914, 5639, 3823, 8526, 3238, 16766, 966, 31, 203, 225, 533, 8526, 1071, 16766, 31, 203, 203, 225, 3885, 12, 2867, 1147, 1887, 13, 288, 203, 565, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 565, 1147, 273, 467, 654, 39, 3462, 12, 2316, 1887, 1769, 203, 225, 289, 203, 203, 225, 9606, 1338, 5541, 1435, 288, 203, 565, 2583, 12, 5332, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 1435, 3631, 315, 902, 3410, 8863, 203, 565, 389, 31, 203, 2 ]
./full_match/1/0x54F2F2146904d536d05Ce81C3B4daEf1a843d3F7/sources/coin.sol
* @dev Initializes the contract setting the deployer as the initial owner./
constructor () { _owner = 0x7a6345Ad5dC3001dD5A5c06BeEb4935e834fC02E emit OwnershipTransferred(address(0), _owner); }
16,447,992
[ 1, 9685, 326, 6835, 3637, 326, 7286, 264, 487, 326, 2172, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 288, 203, 3639, 389, 8443, 273, 374, 92, 27, 69, 4449, 7950, 1871, 25, 72, 39, 23, 11664, 72, 40, 25, 37, 25, 71, 7677, 1919, 41, 70, 7616, 4763, 73, 28, 5026, 74, 39, 3103, 41, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.6; contract XGoldContract047 { address private creator; string private welcome = "The Blockchain Looks Corny."; /* Amount of blocks */ uint public amountOfBlocks; /* Block */ struct Block { address owner; uint number; string state; } /* blocks */ mapping (uint => Block) public blocks; Block[] public arrayBlocks; /* Get total amount of blocks */ function getTotoalAmountOfBlocks() constant returns (uint) { return amountOfBlocks; } /* Get owner of block */ function getOwnerOfBlock(uint blockNumber) constant returns (address) { address owner; for(uint i = 0;i<amountOfBlocks+1;i++){ if(blocks[i].number == blockNumber){ return blocks[i].owner; } } } /* Get blocks of sender */ function getBlocksOfSender() constant returns (uint[]) { uint[] list; for(uint i = 0;i<amountOfBlocks+1;i++){ if(blocks[i].owner == msg.sender){ list.push(blocks[i].number); } } return list; } /* Is block for sale */ function isBlockForSale(uint blockNumber) constant returns (bool){ for(uint i = 0;i<amountOfBlocks+1;i++){ if(blocks[i].number == blockNumber){ return false; } } return true; } /* Buy gold block */ function buyGoldBlock(uint blockNumber) payable public returns(bool){ if(!isBlockForSale(blockNumber)) return false; amountOfBlocks = amountOfBlocks+1; blocks[amountOfBlocks] = Block(msg.sender, blockNumber, "gold"); arrayBlocks.push(Block(msg.sender, blockNumber, "gold")); return true; } /* Buy nebula block */ function buyNebulaBlock(uint blockNumber) payable public returns(bool){ if(!isBlockForSale(blockNumber)) return false; amountOfBlocks = amountOfBlocks+1; blocks[amountOfBlocks] = Block(msg.sender, blockNumber, "nebula"); arrayBlocks.push(Block(msg.sender, blockNumber, "nebula")); return true; } /* Is sender owner of block */ function isSenderOwnerOfBlock(uint blockNumber) constant returns (bool) { for(uint i = 0;i<amountOfBlocks+1;i++){ if(blocks[i].number == blockNumber){ if(blocks[i].owner == msg.sender){ return true; } return false; } } } /* Sell block */ function sellBlock(uint blockNumber) payable public returns(bool){ if(!isSenderOwnerOfBlock(blockNumber)) return; for(uint i = 0;i<amountOfBlocks+1;i++){ if(blocks[i].number == blockNumber){ blocks[i].owner = 0x0; blocks[i].state = 'available'; //Send money back //Check if sending back was successful if (!msg.sender.send(0.001 ether)) throw; amountOfBlocks--; return true; } return false; } } /* Get welcome */ function getWelcome() constant returns(string){ return welcome; } /* Get balance */ function getTotalBalance() constant returns(uint){ return this.balance; } /* Kill */ function kill(){ if(msg.sender == creator){ suicide(creator); } } }
Send money backCheck if sending back was successful
function sellBlock(uint blockNumber) payable public returns(bool){ if(!isSenderOwnerOfBlock(blockNumber)) return; for(uint i = 0;i<amountOfBlocks+1;i++){ if(blocks[i].number == blockNumber){ blocks[i].owner = 0x0; blocks[i].state = 'available'; if (!msg.sender.send(0.001 ether)) throw; amountOfBlocks--; return true; } return false; } }
6,461,198
[ 1, 3826, 15601, 1473, 1564, 309, 5431, 1473, 1703, 6873, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 357, 80, 1768, 12, 11890, 1203, 1854, 13, 8843, 429, 1071, 1135, 12, 6430, 15329, 203, 203, 3639, 309, 12, 5, 291, 12021, 5541, 951, 1768, 12, 2629, 1854, 3719, 327, 31, 203, 2398, 203, 2398, 203, 3639, 364, 12, 11890, 277, 273, 374, 31, 77, 32, 8949, 951, 6450, 15, 21, 31, 77, 27245, 95, 203, 2398, 203, 5411, 309, 12, 7996, 63, 77, 8009, 2696, 422, 1203, 1854, 15329, 203, 1171, 203, 7734, 4398, 63, 77, 8009, 8443, 273, 374, 92, 20, 31, 203, 7734, 4398, 63, 77, 8009, 2019, 273, 296, 5699, 13506, 203, 1171, 203, 1171, 203, 7734, 309, 16051, 3576, 18, 15330, 18, 4661, 12, 20, 18, 11664, 225, 2437, 3719, 203, 7734, 604, 31, 203, 1171, 203, 7734, 3844, 951, 6450, 413, 31, 203, 7734, 327, 638, 31, 203, 1171, 203, 5411, 289, 203, 2398, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 2398, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "./MELDBaseSale.sol"; contract MELDPublicSale is MELDBaseSale { using SafeMathUpgradeable for uint256; // Calculate token vesting // Unlocked @TGE 40% // The rest are released once a month, Aufgeteilt in 3 Monate function vesting(uint256 tokens, address beneficiary) internal override { uint vestingMonth = 3; uint256 vestingPeriod = 30 days; uint unlockedTGEPercent = 40; uint256 unlockedTGETokens = tokens.mul(unlockedTGEPercent).div(100); uint256 lockedTokens = tokens.mul(100 - unlockedTGEPercent).div(100); uint256 unlockedTokensEveryMonth = lockedTokens.div(vestingMonth); for (uint month = 1; month <= vestingMonth; month++) { uint256 releaseTime = block.timestamp + vestingPeriod * month; MELDVestingContract.addVesting(beneficiary, releaseTime, unlockedTokensEveryMonth); } // Immediately transfer the unlock @TGE portion to the beneficiary MELDToken.transfer(beneficiary, unlockedTGETokens); // Take over the locked front to the Vesting Contract MELDToken.transfer(address(MELDVestingContract), lockedTokens); } }
Calculate token vesting Unlocked @TGE 40% The rest are released once a month, Aufgeteilt in 3 Monate
contract MELDPublicSale is MELDBaseSale { using SafeMathUpgradeable for uint256; pragma solidity ^0.8.2; function vesting(uint256 tokens, address beneficiary) internal override { uint vestingMonth = 3; uint256 vestingPeriod = 30 days; uint unlockedTGEPercent = 40; uint256 unlockedTGETokens = tokens.mul(unlockedTGEPercent).div(100); uint256 lockedTokens = tokens.mul(100 - unlockedTGEPercent).div(100); uint256 unlockedTokensEveryMonth = lockedTokens.div(vestingMonth); for (uint month = 1; month <= vestingMonth; month++) { uint256 releaseTime = block.timestamp + vestingPeriod * month; MELDVestingContract.addVesting(beneficiary, releaseTime, unlockedTokensEveryMonth); } } function vesting(uint256 tokens, address beneficiary) internal override { uint vestingMonth = 3; uint256 vestingPeriod = 30 days; uint unlockedTGEPercent = 40; uint256 unlockedTGETokens = tokens.mul(unlockedTGEPercent).div(100); uint256 lockedTokens = tokens.mul(100 - unlockedTGEPercent).div(100); uint256 unlockedTokensEveryMonth = lockedTokens.div(vestingMonth); for (uint month = 1; month <= vestingMonth; month++) { uint256 releaseTime = block.timestamp + vestingPeriod * month; MELDVestingContract.addVesting(beneficiary, releaseTime, unlockedTokensEveryMonth); } } MELDToken.transfer(beneficiary, unlockedTGETokens); MELDToken.transfer(address(MELDVestingContract), lockedTokens); }
1,020,589
[ 1, 8695, 1147, 331, 10100, 3967, 329, 632, 56, 7113, 8063, 9, 1021, 3127, 854, 15976, 3647, 279, 3138, 16, 432, 696, 588, 73, 4526, 316, 890, 9041, 340, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 490, 5192, 4782, 30746, 353, 490, 5192, 2171, 30746, 288, 203, 565, 1450, 14060, 10477, 10784, 429, 364, 2254, 5034, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 22, 31, 203, 565, 445, 331, 10100, 12, 11890, 5034, 2430, 16, 1758, 27641, 74, 14463, 814, 13, 2713, 3849, 288, 203, 3639, 2254, 331, 10100, 5445, 273, 890, 31, 203, 3639, 2254, 5034, 331, 10100, 5027, 273, 5196, 4681, 31, 203, 3639, 2254, 25966, 56, 7113, 8410, 273, 8063, 31, 203, 203, 3639, 2254, 5034, 25966, 56, 3264, 3573, 273, 2430, 18, 16411, 12, 318, 15091, 56, 7113, 8410, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 8586, 5157, 273, 2430, 18, 16411, 12, 6625, 300, 25966, 56, 7113, 8410, 2934, 2892, 12, 6625, 1769, 203, 3639, 2254, 5034, 25966, 5157, 21465, 5445, 273, 8586, 5157, 18, 2892, 12, 90, 10100, 5445, 1769, 203, 3639, 364, 261, 11890, 3138, 273, 404, 31, 3138, 1648, 331, 10100, 5445, 31, 3138, 27245, 288, 203, 5411, 2254, 5034, 3992, 950, 273, 1203, 18, 5508, 397, 331, 10100, 5027, 380, 3138, 31, 203, 5411, 490, 5192, 58, 10100, 8924, 18, 1289, 58, 10100, 12, 70, 4009, 74, 14463, 814, 16, 3992, 950, 16, 25966, 5157, 21465, 5445, 1769, 203, 3639, 289, 203, 203, 203, 565, 289, 203, 565, 445, 331, 10100, 12, 11890, 5034, 2430, 16, 1758, 27641, 74, 14463, 814, 13, 2713, 3849, 288, 203, 3639, 2254, 331, 10100, 5445, 273, 890, 31, 203, 3639, 2254, 5034, 331, 10100, 5027, 273, 5196, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** * @dev TestGhostMarketERC721_V2 for upgrade. */ import "../contracts/ERC721PresetMinterPauserAutoIdUpgradeableCustom.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol"; contract TestGhostMarketERC721_V2 is Initializable, ERC721PresetMinterPauserAutoIdUpgradeableCustom, ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC165StorageUpgradeable { // struct for royalties fees struct Royalty { address payable recipient; uint256 value; } // tokenId => royalties array mapping(uint256 => Royalty[]) internal _royalties; // tokenId => locked content array mapping(uint256 => string) internal _lockedContent; // tokenId => locked content view counter array mapping(uint256 => uint256) internal _lockedContentViewTracker; // tokenId => attributes array mapping(uint256 => string) internal _metadataJson; // events event LockedContentViewed(address msgSender, uint256 tokenId, string lockedContent); event MintFeesWithdrawn(address feeWithdrawer, uint256 withdrawAmount); event MintFeesUpdated(address feeUpdater, uint256 newValue); event Minted(address toAddress, uint256 tokenId, string externalURI); event NewMintFeeIncremented(uint256 newValue); // mint fees balance uint256 internal _payedMintFeesBalance; // mint fees value uint256 internal _ghostmarketMintFees; /** * bytes4(keccak256(_INTERFACE_ID_ERC721_GHOSTMARKET)) == 0xee40ffc1 */ bytes4 private constant _INTERFACE_ID_ERC721_GHOSTMARKET = 0xee40ffc1; function initialize(string memory name, string memory symbol, string memory uri) public override initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC721Enumerable_init_unchained(); __ERC721Burnable_init_unchained(); __Pausable_init_unchained(); __ERC721Pausable_init_unchained(); __ERC721URIStorage_init_unchained(); __ERC721_init_unchained(name, symbol); __ERC721PresetMinterPauserAutoId_init_unchained(uri); __Ownable_init_unchained(); _registerInterface(_INTERFACE_ID_ERC721_GHOSTMARKET); } function getSomething() external pure returns (uint) { return 10; } function incrementMintingFee() external { _ghostmarketMintFees2 = _ghostmarketMintFees + 1; emit NewMintFeeIncremented(_ghostmarketMintFees2); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721PresetMinterPauserAutoIdUpgradeableCustom, ERC165StorageUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev set a NFT royalties fees & recipients * fee basis points 10000 = 100% */ function _saveRoyalties(uint256 tokenId, Royalty[] memory royalties) internal { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); for (uint256 i = 0; i < royalties.length; i++) { require(royalties[i].recipient != address(0x0), "Recipient should be present"); require(royalties[i].value > 0, "Royalties value should be positive"); require(royalties[i].value <= 5000, "Royalties value should not be more than 50%"); _royalties[tokenId].push(royalties[i]); } } /** * @dev set a NFT custom attributes to contract storage */ function _setMetadataJson(uint256 tokenId, string memory metadataJson) internal { _metadataJson[tokenId] = metadataJson; } /** * @dev set a NFT locked content as string */ function _setLockedContent(uint256 tokenId, string memory content) internal { _lockedContent[tokenId] = content; } /** * @dev check mint fees sent to contract * emits MintFeesPaid event if set */ function _checkMintFees() internal { if (_ghostmarketMintFees > 0) { require(msg.value == _ghostmarketMintFees, "Wrong fees value sent to GhostMarket for mint fees"); } if (msg.value > 0) { _payedMintFeesBalance += msg.value; } } /** * @dev increment a NFT locked content view tracker */ function _incrementCurrentLockedContentViewTracker(uint256 tokenId) internal { _lockedContentViewTracker[tokenId] = _lockedContentViewTracker[tokenId] + 1; } /** * @dev mint NFT, set royalties, set metadata json, set lockedcontent * emits Minted event */ function mintGhost(address to, Royalty[] memory royalties, string memory externalURI, string memory metadata, string memory lockedcontent) external payable nonReentrant { require(to != address(0x0), "to can't be empty"); require(keccak256(abi.encodePacked(externalURI)) != keccak256(abi.encodePacked("")), "externalURI can't be empty"); mint(to); uint256 tokenId = getLastTokenID(); if (royalties.length > 0) { _saveRoyalties(tokenId, royalties); } if (keccak256(abi.encodePacked(metadata)) != keccak256(abi.encodePacked(""))) { _setMetadataJson(tokenId, metadata); } if (keccak256(abi.encodePacked(lockedcontent)) != keccak256(abi.encodePacked(""))) { _setLockedContent(tokenId, lockedcontent); } _checkMintFees(); emit Minted(to, tokenId, externalURI); } /** * @dev withdraw contract balance * emits MintFeesWithdrawn event */ function withdraw(uint256 withdrawAmount) external onlyOwner { require(withdrawAmount > 0 && withdrawAmount <= _payedMintFeesBalance, "Withdraw amount should be greater then 0 and less then contract balance"); _payedMintFeesBalance -= withdrawAmount; (bool success, ) = msg.sender.call{value: withdrawAmount}(""); require(success, "Transfer failed."); emit MintFeesWithdrawn(msg.sender, withdrawAmount); } /** * @dev bulk burn NFT */ function burnBatch(uint256[] memory tokensId) external { for (uint256 i = 0; i < tokensId.length; i++) { burn(tokensId[i]); } } /** * @dev sets Ghostmarket mint fees as uint256 * emits MintFeesUpdated event */ function setGhostmarketMintFee(uint256 gmmf) external { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Caller must have admin role to set mint fees"); _ghostmarketMintFees = gmmf; emit MintFeesUpdated(msg.sender, _ghostmarketMintFees); } /** * @return get Ghostmarket mint fees */ function getGhostmarketMintFees() external view returns (uint256) { return _ghostmarketMintFees; } /** * @dev get locked content for a NFT * emits LockedContentViewed event */ function getLockedContent(uint256 tokenId) external { require(ownerOf(tokenId) == msg.sender, "Caller must be the owner of the NFT"); _incrementCurrentLockedContentViewTracker(tokenId); emit LockedContentViewed(msg.sender, tokenId, _lockedContent[tokenId]); } /** * @dev get a NFT current locked content view tracker */ function getCurrentLockedContentViewTracker(uint256 tokenId) external view returns (uint256) { return _lockedContentViewTracker[tokenId]; } /** * @dev get a NFT custom attributes */ function getMetadataJson(uint256 tokenId) external view returns (string memory) { return _metadataJson[tokenId]; } /** * @dev get a NFT royalties recipients */ function getRoyaltiesRecipients(uint256 tokenId) external view returns (address payable[] memory) { Royalty[] memory royalties = _royalties[tokenId]; address payable[] memory result = new address payable[](royalties.length); for (uint256 i = 0; i < royalties.length; i++) { result[i] = royalties[i].recipient; } return result; } /** * @dev get a NFT royalties fees * fee basis points 10000 = 100% */ function getRoyaltiesBps(uint256 tokenId) external view returns (uint256[] memory) { Royalty[] memory royalties = _royalties[tokenId]; uint256[] memory result = new uint256[](royalties.length); for (uint256 i = 0; i < royalties.length; i++) { result[i] = royalties[i].value; } return result; } uint256[50] private __gap; uint256 internal _ghostmarketMintFees2; }
* @dev get a NFT royalties recipients/
function getRoyaltiesRecipients(uint256 tokenId) external view returns (address payable[] memory) { Royalty[] memory royalties = _royalties[tokenId]; address payable[] memory result = new address payable[](royalties.length); for (uint256 i = 0; i < royalties.length; i++) { result[i] = royalties[i].recipient; } return result; }
1,777,567
[ 1, 588, 279, 423, 4464, 721, 93, 2390, 606, 12045, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 4170, 13372, 2390, 606, 22740, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 2867, 8843, 429, 8526, 3778, 13, 203, 565, 288, 203, 202, 202, 54, 13372, 15006, 8526, 3778, 721, 93, 2390, 606, 273, 389, 3800, 2390, 606, 63, 2316, 548, 15533, 203, 202, 202, 2867, 8843, 429, 8526, 3778, 563, 273, 394, 1758, 8843, 429, 8526, 12, 3800, 2390, 606, 18, 2469, 1769, 203, 202, 202, 1884, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 721, 93, 2390, 606, 18, 2469, 31, 277, 27245, 288, 203, 1082, 202, 2088, 63, 77, 65, 273, 721, 93, 2390, 606, 63, 77, 8009, 20367, 31, 203, 202, 202, 97, 203, 202, 202, 2463, 563, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/Context.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol 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; } } // File: ether-library/contracts/IERC20.sol pragma solidity >=0.4.0; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the erc20 token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: ether-library/contracts/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/StakingInitializable.sol pragma solidity 0.6.12; contract StakingInitializable is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The address of the staking factory address public STAKING_FACTORY; // Whether a limit is set for users bool public hasUserLimit; // Whether it is initialized bool public isInitialized; // Accrued token per share uint256 public accTokenPerShare; // The block number when reward ends. uint256 public endBlock; // The block number when reward starts. uint256 public startBlock; // The block number of the last pool update uint256 public lastRewardBlock; // The deposit fee uint16 public depositFee; // The withdraw fee when stake before the locked time uint16 public withdrawFee; // The withdraw lock period uint256 public lockPeriod; // The fee address address payable public feeAddress; // The pool limit (0 if none) uint256 public poolLimitPerUser; // reward tokens created per block. uint256 public rewardPerBlock; uint16 public constant MAX_DEPOSIT_FEE = 2000; uint16 public constant MAX_WITHDRAW_FEE = 2000; uint256 public constant MAX_LOCK_PERIOD = 30 days; uint256 public constant MAX_EMISSION_RATE = 10**7; // The precision factor uint256 public PRECISION_FACTOR; // The reward token IERC20 public rewardToken; // The staked token IERC20 public stakedToken; // Total supply of staked token uint256 public stakedSupply; // Info of each user that stakes tokens (stakedToken) mapping(address => UserInfo) public userInfo; struct UserInfo { uint256 amount; // How many staked tokens the user has provided uint256 rewardDebt; // Reward debt uint256 lastDepositedAt; // Last deposited time } event AdminTokenRecovery(address tokenRecovered, uint256 amount); event UserDeposited(address indexed user, uint256 amount); event EmergencyWithdrawn(address indexed user, uint256 amount); event EmergencyRewardWithdrawn(uint256 amount); event StartAndEndBlocksUpdated(uint256 startBlock, uint256 endBlock); event RewardPerBlockUpdated(uint256 oldValue, uint256 newValue); event DepositFeeUpdated(uint16 oldValue, uint16 newValue); event WithdrawFeeUpdated(uint16 oldValue, uint16 newValue); event LockPeriodUpdated(uint256 oldValue, uint256 newValue); event FeeAddressUpdated(address oldAddress, address newAddress); event PoolLimitUpdated(uint256 oldValue, uint256 newValue); event RewardsStopped(uint256 blockNumber); event UserWithdrawn(address indexed user, uint256 amount); constructor() public { STAKING_FACTORY = msg.sender; } /** * @notice Initialize the contract * @param _stakedToken: staked token address * @param _rewardToken: reward token address * @param _rewardPerBlock: reward per block (in rewardToken) * @param _startBlock: start block * @param _endBlock: end block * @param _poolLimitPerUser: pool limit per user in stakedToken (if any, else 0) * @param _depositFee: deposit fee * @param _withdrawFee: withdraw fee * @param _lockPeriod: lock period * @param _feeAddress: fee address * @param _admin: admin address with ownership */ function initialize( IERC20 _stakedToken, IERC20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock, uint256 _poolLimitPerUser, uint16 _depositFee, uint16 _withdrawFee, uint256 _lockPeriod, address payable _feeAddress, address _admin ) external { require(!isInitialized, "Already initialized"); require(msg.sender == STAKING_FACTORY, "Not factory"); require(_stakedToken.totalSupply() >= 0, "Invalid stake token"); require(_rewardToken.totalSupply() >= 0, "Invalid reward token"); require(_feeAddress != address(0), "Invalid zero address"); _stakedToken.balanceOf(address(this)); _rewardToken.balanceOf(address(this)); // require(_stakedToken != _rewardToken, "stakedToken must be different from rewardToken"); require(_startBlock > block.number, "startBlock cannot be in the past"); require( _startBlock < _endBlock, "startBlock must be lower than endBlock" ); // Make this contract initialized isInitialized = true; stakedToken = _stakedToken; rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; endBlock = _endBlock; require(_depositFee <= MAX_DEPOSIT_FEE, "Invalid deposit fee"); depositFee = _depositFee; require(_withdrawFee <= MAX_WITHDRAW_FEE, "Invalid withdraw fee"); withdrawFee = _withdrawFee; require(_lockPeriod <= MAX_LOCK_PERIOD, "Invalid lock period"); lockPeriod = _lockPeriod; feeAddress = _feeAddress; if (_poolLimitPerUser > 0) { hasUserLimit = true; poolLimitPerUser = _poolLimitPerUser; } uint256 decimalsRewardToken = uint256(rewardToken.decimals()); require(decimalsRewardToken < 30, "Must be inferior to 30"); PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken))); // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; // Transfer ownership to the admin address who becomes owner of the contract transferOwnership(_admin); } /* * @notice Deposit staked tokens and collect reward tokens (if any) * @param _amount: amount to withdraw (in rewardToken) */ function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; if (hasUserLimit) { require( _amount.add(user.amount) <= poolLimitPerUser, "User amount above limit" ); } _updatePool(); if (user.amount > 0) { uint256 pending = user .amount .mul(accTokenPerShare) .div(PRECISION_FACTOR) .sub(user.rewardDebt); if (pending > 0) { safeRewardTransfer(msg.sender, pending); } } if (_amount > 0) { uint256 balanceBefore = stakedToken.balanceOf(address(this)); stakedToken.safeTransferFrom(msg.sender, address(this), _amount); _amount = stakedToken.balanceOf(address(this)).sub(balanceBefore); uint256 feeAmount = 0; if (depositFee > 0) { feeAmount = _amount.mul(depositFee).div(10000); if (feeAmount > 0) { stakedToken.safeTransfer(feeAddress, feeAmount); } } user.amount = user.amount.add(_amount).sub(feeAmount); user.lastDepositedAt = block.timestamp; stakedSupply = stakedSupply.add(_amount).sub(feeAmount); } user.rewardDebt = user.amount.mul(accTokenPerShare).div( PRECISION_FACTOR ); emit UserDeposited(msg.sender, _amount); } /* * @notice Withdraw staked tokens and collect reward tokens * @param _amount: amount to withdraw (in rewardToken) */ function withdraw(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; require( stakedSupply >= _amount && user.amount >= _amount, "Amount to withdraw too high" ); _updatePool(); uint256 pending = user .amount .mul(accTokenPerShare) .div(PRECISION_FACTOR) .sub(user.rewardDebt); if (_amount > 0) { user.amount = user.amount.sub(_amount); stakedSupply = stakedSupply.sub(_amount); // Check if lock period passed if (user.lastDepositedAt.add(lockPeriod) > block.timestamp) { uint256 feeAmount = _amount.mul(withdrawFee).div(10000); if (feeAmount > 0) { _amount = _amount.sub(feeAmount); stakedToken.safeTransfer(feeAddress, feeAmount); } } if (_amount > 0) { stakedToken.safeTransfer(msg.sender, _amount); } } if (pending > 0) { safeRewardTransfer(msg.sender, pending); } user.rewardDebt = user.amount.mul(accTokenPerShare).div( PRECISION_FACTOR ); emit UserWithdrawn(msg.sender, _amount); } /** * @notice Safe reward transfer, just in case if rounding error causes pool to not have enough reward tokens. * @param _to receiver address * @param _amount amount to transfer * @return realAmount amount sent to the receiver */ function safeRewardTransfer(address _to, uint256 _amount) internal returns (uint256 realAmount) { uint256 rewardBalance = rewardToken.balanceOf(address(this)); if (_amount > 0 && rewardBalance > 0) { realAmount = _amount; // When there is not enough reward balance, just send available rewards if (realAmount > rewardBalance) { realAmount = rewardBalance; } // When staked token is same as reward token, rewarding amount should not occupy staked amount if ( address(stakedToken) != address(rewardToken) || stakedSupply.add(realAmount) <= rewardBalance ) { rewardToken.safeTransfer(_to, realAmount); } else if (stakedSupply < rewardBalance) { realAmount = rewardBalance.sub(stakedSupply); rewardToken.safeTransfer(_to, realAmount); } else { realAmount = 0; } } else { realAmount = 0; } return realAmount; } /** * @notice Withdraw staked tokens without caring about rewards rewards * @dev Needs to be for emergency. */ function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint256 amountToTransfer = user.amount; user.amount = 0; user.rewardDebt = 0; stakedSupply = stakedSupply.sub(amountToTransfer); if (amountToTransfer > 0) { stakedToken.safeTransfer(msg.sender, amountToTransfer); } emit EmergencyWithdrawn(msg.sender, amountToTransfer); } /** * @notice Withdraw all reward tokens * @dev Only callable by owner. Needs to be for emergency. */ function emergencyRewardWithdraw(uint256 _amount) external onlyOwner { require( startBlock > block.number || endBlock < block.number, "Not allowed to remove reward tokens while pool is live" ); safeRewardTransfer(msg.sender, _amount); emit EmergencyRewardWithdrawn(_amount); } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of tokens to withdraw * @dev This function is only callable by admin. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require( _tokenAddress != address(stakedToken), "Cannot be staked token" ); require( _tokenAddress != address(rewardToken), "Cannot be reward token" ); IERC20(_tokenAddress).safeTransfer(msg.sender, _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /* * @notice Stop rewards * @dev Only callable by owner */ function stopReward() external onlyOwner { require(startBlock < block.number, "Pool has not started"); require(block.number <= endBlock, "Pool has ended"); endBlock = block.number; emit RewardsStopped(block.number); } /* * @notice Update pool limit per user * @dev Only callable by owner. * @param _hasUserLimit: whether the limit remains forced * @param _poolLimitPerUser: new pool limit per user */ function updatePoolLimitPerUser( bool _hasUserLimit, uint256 _poolLimitPerUser ) external onlyOwner { require(hasUserLimit, "Must be set"); uint256 oldValue = poolLimitPerUser; if (_hasUserLimit) { require( _poolLimitPerUser > poolLimitPerUser, "New limit must be higher" ); poolLimitPerUser = _poolLimitPerUser; } else { hasUserLimit = _hasUserLimit; poolLimitPerUser = 0; } emit PoolLimitUpdated(oldValue, _poolLimitPerUser); } /* * @notice Update reward per block * @dev Only callable by owner. * @param _rewardPerBlock: the reward per block */ function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner { require(rewardPerBlock != _rewardPerBlock, "Same value alrady set"); uint256 rewardDecimals = uint256(rewardToken.decimals()); require( _rewardPerBlock <= MAX_EMISSION_RATE.mul(10**rewardDecimals), "Out of maximum emission rate" ); _updatePool(); emit RewardPerBlockUpdated(rewardPerBlock, _rewardPerBlock); rewardPerBlock = _rewardPerBlock; } /* * @notice Update deposit fee * @dev Only callable by owner. * @param _depositFee: the deposit fee */ function updateDepositFee(uint16 _depositFee) external onlyOwner { require(depositFee != _depositFee, "Same vaue already set"); require(_depositFee <= MAX_DEPOSIT_FEE, "Invalid deposit fee"); emit DepositFeeUpdated(depositFee, _depositFee); depositFee = _depositFee; } /* * @notice Update withdraw fee * @dev Only callable by owner. * @param _withdrawFee: the deposit fee */ function updateWithdrawFee(uint16 _withdrawFee) external onlyOwner { require(withdrawFee != _withdrawFee, "Same value already set"); require(_withdrawFee <= MAX_WITHDRAW_FEE, "Invalid withdraw fee"); emit WithdrawFeeUpdated(withdrawFee, _withdrawFee); withdrawFee = _withdrawFee; } /* * @notice Update withdraw lock period * @dev Only callable by owner. * @param _lockPeriod: the withdraw lock period */ function updateLockPeriod(uint256 _lockPeriod) external onlyOwner { require(lockPeriod != _lockPeriod, "Same value already set"); require(_lockPeriod <= MAX_LOCK_PERIOD, "Exceeds max lock period"); emit LockPeriodUpdated(lockPeriod, _lockPeriod); lockPeriod = _lockPeriod; } /* * @notice Update fee address * @dev Only callable by owner. * @param _feeAddress: the fee address */ function updateFeeAddress(address _feeAddress) external onlyOwner { require(_feeAddress != address(0), "Invalid zero address"); require(feeAddress != _feeAddress, "Same value already set"); require(feeAddress != _feeAddress, "Same fee address already set"); emit FeeAddressUpdated(feeAddress, _feeAddress); feeAddress = payable(_feeAddress); } /** * @notice It allows the admin to update start and end blocks * @dev This function is only callable by owner. * @param _startBlock: the new start block * @param _endBlock: the new end block */ function updateStartAndEndBlocks(uint256 _startBlock, uint256 _endBlock) external onlyOwner { require(block.number < startBlock, "Pool has started"); require( _startBlock < _endBlock, "New startBlock must be lower than new endBlock" ); require( block.number < _startBlock, "New startBlock must be higher than current block" ); startBlock = _startBlock; endBlock = _endBlock; // Set the lastRewardBlock as the startBlock lastRewardBlock = startBlock; emit StartAndEndBlocksUpdated(_startBlock, _endBlock); } /* * @notice View function to see pending reward on frontend. * @param _user: user address * @return Pending reward for a given user */ function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; if (block.number > lastRewardBlock && stakedSupply != 0) { uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 rewardAmount = multiplier.mul(rewardPerBlock); uint256 adjustedTokenPerShare = accTokenPerShare.add( rewardAmount.mul(PRECISION_FACTOR).div(stakedSupply) ); return user .amount .mul(adjustedTokenPerShare) .div(PRECISION_FACTOR) .sub(user.rewardDebt); } else { return user.amount.mul(accTokenPerShare).div(PRECISION_FACTOR).sub( user.rewardDebt ); } } /* * @notice Update reward variables of the given pool to be up-to-date. */ function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } if (stakedSupply == 0) { lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 rewardAmount = multiplier.mul(rewardPerBlock); accTokenPerShare = accTokenPerShare.add( rewardAmount.mul(PRECISION_FACTOR).div(stakedSupply) ); lastRewardBlock = block.number; } /* * @notice Return reward multiplier over the given _from to _to block. * @param _from: block to start * @param _to: block to finish */ function _getMultiplier(uint256 _from, uint256 _to) internal view returns (uint256) { if (_to <= endBlock) { return _to.sub(_from); } else if (_from >= endBlock) { return 0; } else { return endBlock.sub(_from); } } }
@notice Update reward variables of the given pool to be up-to-date./
function _updatePool() internal { if (block.number <= lastRewardBlock) { return; } if (stakedSupply == 0) { lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(lastRewardBlock, block.number); uint256 rewardAmount = multiplier.mul(rewardPerBlock); accTokenPerShare = accTokenPerShare.add( rewardAmount.mul(PRECISION_FACTOR).div(stakedSupply) ); lastRewardBlock = block.number; }
1,644,159
[ 1, 1891, 19890, 3152, 434, 326, 864, 2845, 358, 506, 731, 17, 869, 17, 712, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2725, 2864, 1435, 2713, 288, 203, 3639, 309, 261, 2629, 18, 2696, 1648, 1142, 17631, 1060, 1768, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 334, 9477, 3088, 1283, 422, 374, 13, 288, 203, 5411, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 15027, 273, 389, 588, 23365, 12, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 3639, 2254, 5034, 19890, 6275, 273, 15027, 18, 16411, 12, 266, 2913, 2173, 1768, 1769, 203, 3639, 4078, 1345, 2173, 9535, 273, 4078, 1345, 2173, 9535, 18, 1289, 12, 203, 5411, 19890, 6275, 18, 16411, 12, 3670, 26913, 67, 26835, 2934, 2892, 12, 334, 9477, 3088, 1283, 13, 203, 3639, 11272, 203, 3639, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @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) public balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation */ contract MintableToken is StandardToken, Ownable { uint256 public hardCap; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title KryptoroToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract KryptoroToken is MintableToken, Destructible { string public constant name = "KRYPTORO Coin"; string public constant symbol = "KTO"; uint8 public constant decimals = 18; /** * @dev Constructor that gives msg.sender all of existing tokens. */ function KryptoroToken() public { hardCap = 100 * 1000000 * (10 ** uint256(decimals)); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply.add(_amount) <= hardCap); return super.mint(_to, _amount); } } /** * @title KTOCrowdsale * @dev KTOCrowdsale is a completed contract for managing a token crowdsale. * KTOCrowdsale have a start and end timestamps, where investors can make * token purchases and the KTOCrowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract KTOCrowdsale is Ownable{ using SafeMath for uint256; // The token being sold KryptoroToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event TokenContractUpdated(bool state); event WalletAddressUpdated(bool state); function KTOCrowdsale() public { token = createTokenContract(); startTime = 1532332800; endTime = 1539590400; rate = 612; wallet = 0x34367d515ff223a27985518f2780cccc4a7e0fc9; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (KryptoroToken) { return new KryptoroToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool nonZeroPurchase = msg.value != 0; bool withinPeriod = now >= startTime && now <= endTime; return nonZeroPurchase && withinPeriod; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool timeEnded = now > endTime; return timeEnded; } // update token contract function updateKryptoroToken(address _tokenAddress) onlyOwner{ require(_tokenAddress != address(0)); token.transferOwnership(_tokenAddress); TokenContractUpdated(true); } // update wallet address function updateWalletAddress(address _newWallet) onlyOwner { require(_newWallet != address(0)); wallet = _newWallet; WalletAddressUpdated(true); } }
update wallet address
function updateWalletAddress(address _newWallet) onlyOwner { require(_newWallet != address(0)); wallet = _newWallet; WalletAddressUpdated(true); }
2,260,443
[ 1, 2725, 9230, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 16936, 1887, 12, 2867, 389, 2704, 16936, 13, 1338, 5541, 288, 203, 1377, 2583, 24899, 2704, 16936, 480, 1758, 12, 20, 10019, 203, 1377, 9230, 273, 389, 2704, 16936, 31, 203, 203, 1377, 20126, 1887, 7381, 12, 3767, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x0cBE2dF57CA9191B64a7Af3baa3F946fa7Df2F25/sources/Synth.sol
* @notice Function that allows synth contract to delegate sending fee to the fee Pool. @dev Only the synth contract can call this function. @param from The address fee is coming from. @param sourceCurrencyKey source currency fee from. @param sourceAmount The amount, specified in UNIT of source currency. @return Boolean that indicates whether the transfer succeeded or failed./ Pass it along, defaulting to the sender as the recipient. Tell the fee pool about this.
function synthInitiatedFeePayment( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) external onlySynth returns (bool) { require(sourceAmount > 0, "Source can't be 0"); bool result = _internalExchange( from, sourceCurrencyKey, sourceAmount, "XDR", feePool.FEE_ADDRESS(), ); feePool.feePaid(sourceCurrencyKey, sourceAmount); return result; }
4,836,168
[ 1, 2083, 716, 5360, 6194, 451, 6835, 358, 7152, 5431, 14036, 358, 326, 14036, 8828, 18, 225, 5098, 326, 6194, 451, 6835, 848, 745, 333, 445, 18, 225, 628, 1021, 1758, 14036, 353, 19283, 628, 18, 225, 1084, 7623, 653, 1084, 5462, 14036, 628, 18, 225, 1084, 6275, 1021, 3844, 16, 1269, 316, 28721, 434, 1084, 5462, 18, 327, 3411, 716, 8527, 2856, 326, 7412, 15784, 578, 2535, 18, 19, 10311, 518, 7563, 16, 805, 310, 358, 326, 5793, 487, 326, 8027, 18, 29860, 326, 14036, 2845, 2973, 333, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6194, 451, 2570, 10206, 14667, 6032, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1731, 24, 1084, 7623, 653, 16, 203, 3639, 2254, 1084, 6275, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 10503, 451, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 3168, 6275, 405, 374, 16, 315, 1830, 848, 1404, 506, 374, 8863, 203, 203, 3639, 1426, 563, 273, 389, 7236, 11688, 12, 203, 5411, 628, 16, 203, 5411, 1084, 7623, 653, 16, 203, 5411, 1084, 6275, 16, 203, 5411, 315, 60, 6331, 3113, 203, 5411, 14036, 2864, 18, 8090, 41, 67, 15140, 9334, 203, 3639, 11272, 203, 203, 3639, 14036, 2864, 18, 21386, 16507, 350, 12, 3168, 7623, 653, 16, 1084, 6275, 1769, 203, 203, 3639, 327, 563, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.12; library SafeMath { function MUL98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING if (a == 0) return 0; uint256 c = a * b; require(c / a == b); return c; } function DIV107(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0); uint256 c = a / b; return c; } function SUB705(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD235(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD157(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } contract ERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; event TRANSFER731(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL787(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING uint256 internal _totalSupply; function TOTALSUPPLY882() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF767(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE10(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER204(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER522(msg.sender, to, value); return true; } function APPROVE277(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _allowed[msg.sender][spender] = value; emit APPROVAL787(msg.sender, spender, value); return true; } function TRANSFERFROM832(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER522(from, to, value); _allowed[msg.sender][to] = _allowed[msg.sender][to].SUB705(value); return true; } function _TRANSFER522(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB705(value); _balances[to] = _balances[to].ADD235(value); emit TRANSFER731(from, to, value); } } contract ERC20Mintable is ERC20 { string public name; string public symbol; uint8 public decimals; function _MINT321(address to, uint256 amount) internal { //inject NONSTANDARD NAMING _balances[to] = _balances[to].ADD235(amount); _totalSupply = _totalSupply.ADD235(amount); emit TRANSFER731(address(0), to, amount); } function _BURN441(address from, uint256 amount) internal { //inject NONSTANDARD NAMING _balances[from] = _balances[from].SUB705(amount); _totalSupply = _totalSupply.SUB705(amount); emit TRANSFER731(from, address(0), amount); } } // ----------- Aave ---------------- contract ILendingPoolAddressesProvider { function GETLENDINGPOOL38() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLIMPL881(address _pool) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLCORE21() public view returns (address payable); //inject NONSTANDARD NAMING function SETLENDINGPOOLCOREIMPL156(address _lendingPoolCore) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLCONFIGURATOR254() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLCONFIGURATORIMPL555(address _configurator) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLDATAPROVIDER61() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLDATAPROVIDERIMPL193(address _provider) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLPARAMETERSPROVIDER362() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLPARAMETERSPROVIDERIMPL978(address _parametersProvider) public; //inject NONSTANDARD NAMING function GETTOKENDISTRIBUTOR827() public view returns (address); //inject NONSTANDARD NAMING function SETTOKENDISTRIBUTOR348(address _tokenDistributor) public; //inject NONSTANDARD NAMING function GETFEEPROVIDER168() public view returns (address); //inject NONSTANDARD NAMING function SETFEEPROVIDERIMPL718(address _feeProvider) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLLIQUIDATIONMANAGER82() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLLIQUIDATIONMANAGER708(address _manager) public; //inject NONSTANDARD NAMING function GETLENDINGPOOLMANAGER762() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGPOOLMANAGER882(address _lendingPoolManager) public; //inject NONSTANDARD NAMING function GETPRICEORACLE485() public view returns (address); //inject NONSTANDARD NAMING function SETPRICEORACLE428(address _priceOracle) public; //inject NONSTANDARD NAMING function GETLENDINGRATEORACLE592() public view returns (address); //inject NONSTANDARD NAMING function SETLENDINGRATEORACLE655(address _lendingRateOracle) public; //inject NONSTANDARD NAMING } interface ILendingPool { function ADDRESSESPROVIDER344() external view returns(address); //inject NONSTANDARD NAMING function DEPOSIT818(address _reserve, uint256 _amount, uint16 _referralCode) external payable; //inject NONSTANDARD NAMING function REDEEMUNDERLYING805(address _reserve, address _user, uint256 _amount) external; //inject NONSTANDARD NAMING function BORROW264(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external; //inject NONSTANDARD NAMING function REPAY662(address _reserve, uint256 _amount, address _onBehalfOf) external payable; //inject NONSTANDARD NAMING function SWAPBORROWRATEMODE766(address _reserve) external; //inject NONSTANDARD NAMING function REBALANCEFIXEDBORROWRATE627(address _reserve, address _user) external; //inject NONSTANDARD NAMING function SETUSERUSERESERVEASCOLLATERAL986(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING function LIQUIDATIONCALL807(address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken) external payable; //inject NONSTANDARD NAMING function FLASHLOAN206(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external; //inject NONSTANDARD NAMING function GETRESERVECONFIGURATIONDATA59(address _reserve) external view returns(uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive); //inject NONSTANDARD NAMING function GETRESERVEDATA692(address _reserve) external view returns(uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp); //inject NONSTANDARD NAMING function GETUSERACCOUNTDATA811(address _user) external view returns(uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor); //inject NONSTANDARD NAMING function GETUSERRESERVEDATA732(address _reserve, address _user) external view returns(uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled); //inject NONSTANDARD NAMING function GETRESERVES689() external view; //inject NONSTANDARD NAMING } interface ILendingPoolCore { function GETRESERVEATOKENADDRESS314(address _reserve) external view returns (address); //inject NONSTANDARD NAMING function GETRESERVECURRENTVARIABLEBORROWRATE762(address _token) external view returns (uint256); //inject NONSTANDARD NAMING function GETRESERVECURRENTLIQUIDITYRATE636(address _token) external view returns (uint256); //inject NONSTANDARD NAMING } interface IAavePriceOracleGetter { function GETASSETPRICE734(address _asset) external view returns (uint256); //inject NONSTANDARD NAMING function GETASSETSPRICES996(address[] calldata _assets) external view returns(uint256[] memory); //inject NONSTANDARD NAMING function GETSOURCEOFASSET324(address _asset) external view returns(address); //inject NONSTANDARD NAMING function GETFALLBACKORACLE535() external view returns(address); //inject NONSTANDARD NAMING } interface IAToken { function REDIRECTINTERESTSTREAM242(address _to) external; //inject NONSTANDARD NAMING function REDIRECTINTERESTSTREAMOF292(address _from, address _to) external; //inject NONSTANDARD NAMING function ALLOWINTERESTREDIRECTIONTO292(address _to) external; //inject NONSTANDARD NAMING function REDEEM632(uint256 _amount) external; //inject NONSTANDARD NAMING function PRINCIPALBALANCEOF100(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function ISTRANSFERALLOWED396(address _user, uint256 _amount) external view returns (bool); //inject NONSTANDARD NAMING function GETUSERINDEX768(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function GETINTERESTREDIRECTIONADDRESS228(address _user) external view returns(address); //inject NONSTANDARD NAMING function GETREDIRECTEDBALANCE288(address _user) external view returns(uint256); //inject NONSTANDARD NAMING function TOTALSUPPLY882() external view returns (uint256 supply); //inject NONSTANDARD NAMING function BALANCEOF767(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING function TRANSFER204(address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function TRANSFERFROM832(address _from, address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function APPROVE277(address _spender, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING function ALLOWANCE10(address _owner, address _spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING function NAME858() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL894() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS454() external view returns (uint8); //inject NONSTANDARD NAMING } interface PriceOracle { function GETUNDERLYINGPRICE929(address) external view returns (uint256); //inject NONSTANDARD NAMING } // ---------- Compound ---------- interface CErc20 { function BORROW264(uint256) external returns (uint256); //inject NONSTANDARD NAMING function BORROWRATEPERBLOCK388() external view returns (uint256); //inject NONSTANDARD NAMING function BORROWBALANCECURRENT444(address) external returns (uint256); //inject NONSTANDARD NAMING function REPAYBORROW515(uint256) external returns (uint256); //inject NONSTANDARD NAMING } interface CEth { function MINT397() external payable; //inject NONSTANDARD NAMING function REDEEMUNDERLYING805(uint redeemAmount) external returns (uint256); //inject NONSTANDARD NAMING function BALANCEOFUNDERLYING788(address owner) external returns (uint256); //inject NONSTANDARD NAMING function SUPPLYRATEPERBLOCK15() external view returns (uint256); //inject NONSTANDARD NAMING } interface Comptroller { function MARKETS249(address) external returns (bool, uint256); //inject NONSTANDARD NAMING function ENTERMARKETS82(address[] calldata) //inject NONSTANDARD NAMING external returns (uint256[] memory); function GETACCOUNTLIQUIDITY384(address) //inject NONSTANDARD NAMING external view returns (uint256, uint256, uint256); function ORACLE168() external view returns(address); //inject NONSTANDARD NAMING } // ---------- kyber ---------- interface Exchange { function TRADE301( //inject NONSTANDARD NAMING address src, uint srcAmount, address dest, address destAddress, uint maxDestAmount, uint minConversionRate, address walletId )external payable returns(uint); } // -----tCDP----- contract tCDPConstants { uint256 constant dust264 = 1e6; // minimum mint amount //inject NONSTANDARD NAMING ERC20 constant dai445 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI(debt) token address //inject NONSTANDARD NAMING //Compound Comptroller constant comptroller75 = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //inject NONSTANDARD NAMING CEth constant ceth501 = CEth(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); //inject NONSTANDARD NAMING CErc20 constant cdai61 = CErc20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); //inject NONSTANDARD NAMING //AAVE ILendingPoolAddressesProvider constant addressesprovider654 = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING uint16 constant referral215 = 47; // TODO: apply new referral code //inject NONSTANDARD NAMING //Kyber Exchange constant kybernetwork927 = Exchange(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); //inject NONSTANDARD NAMING address constant etheraddr36 = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //inject NONSTANDARD NAMING address constant ref472 = 0xD0533664013a82c31584B7FFDB215139f38Ad77A; //inject NONSTANDARD NAMING //rebalance target/boundary/size uint256 constant targetratio559 = 0.4e18; //40% //inject NONSTANDARD NAMING uint256 constant upperbound23 = 444444444444444444; // 1/225% //inject NONSTANDARD NAMING uint256 constant lowerbound414 = 363636363636363636; // 1/275% //inject NONSTANDARD NAMING uint256 constant bite558 = 0.025 * 1e18; //2.5% //inject NONSTANDARD NAMING } contract tCDP is ERC20Mintable, tCDPConstants{ using SafeMath for *; bool public isCompound; event MIGRATION431(uint8); // 0x01 = to Compound, 0x02 = to Aave //inject NONSTANDARD NAMING constructor() public { symbol = "tETH-DAI"; name = "tokenized CDP ETH-DAI v1"; decimals = 18; address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); dai445.APPROVE277(lendingPoolCoreAddress, uint256(-1)); dai445.APPROVE277(address(cdai61), uint256(-1)); address[] memory cTokens = new address[](1); cTokens[0] = address(ceth501); uint256[] memory errors = comptroller75.ENTERMARKETS82(cTokens); require(errors[0] == 0, "Comptroller.enterMarkets failed."); dai445.APPROVE277(address(kybernetwork927), uint256(-1)); isCompound = FINDBESTRATE616(); } function INITIATE270(uint256 amount) external payable { //inject NONSTANDARD NAMING require(_totalSupply < dust264, "initiated"); require(msg.value > dust264, "value too small"); if(isCompound) { ceth501.MINT397.value(msg.value)(); _MINT321(msg.sender, msg.value); require(cdai61.BORROW264(amount) == 0, "borrow failed"); dai445.TRANSFER204(msg.sender, amount); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(msg.value)(etheraddr36, msg.value, referral215); _MINT321(msg.sender, msg.value); lendingPool.BORROW264(address(dai445), amount, 2, referral215); dai445.TRANSFER204(msg.sender, amount); } } function COLLATERAL797() public returns(uint256) { //inject NONSTANDARD NAMING if(isCompound) { return ceth501.BALANCEOFUNDERLYING788(address(this)); } else { address lendingPoolCore = addressesprovider654.GETLENDINGPOOLCORE21(); address aETH = ILendingPoolCore(lendingPoolCore).GETRESERVEATOKENADDRESS314(etheraddr36); return IAToken(aETH).BALANCEOF767(address(this)); } } function DEBT567() public returns(uint256) { //inject NONSTANDARD NAMING if(isCompound) { return cdai61.BORROWBALANCECURRENT444(address(this)); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); (, uint256 borrowBalance,,,,,,,,) = lendingPool.GETUSERRESERVEDATA732(address(dai445), address(this)); return borrowBalance; } } function MINT397() external payable returns(uint256) { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); uint256 amount = msg.value; uint256 tokenToMint = _totalSupply.MUL98(amount).DIV107(COLLATERAL797()); uint256 tokenToBorrow = DEBT567().MUL98(amount).DIV107(COLLATERAL797()); _MINT321(msg.sender, tokenToMint); if(isCompound) { ceth501.MINT397.value(amount)(); require(cdai61.BORROW264(tokenToBorrow) == 0, "borrow failed"); dai445.TRANSFER204(msg.sender, tokenToBorrow); } else{ // deposit ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(amount)(etheraddr36, amount, referral215); // borrow lendingPool.BORROW264(address(dai445), tokenToBorrow, 2, referral215); // transfer dai445.TRANSFER204(msg.sender, tokenToBorrow); } return tokenToMint; } function BURN250(uint256 amount) external { //inject NONSTANDARD NAMING uint256 tokenToRepay = amount.MUL98(DEBT567()).DIV107(_totalSupply); uint256 tokenToDraw = amount.MUL98(COLLATERAL797()).DIV107(_totalSupply); _BURN441(msg.sender, amount); dai445.TRANSFERFROM832(msg.sender, address(this), tokenToRepay); if(isCompound) { require(cdai61.REPAYBORROW515(tokenToRepay) == 0, "repay failed"); require(ceth501.REDEEMUNDERLYING805(tokenToDraw) == 0, "redeem failed"); } else { // repay ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); // Dai.approve(lendingPoolCoreAddress, tokenToRepay); lendingPool.REPAY662(address(dai445), tokenToRepay, address(this)); // redeem IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(tokenToDraw); } (bool success, ) = msg.sender.call.value(tokenToDraw)(""); require(success, "Failed to transfer ether to msg.sender"); } function() external payable{} //true if (cEth APR - cDai APR) >= (aEth APR - aDai APR), otherwise, false function FINDBESTRATE616() public view returns (bool) { //inject NONSTANDARD NAMING return AAVEDAIAPR797().MUL98(targetratio559).DIV107(1e18).ADD235(COMPOUNDETHAPR912()) > COMPOUNDDAIAPR961().MUL98(targetratio559).DIV107(1e18).ADD235(AAVEETHAPR160()); } function COMPOUNDDAIAPR961() public view returns (uint256) { //inject NONSTANDARD NAMING return cdai61.BORROWRATEPERBLOCK388().MUL98(2102400); } function COMPOUNDETHAPR912() public view returns (uint256) { //inject NONSTANDARD NAMING return ceth501.SUPPLYRATEPERBLOCK15().MUL98(2102400); } function AAVEDAIAPR797() public view returns (uint256) { //inject NONSTANDARD NAMING ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21()); return core.GETRESERVECURRENTVARIABLEBORROWRATE762(address(dai445)).DIV107(1e9); } function AAVEETHAPR160() public view returns (uint256) { //inject NONSTANDARD NAMING ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21()); return core.GETRESERVECURRENTLIQUIDITYRATE636(etheraddr36).DIV107(1e9); } function GETUNDERLYINGPRICE929() public view returns(uint256) { //inject NONSTANDARD NAMING uint256 price; if(isCompound) { address oracle = comptroller75.ORACLE168(); PriceOracle priceOracle = PriceOracle(oracle); price = priceOracle.GETUNDERLYINGPRICE929(address(cdai61)); } else { address oracleAddress = addressesprovider654.GETPRICEORACLE485(); IAavePriceOracleGetter priceOracle = IAavePriceOracleGetter(oracleAddress); price = priceOracle.GETASSETPRICE734(address(dai445)); } return price; } function DEBTRATIO670() public returns (uint256) { //inject NONSTANDARD NAMING uint256 price = GETUNDERLYINGPRICE929(); uint256 ratio = DEBT567().MUL98(price).DIV107(COLLATERAL797()); return ratio; } function DELEVERAGE904() external { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); require(DEBTRATIO670() > upperbound23, "debt ratio is good"); uint256 amount = COLLATERAL797().MUL98(bite558).DIV107(1e18); if(isCompound) { require(ceth501.REDEEMUNDERLYING805(amount) == 0, "redeem failed"); uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472); require(cdai61.REPAYBORROW515(income) == 0, "repay failed"); } else { // redeem address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(amount); uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472); // repay ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); // Dai.approve(lendingPoolCoreAddress, income); lendingPool.REPAY662(address(dai445), income, address(this)); } } function LEVERAGE920() external { //inject NONSTANDARD NAMING require(_totalSupply >= dust264, "not initiated"); require(DEBTRATIO670() < lowerbound414, "debt ratio is good"); uint256 amount = DEBT567().MUL98(bite558).DIV107(1e18); if(isCompound) { require(cdai61.BORROW264(amount) == 0, "borrow failed"); uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472); ceth501.MINT397.value(income)(); } else { // borrow ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.BORROW264(address(dai445), amount, 2, referral215); uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472); // deposit lendingPool.DEPOSIT818.value(income)(etheraddr36, income, referral215); } } function MIGRATE814() external { //inject NONSTANDARD NAMING if(FINDBESTRATE616() != isCompound) { uint256 _debt = DEBT567(); uint256 _collateral = COLLATERAL797(); dai445.TRANSFERFROM832(msg.sender, address(this), _debt); uint256 newBorrow = _debt.ADD235(2); if(isCompound) { require(cdai61.REPAYBORROW515(_debt) == 0, "borrow failed"); require(ceth501.REDEEMUNDERLYING805(_collateral) == 0, "redeem failed"); ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); lendingPool.DEPOSIT818.value(_collateral)(etheraddr36, _collateral, referral215); lendingPool.BORROW264(address(dai445), newBorrow, 2, referral215); isCompound = false; emit MIGRATION431(0x02); } else { ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38()); address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21(); lendingPool.REPAY662(address(dai445), _debt, address(this)); IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36)); aETH.REDEEM632(_collateral); ceth501.MINT397.value(_collateral)(); require(cdai61.BORROW264(newBorrow) == 0, "borrow failed"); isCompound = true; emit MIGRATION431(0x01); } dai445.TRANSFER204(msg.sender, newBorrow); } } }
inject NONSTANDARD NAMING
function ALLOWANCE10(address owner, address spender) public view returns (uint256) {
5,544,541
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18592, 4722, 2163, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./libraries/DecimalsConverter.sol"; import "./interfaces/ICapitalPool.sol"; import "./interfaces/IClaimingRegistry.sol"; import "./interfaces/IContractsRegistry.sol"; import "./interfaces/ILeveragePortfolio.sol"; import "./interfaces/ILiquidityRegistry.sol"; import "./interfaces/IPolicyBook.sol"; import "./interfaces/IPolicyBookFacade.sol"; import "./interfaces/IPolicyBookRegistry.sol"; import "./interfaces/IYieldGenerator.sol"; import "./interfaces/ILeveragePortfolioView.sol"; import "./abstract/AbstractDependant.sol"; import "./Globals.sol"; contract CapitalPool is ICapitalPool, OwnableUpgradeable, AbstractDependant { using SafeERC20 for ERC20; using SafeMath for uint256; IClaimingRegistry public claimingRegistry; IPolicyBookRegistry public policyBookRegistry; IYieldGenerator public yieldGenerator; ILeveragePortfolio public reinsurancePool; ILiquidityRegistry public liquidityRegistry; ILeveragePortfolioView public leveragePortfolioView; ERC20 public stblToken; // reisnurance pool vStable balance updated by(premium, interest from defi) uint256 public reinsurancePoolBalance; // user leverage pool vStable balance updated by(premium, addliq, withdraw liq) mapping(address => uint256) public leveragePoolBalance; // policy books vStable balances updated by(premium, addliq, withdraw liq) mapping(address => uint256) public regularCoverageBalance; // all hStable capital balance , updated by (all pool transfer + deposit to dfi + liq cushion) uint256 public hardUsdtAccumulatedBalance; // all vStable capital balance , updated by (all pool transfer + withdraw from liq cushion) uint256 public override virtualUsdtAccumulatedBalance; // pool balances tracking uint256 public liquidityCushionBalance; address public maintainer; uint256 public stblDecimals; event PoolBalancesUpdated( uint256 hardUsdtAccumulatedBalance, uint256 virtualUsdtAccumulatedBalance, uint256 liquidityCushionBalance, uint256 reinsurancePoolBalance ); event LiquidityCushionRebalanced( uint256 liquidityNeede, uint256 liquidityWithdraw, uint256 liquidityDeposit ); modifier broadcastBalancing() { _; emit PoolBalancesUpdated( hardUsdtAccumulatedBalance, virtualUsdtAccumulatedBalance, liquidityCushionBalance, reinsurancePoolBalance ); } modifier onlyPolicyBook() { require(policyBookRegistry.isPolicyBook(msg.sender), "CAPL: Not a PolicyBook"); _; } modifier onlyReinsurancePool() { require( address(reinsurancePool) == _msgSender(), "RP: Caller is not a reinsurance pool contract" ); _; } modifier onlyMaintainer() { require(_msgSender() == maintainer, "CP: not maintainer"); _; } function __CapitalPool_init() external initializer { __Ownable_init(); maintainer = _msgSender(); } function setDependencies(IContractsRegistry _contractsRegistry) external override onlyInjectorOrZero { claimingRegistry = IClaimingRegistry(_contractsRegistry.getClaimingRegistryContract()); policyBookRegistry = IPolicyBookRegistry( _contractsRegistry.getPolicyBookRegistryContract() ); stblToken = ERC20(_contractsRegistry.getUSDTContract()); yieldGenerator = IYieldGenerator(_contractsRegistry.getYieldGeneratorContract()); reinsurancePool = ILeveragePortfolio(_contractsRegistry.getReinsurancePoolContract()); liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract()); leveragePortfolioView = ILeveragePortfolioView( _contractsRegistry.getLeveragePortfolioViewContract() ); stblDecimals = stblToken.decimals(); } /// @notice distributes the policybook premiums into pools (CP, ULP , RP) /// @dev distributes the balances acording to the established percentages /// @param _stblAmount amount hardSTBL ingressed into the system /// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for /// @param _protocolFee uint256 the amount of protocol fee earned by premium function addPolicyHoldersHardSTBL( uint256 _stblAmount, uint256 _epochsNumber, uint256 _protocolFee ) external override onlyPolicyBook broadcastBalancing returns (uint256) { PremiumFactors memory factors; factors.vStblOfCP = regularCoverageBalance[_msgSender()]; factors.premiumPrice = _stblAmount.sub(_protocolFee); IPolicyBookFacade policyBookFacade = IPolicyBookFacade(IPolicyBook(_msgSender()).policyBookFacade()); /// TODO for v2 it is one user leverage pool , so need to figure it out after v2 ( factors.vStblDeployedByRP, , factors.lStblDeployedByLP, factors.userLeveragePoolAddress ) = policyBookFacade.getPoolsData(); uint256 reinsurancePoolPremium; uint256 userLeveragePoolPremium; uint256 coveragePoolPremium; if (factors.vStblDeployedByRP == 0 && factors.lStblDeployedByLP == 0) { coveragePoolPremium = factors.premiumPrice; } else { factors.stblAmount = _stblAmount; factors.premiumDurationInDays = _epochsNumber.mul(EPOCH_DAYS_AMOUNT); ( reinsurancePoolPremium, userLeveragePoolPremium, coveragePoolPremium ) = _calcPremiumForAllPools(factors); } uint256 reinsurancePoolTotalPremium = reinsurancePoolPremium.add(_protocolFee); reinsurancePoolBalance += reinsurancePoolTotalPremium; reinsurancePool.addPolicyPremium( _epochsNumber, DecimalsConverter.convertTo18(reinsurancePoolTotalPremium, stblDecimals) ); if (userLeveragePoolPremium > 0) { leveragePoolBalance[factors.userLeveragePoolAddress] += userLeveragePoolPremium; ILeveragePortfolio(factors.userLeveragePoolAddress).addPolicyPremium( _epochsNumber, DecimalsConverter.convertTo18(userLeveragePoolPremium, stblDecimals) ); } regularCoverageBalance[_msgSender()] += coveragePoolPremium; hardUsdtAccumulatedBalance += _stblAmount; virtualUsdtAccumulatedBalance += _stblAmount; return DecimalsConverter.convertTo18(coveragePoolPremium, stblDecimals); } function _calcPremiumForAllPools(PremiumFactors memory factors) internal view returns ( uint256 reinsurancePoolPremium, uint256 userLeveragePoolPremium, uint256 coveragePoolPremium ) { uint256 _totalCoverTokens = DecimalsConverter.convertFrom18( (IPolicyBook(_msgSender())).totalCoverTokens(), stblDecimals ); uint256 poolUtilizationRation = _totalCoverTokens.mul(PERCENTAGE_100).div(factors.vStblOfCP); if (factors.lStblDeployedByLP > 0) { factors.participatedlStblDeployedByLP = factors .lStblDeployedByLP .mul( leveragePortfolioView.calcM(poolUtilizationRation, factors.userLeveragePoolAddress) ) .div(PERCENTAGE_100); } uint256 totalLiqforPremium = factors.vStblOfCP.add(factors.vStblDeployedByRP).add( factors.participatedlStblDeployedByLP ); uint256 premiumPerDay = factors.premiumPrice.mul(PRECISION).div( factors.premiumDurationInDays.mul(stblDecimals) ); factors.premiumPerDeployment = (premiumPerDay.mul(stblDecimals)).div(totalLiqforPremium); reinsurancePoolPremium = _calcReinsurancePoolPremium(factors); if (factors.lStblDeployedByLP > 0) { userLeveragePoolPremium = _calcUserLeveragePoolPremium(factors); } coveragePoolPremium = _calcCoveragePoolPremium(factors); } /// @notice distributes the hardSTBL from the coverage providers /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addCoverageProvidersHardSTBL(uint256 _stblAmount) external override onlyPolicyBook broadcastBalancing { regularCoverageBalance[_msgSender()] += _stblAmount; hardUsdtAccumulatedBalance += _stblAmount; virtualUsdtAccumulatedBalance += _stblAmount; } //// @notice distributes the hardSTBL from the leverage providers /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addLeverageProvidersHardSTBL(uint256 _stblAmount) external override onlyPolicyBook broadcastBalancing { leveragePoolBalance[_msgSender()] += _stblAmount; hardUsdtAccumulatedBalance += _stblAmount; virtualUsdtAccumulatedBalance += _stblAmount; } /// @notice distributes the hardSTBL from the reinsurance pool /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addReinsurancePoolHardSTBL(uint256 _stblAmount) external override onlyReinsurancePool broadcastBalancing { reinsurancePoolBalance += _stblAmount; hardUsdtAccumulatedBalance += _stblAmount; virtualUsdtAccumulatedBalance += _stblAmount; } /// TODO if user not withdraw the amount after request withdraw , should the amount returned back to capital pool /// @notice rebalances pools acording to v2 specification and dao enforced policies /// @dev emits PoolBalancesUpdated function rebalanceLiquidityCushion() public override broadcastBalancing onlyMaintainer { uint256 _pendingClaimAmount = claimingRegistry.getAllPendingClaimsAmount(); uint256 _pendingWithdrawlAmount = liquidityRegistry.getAllPendingWithdrawalRequestsAmount(); uint256 _requiredLiquidity = _pendingWithdrawlAmount.add(_pendingClaimAmount); _requiredLiquidity = DecimalsConverter.convertFrom18(_requiredLiquidity, stblDecimals); (uint256 _deposit, uint256 _withdraw) = getDepositAndWithdraw(_requiredLiquidity); liquidityCushionBalance = _requiredLiquidity; hardUsdtAccumulatedBalance = 0; uint256 _actualAmount; if (_deposit > 0) { stblToken.safeApprove(address(yieldGenerator), 0); stblToken.safeApprove(address(yieldGenerator), _deposit); _actualAmount = yieldGenerator.deposit(_deposit); if (_actualAmount < _deposit) { hardUsdtAccumulatedBalance += _deposit.sub(_actualAmount); } } else if (_withdraw > 0) { _actualAmount = yieldGenerator.withdraw(_withdraw); if (_actualAmount < _withdraw) { liquidityCushionBalance -= _withdraw.sub(_actualAmount); } } emit LiquidityCushionRebalanced(_requiredLiquidity, _withdraw, _deposit); } /// @notice Fullfils policybook claims by transfering the balance to claimer /// @param _claimer, address of the claimer recieving the withdraw /// @param _stblAmount uint256 amount to be withdrawn function fundClaim(address _claimer, uint256 _stblAmount) external override onlyPolicyBook { _withdrawFromLiquidityCushion(_claimer, _stblAmount); regularCoverageBalance[_msgSender()] -= _stblAmount; } /// @notice Withdraws liquidity from a specific policbybook to the user /// @param _sender, address of the user beneficiary of the withdraw /// @param _stblAmount uint256 amount to be withdrawn function withdrawLiquidity( address _sender, uint256 _stblAmount, bool _isLeveragePool ) external override onlyPolicyBook broadcastBalancing { _withdrawFromLiquidityCushion(_sender, _stblAmount); if (_isLeveragePool) { leveragePoolBalance[_msgSender()] -= _stblAmount; } else { regularCoverageBalance[_msgSender()] -= _stblAmount; } } function setMaintainer(address _newMainteiner) public onlyOwner { require(_newMainteiner != address(0), "CP: invalid maintainer address"); maintainer = _newMainteiner; } function _withdrawFromLiquidityCushion(address _sender, uint256 _stblAmount) internal broadcastBalancing { require(liquidityCushionBalance >= _stblAmount, "CP: insuficient liquidity"); liquidityCushionBalance = liquidityCushionBalance.sub(_stblAmount); virtualUsdtAccumulatedBalance -= _stblAmount; stblToken.safeTransfer(_sender, _stblAmount); } function _calcReinsurancePoolPremium(PremiumFactors memory factors) internal pure returns (uint256) { return ( factors .premiumPerDeployment .mul(factors.vStblDeployedByRP) .mul(factors.premiumDurationInDays) .div(PRECISION) ); } function _calcUserLeveragePoolPremium(PremiumFactors memory factors) internal pure returns (uint256) { return factors .premiumPerDeployment .mul(factors.participatedlStblDeployedByLP) .mul(factors.premiumDurationInDays) .div(PRECISION); } function _calcCoveragePoolPremium(PremiumFactors memory factors) internal pure returns (uint256) { return factors .premiumPerDeployment .mul(factors.vStblOfCP) .mul(factors.premiumDurationInDays) .div(PRECISION); } function getDepositAndWithdraw(uint256 _requiredLiquidity) internal view returns (uint256 deposit, uint256 withdraw) { uint256 _availableBalance = hardUsdtAccumulatedBalance.add(liquidityCushionBalance); if (_requiredLiquidity > _availableBalance) { withdraw = _requiredLiquidity.sub(_availableBalance); } else if (_requiredLiquidity < _availableBalance) { deposit = _availableBalance.sub(_requiredLiquidity); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds uint256 constant DAYS_IN_THE_YEAR = 365; uint256 constant MAX_INT = type(uint256).max; uint256 constant DECIMALS18 = 10**18; uint256 constant PRECISION = 10**25; uint256 constant PERCENTAGE_100 = 100 * PRECISION; uint256 constant BLOCKS_PER_DAY = 6450; uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365; uint256 constant APY_TOKENS = DECIMALS18; uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION; uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23; uint256 constant EPOCH_DAYS_AMOUNT = 7; // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "../interfaces/IContractsRegistry.sol"; abstract contract AbstractDependant { /// @dev keccak256(AbstractDependant.setInjector(address)) - 1 bytes32 private constant _INJECTOR_SLOT = 0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76; modifier onlyInjectorOrZero() { address _injector = injector(); require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector"); _; } function setInjector(address _injector) external onlyInjectorOrZero { bytes32 slot = _INJECTOR_SLOT; assembly { sstore(slot, _injector) } } /// @dev has to apply onlyInjectorOrZero() modifier function setDependencies(IContractsRegistry) external virtual; function injector() public view returns (address _injector) { bytes32 slot = _INJECTOR_SLOT; assembly { _injector := sload(slot) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ICapitalPool { struct PremiumFactors { uint256 stblAmount; uint256 premiumDurationInDays; uint256 premiumPrice; uint256 lStblDeployedByLP; uint256 vStblDeployedByRP; uint256 vStblOfCP; uint256 premiumPerDeployment; uint256 participatedlStblDeployedByLP; address userLeveragePoolAddress; } function virtualUsdtAccumulatedBalance() external view returns (uint256); /// @notice distributes the policybook premiums into pools (CP, ULP , RP) /// @dev distributes the balances acording to the established percentages /// @param _stblAmount amount hardSTBL ingressed into the system /// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for /// @param _protocolFee uint256 the amount of protocol fee earned by premium function addPolicyHoldersHardSTBL( uint256 _stblAmount, uint256 _epochsNumber, uint256 _protocolFee ) external returns (uint256); /// @notice distributes the hardSTBL from the coverage providers /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addCoverageProvidersHardSTBL(uint256 _stblAmount) external; /// @notice distributes the hardSTBL from the leverage providers /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addLeverageProvidersHardSTBL(uint256 _stblAmount) external; /// @notice distributes the hardSTBL from the reinsurance pool /// @dev emits PoolBalancedUpdated event /// @param _stblAmount amount hardSTBL ingressed into the system function addReinsurancePoolHardSTBL(uint256 _stblAmount) external; /// @notice rebalances pools acording to v2 specification and dao enforced policies /// @dev emits PoolBalancesUpdated function rebalanceLiquidityCushion() external; /// @notice Fullfils policybook claims by transfering the balance to claimer /// @param _claimer, address of the claimer recieving the withdraw /// @param _stblAmount uint256 amount to be withdrawn function fundClaim(address _claimer, uint256 _stblAmount) external; /// @notice Withdraws liquidity from a specific policbybook to the user /// @param _sender, address of the user beneficiary of the withdraw /// @param _stblAmount uint256 amount to be withdrawn /// @param _isLeveragePool bool wether the pool is ULP or CP(policybook) function withdrawLiquidity( address _sender, uint256 _stblAmount, bool _isLeveragePool ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IClaimingRegistry { enum ClaimStatus { CAN_CLAIM, UNCLAIMABLE, PENDING, AWAITING_CALCULATION, REJECTED_CAN_APPEAL, REJECTED, ACCEPTED } struct ClaimInfo { address claimer; address policyBookAddress; string evidenceURI; uint256 dateSubmitted; uint256 dateEnded; bool appeal; ClaimStatus status; uint256 claimAmount; } /// @notice returns anonymous voting duration function anonymousVotingDuration(uint256 index) external view returns (uint256); /// @notice returns the whole voting duration function votingDuration(uint256 index) external view returns (uint256); /// @notice returns how many time should pass before anyone could calculate a claim result function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256); /// @notice returns true if a user can buy new policy of specified PolicyBook function canBuyNewPolicy(address buyer, address policyBookAddress) external view returns (bool); /// @notice submits new PolicyBook claim for the user function submitClaim( address user, address policyBookAddress, string calldata evidenceURI, uint256 cover, bool appeal ) external returns (uint256); /// @notice returns true if the claim with this index exists function claimExists(uint256 index) external view returns (bool); /// @notice returns claim submition time function claimSubmittedTime(uint256 index) external view returns (uint256); /// @notice returns claim end time or zero in case it is pending function claimEndTime(uint256 index) external view returns (uint256); /// @notice returns true if the claim is anonymously votable function isClaimAnonymouslyVotable(uint256 index) external view returns (bool); /// @notice returns true if the claim is exposably votable function isClaimExposablyVotable(uint256 index) external view returns (bool); /// @notice returns true if claim is anonymously votable or exposably votable function isClaimVotable(uint256 index) external view returns (bool); /// @notice returns true if a claim can be calculated by anyone function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool); /// @notice returns true if this claim is pending or awaiting function isClaimPending(uint256 index) external view returns (bool); /// @notice returns how many claims the holder has function countPolicyClaimerClaims(address user) external view returns (uint256); /// @notice returns how many pending claims are there function countPendingClaims() external view returns (uint256); /// @notice returns how many claims are there function countClaims() external view returns (uint256); /// @notice returns a claim index of it's claimer and an ordinal number function claimOfOwnerIndexAt(address claimer, uint256 orderIndex) external view returns (uint256); /// @notice returns pending claim index by its ordinal index function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns claim index by its ordinal index function claimIndexAt(uint256 orderIndex) external view returns (uint256); /// @notice returns current active claim index by policybook and claimer function claimIndex(address claimer, address policyBookAddress) external view returns (uint256); /// @notice returns true if the claim is appealed function isClaimAppeal(uint256 index) external view returns (bool); /// @notice returns current status of a claim function policyStatus(address claimer, address policyBookAddress) external view returns (ClaimStatus); /// @notice returns current status of a claim function claimStatus(uint256 index) external view returns (ClaimStatus); /// @notice returns the claim owner (claimer) function claimOwner(uint256 index) external view returns (address); /// @notice returns the claim PolicyBook function claimPolicyBook(uint256 index) external view returns (address); /// @notice returns claim info by its index function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo); function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount); function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256); /// @notice marks the user's claim as Accepted function acceptClaim(uint256 index) external; /// @notice marks the user's claim as Rejected function rejectClaim(uint256 index) external; /// @notice Update Image Uri in case it contains material that is ilegal /// or offensive. /// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri. /// @param _claimIndex Claim Index that is going to be updated /// @param _newEvidenceURI New evidence uri. It can be blank. function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IContractsRegistry { function getUniswapRouterContract() external view returns (address); function getUniswapBMIToETHPairContract() external view returns (address); function getUniswapBMIToUSDTPairContract() external view returns (address); function getSushiswapRouterContract() external view returns (address); function getSushiswapBMIToETHPairContract() external view returns (address); function getSushiswapBMIToUSDTPairContract() external view returns (address); function getSushiSwapMasterChefV2Contract() external view returns (address); function getWETHContract() external view returns (address); function getUSDTContract() external view returns (address); function getBMIContract() external view returns (address); function getPriceFeedContract() external view returns (address); function getPolicyBookRegistryContract() external view returns (address); function getPolicyBookFabricContract() external view returns (address); function getBMICoverStakingContract() external view returns (address); function getBMICoverStakingViewContract() external view returns (address); function getLegacyRewardsGeneratorContract() external view returns (address); function getRewardsGeneratorContract() external view returns (address); function getBMIUtilityNFTContract() external view returns (address); function getNFTStakingContract() external view returns (address); function getLiquidityMiningContract() external view returns (address); function getClaimingRegistryContract() external view returns (address); function getPolicyRegistryContract() external view returns (address); function getLiquidityRegistryContract() external view returns (address); function getClaimVotingContract() external view returns (address); function getReinsurancePoolContract() external view returns (address); function getLeveragePortfolioViewContract() external view returns (address); function getCapitalPoolContract() external view returns (address); function getPolicyBookAdminContract() external view returns (address); function getPolicyQuoteContract() external view returns (address); function getLegacyBMIStakingContract() external view returns (address); function getBMIStakingContract() external view returns (address); function getSTKBMIContract() external view returns (address); function getVBMIContract() external view returns (address); function getLegacyLiquidityMiningStakingContract() external view returns (address); function getLiquidityMiningStakingETHContract() external view returns (address); function getLiquidityMiningStakingUSDTContract() external view returns (address); function getReputationSystemContract() external view returns (address); function getAaveProtocolContract() external view returns (address); function getAaveLendPoolAddressProvdierContract() external view returns (address); function getAaveATokenContract() external view returns (address); function getCompoundProtocolContract() external view returns (address); function getCompoundCTokenContract() external view returns (address); function getCompoundComptrollerContract() external view returns (address); function getYearnProtocolContract() external view returns (address); function getYearnVaultContract() external view returns (address); function getYieldGeneratorContract() external view returns (address); function getShieldMiningContract() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface ILeveragePortfolio { enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL} struct LevFundsFactors { uint256 netMPL; uint256 netMPLn; address policyBookAddr; // uint256 poolTotalLiquidity; // uint256 poolUR; // uint256 minUR; } function targetUR() external view returns (uint256); function d_ProtocolConstant() external view returns (uint256); function a_ProtocolConstant() external view returns (uint256); function max_ProtocolConstant() external view returns (uint256); /// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook. /// @param leveragePoolType LeveragePortfolio is determine the pool which call the function function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType) external returns (uint256); /// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook. function deployVirtualStableToCoveragePools() external returns (uint256); /// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner /// @param threshold uint256 is the reevaluatation threshold function setRebalancingThreshold(uint256 threshold) external; /// @notice set the protocol constant : access by owner /// @param _targetUR uint256 target utitlization ration /// @param _d_ProtocolConstant uint256 D protocol constant /// @param _a_ProtocolConstant uint256 A protocol constant /// @param _max_ProtocolConstant uint256 the max % included function setProtocolConstant( uint256 _targetUR, uint256 _d_ProtocolConstant, uint256 _a_ProtocolConstant, uint256 _max_ProtocolConstant ) external; /// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max) /// @param poolUR uint256 utitilization ratio for a coverage pool /// @return uint256 M facotr //function calcM(uint256 poolUR) external returns (uint256); /// @return uint256 the amount of vStable stored in the pool function totalLiquidity() external view returns (uint256); /// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook /// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook /// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for /// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external; /// @notice Used to get a list of coverage pools which get leveraged , use with count() /// @return _coveragePools a list containing policybook addresses function listleveragedCoveragePools(uint256 offset, uint256 limit) external view returns (address[] memory _coveragePools); /// @notice get count of coverage pools which get leveraged function countleveragedCoveragePools() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./ILeveragePortfolio.sol"; import "./IUserLeveragePool.sol"; interface ILeveragePortfolioView { function calcM(uint256 poolUR, address leveragePoolAddress) external view returns (uint256); function calcMaxLevFunds(ILeveragePortfolio.LevFundsFactors memory factors) external view returns (uint256); function calcBMIMultiplier(IUserLeveragePool.BMIMultiplierFactors memory factors) external view returns (uint256); function getPolicyBookFacade(address _policybookAddress) external view returns (IPolicyBookFacade _coveragePool); function calcNetMPLn( ILeveragePortfolio.LeveragePortfolio leveragePoolType, address _policyBookFacade ) external view returns (uint256 _netMPLn); function calcMaxVirtualFunds(address policyBookAddress) external returns (uint256 _amountToDeploy, uint256 _maxAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface ILiquidityRegistry { struct LiquidityInfo { address policyBookAddr; uint256 lockedAmount; uint256 availableAmount; uint256 bmiXRatio; // multiply availableAmount by this num to get stable coin } struct WithdrawalRequestInfo { address policyBookAddr; uint256 requestAmount; uint256 requestSTBLAmount; uint256 availableLiquidity; uint256 readyToWithdrawDate; uint256 endWithdrawDate; } struct WithdrawalSetInfo { address policyBookAddr; uint256 requestAmount; uint256 requestSTBLAmount; uint256 availableSTBLAmount; } function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external; function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external; function getPolicyBooksArrLength(address _userAddr) external view returns (uint256); function getPolicyBooksArr(address _userAddr) external view returns (address[] memory _resultArr); function getLiquidityInfos( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (LiquidityInfo[] memory _resultArr); function getWithdrawalRequests( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr); function getWithdrawalSet( address _userAddr, uint256 _offset, uint256 _limit ) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr); function registerWithdrawl(address _policyBook, address _users) external; function getAllPendingWithdrawalRequestsAmount() external returns (uint256 _totalWithdrawlAmount); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; import "./IClaimingRegistry.sol"; import "./IPolicyBookFacade.sol"; interface IPolicyBook { enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED} struct PolicyHolder { uint256 coverTokens; uint256 startEpochNumber; uint256 endEpochNumber; uint256 paid; uint256 reinsurancePrice; } struct WithdrawalInfo { uint256 withdrawalAmount; uint256 readyToWithdrawDate; bool withdrawalAllowed; } struct BuyPolicyParameters { address buyer; address holder; uint256 epochsNumber; uint256 coverTokens; uint256 distributorFee; address distributor; } function policyHolders(address _holder) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function policyBookFacade() external view returns (IPolicyBookFacade); function setPolicyBookFacade(address _policyBookFacade) external; function EPOCH_DURATION() external view returns (uint256); function stblDecimals() external view returns (uint256); function READY_TO_WITHDRAW_PERIOD() external view returns (uint256); function whitelisted() external view returns (bool); function epochStartTime() external view returns (uint256); // @TODO: should we let DAO to change contract address? /// @notice Returns address of contract this PolicyBook covers, access: ANY /// @return _contract is address of covered contract function insuranceContractAddress() external view returns (address _contract); /// @notice Returns type of contract this PolicyBook covers, access: ANY /// @return _type is type of contract function contractType() external view returns (IPolicyBookFabric.ContractType _type); function totalLiquidity() external view returns (uint256); function totalCoverTokens() external view returns (uint256); // /// @notice return MPL for user leverage pool // function userleveragedMPL() external view returns (uint256); // /// @notice return MPL for reinsurance pool // function reinsurancePoolMPL() external view returns (uint256); // function bmiRewardMultiplier() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns ( uint256 _withdrawalAmount, uint256 _readyToWithdrawDate, bool _withdrawalAllowed ); function __PolicyBook_init( address _insuranceContract, IPolicyBookFabric.ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external; function whitelist(bool _whitelisted) external; function getEpoch(uint256 time) external view returns (uint256); /// @notice get STBL equivalent function convertBMIXToSTBL(uint256 _amount) external view returns (uint256); /// @notice get BMIX equivalent function convertSTBLToBMIX(uint256 _amount) external view returns (uint256); /// @notice submits new claim of the policy book function submitClaimAndInitializeVoting(string calldata evidenceURI) external; /// @notice submits new appeal claim of the policy book function submitAppealAndInitializeVoting(string calldata evidenceURI) external; /// @notice updates info on claim acceptance function commitClaim( address claimer, uint256 claimAmount, uint256 claimEndTime, IClaimingRegistry.ClaimStatus status ) external; /// @notice forces an update of RewardsGenerator multiplier function forceUpdateBMICoverStakingRewardMultiplier() external; /// @notice function to get precise current cover and liquidity function getNewCoverAndLiquidity() external view returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity); /// @notice view function to get precise policy price /// @param _epochsNumber is number of epochs to cover /// @param _coverTokens is number of tokens to cover /// @param _buyer address of the user who buy the policy /// @return totalSeconds is number of seconds to cover /// @return totalPrice is the policy price which will pay by the buyer function getPolicyPrice( uint256 _epochsNumber, uint256 _coverTokens, address _buyer ) external view returns ( uint256 totalSeconds, uint256 totalPrice, uint256 pricePercentage ); /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _buyer who is transferring funds /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicy( address _buyer, address _holder, uint256 _epochsNumber, uint256 _coverTokens, uint256 _distributorFee, address _distributor ) external returns (uint256, uint256); function updateEpochsInfo() external; function secondsToEndCurrentEpoch() external view returns (uint256); /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin /// @param _liquidityHolderAddr is address of address to assign cover /// @param _liqudityAmount is amount of stable coin tokens to secure function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityBuyerAddr address the one that transfer funds /// @param _liquidityHolderAddr address the one that owns liquidity /// @param _liquidityAmount uint256 amount to be added on behalf the sender /// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake function addLiquidity( address _liquidityBuyerAddr, address _liquidityHolderAddr, uint256 _liquidityAmount, uint256 _stakeSTBLAmount ) external; function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256); function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus); function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external; // function requestWithdrawalWithPermit( // uint256 _tokensToWithdraw, // uint8 _v, // bytes32 _r, // bytes32 _s // ) external; function unlockTokens() external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity(address sender) external returns (uint256); function getAPY() external view returns (uint256); /// @notice Getting user stats, access: ANY function userStats(address _user) external view returns (PolicyHolder memory); /// @notice Getting number stats, access: ANY /// @return _maxCapacities is a max token amount that a user can buy /// @return _totalSTBLLiquidity is PolicyBook's liquidity /// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity /// @return _stakedSTBL is how much stable coin are staked on this PolicyBook /// @return _annualProfitYields is its APY /// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance function numberStats() external view returns ( uint256 _maxCapacities, uint256 _totalSTBLLiquidity, uint256 _totalLeveragedLiquidity, uint256 _stakedSTBL, uint256 _annualProfitYields, uint256 _annualInsuranceCost, uint256 _bmiXRatio ); /// @notice Getting info, access: ANY /// @return _symbol is the symbol of PolicyBook (bmiXCover) /// @return _insuredContract is an addres of insured contract /// @return _contractType is a type of insured contract /// @return _whitelisted is a state of whitelisting function info() external view returns ( string memory _symbol, address _insuredContract, IPolicyBookFabric.ContractType _contractType, bool _whitelisted ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; interface IPolicyBookFabric { enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS} /// @notice Create new Policy Book contract, access: ANY /// @param _contract is Contract to create policy book for /// @param _contractType is Contract to create policy book for /// @param _description is bmiXCover token desription for this policy book /// @param _projectSymbol replaces x in bmiXCover token symbol /// @param _initialDeposit is an amount user deposits on creation (addLiquidity()) /// @return _policyBook is address of created contract function create( address _contract, ContractType _contractType, string calldata _description, string calldata _projectSymbol, uint256 _initialDeposit, address _shieldMiningToken ) external returns (address); function createLeveragePools( ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; import "./IPolicyBook.sol"; import "./ILeveragePortfolio.sol"; interface IPolicyBookFacade { /// @notice Let user to buy policy by supplying stable coin, access: ANY /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external; /// @param _holder who owns coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage function buyPolicyFor( address _holder, uint256 _epochsNumber, uint256 _coverTokens ) external; function policyBook() external view returns (IPolicyBook); function userLiquidity(address account) external view returns (uint256); /// @notice virtual funds deployed by reinsurance pool function VUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by reinsurance pool function LUreinsurnacePool() external view returns (uint256); /// @notice leverage funds deployed by user leverage pool function LUuserLeveragePool(address userLeveragePool) external view returns (uint256); /// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool) function totalLeveragedLiquidity() external view returns (uint256); function userleveragedMPL() external view returns (uint256); function reinsurancePoolMPL() external view returns (uint256); function rebalancingThreshold() external view returns (uint256); function safePricingModel() external view returns (bool); /// @notice policyBookFacade initializer /// @param pbProxy polciybook address upgreadable cotnract. function __PolicyBookFacade_init( address pbProxy, address liquidityProvider, uint256 initialDeposit ) external; /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributor( uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @param _buyer who is buying the coverage /// @param _epochsNumber period policy will cover /// @param _coverTokens amount paid for the coverage /// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission) function buyPolicyFromDistributorFor( address _buyer, uint256 _epochsNumber, uint256 _coverTokens, address _distributor ) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _user the one taht add liquidity /// @param _liquidityAmount is amount of stable coin tokens to secure function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external; /// @notice Let user to add liquidity by supplying stable coin and stake it, /// @dev access: ANY function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external; /// @notice fetches all the pools data /// @return uint256 VUreinsurnacePool /// @return uint256 LUreinsurnacePool /// @return uint256 LUleveragePool /// @return uint256 user leverage pool address function getPoolsData() external view returns ( uint256, uint256, uint256, address ); /// @notice deploy leverage funds (RP lStable, ULP lStable) /// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity /// @param leveragePool whether user leverage or reinsurance leverage function deployLeverageFundsAfterRebalance( uint256 deployedAmount, ILeveragePortfolio.LeveragePortfolio leveragePool ) external; /// @notice deploy virtual funds (RP vStable) /// @param deployedAmount uint256 the deployed amount to be added to the liquidity function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external; /// @notice set the MPL for the user leverage and the reinsurance leverage /// @param _userLeverageMPL uint256 value of the user leverage MPL /// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external; /// @notice sets the rebalancing threshold value /// @param _newRebalancingThreshold uint256 rebalancing threshhold value function setRebalancingThreshold(uint256 _newRebalancingThreshold) external; /// @notice sets the rebalancing threshold value /// @param _safePricingModel bool is pricing model safe (true) or not (false) function setSafePricingModel(bool _safePricingModel) external; /// @notice returns how many BMI tokens needs to approve in order to submit a claim function getClaimApprovalAmount(address user) external view returns (uint256); /// @notice upserts a withdraw request /// @dev prevents adding a request if an already pending or ready request is open. /// @param _tokensToWithdraw uint256 amount of tokens to withdraw function requestWithdrawal(uint256 _tokensToWithdraw) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; interface IPolicyBookRegistry { struct PolicyBookStats { string symbol; address insuredContract; IPolicyBookFabric.ContractType contractType; uint256 maxCapacity; uint256 totalSTBLLiquidity; uint256 totalLeveragedLiquidity; uint256 stakedSTBL; uint256 APY; uint256 annualInsuranceCost; uint256 bmiXRatio; bool whitelisted; } function policyBooksByInsuredAddress(address insuredContract) external view returns (address); function policyBookFacades(address facadeAddress) external view returns (address); /// @notice Adds PolicyBook to registry, access: PolicyFabric function add( address insuredContract, IPolicyBookFabric.ContractType contractType, address policyBook, address facadeAddress ) external; function whitelist(address policyBookAddress, bool whitelisted) external; /// @notice returns required allowances for the policybooks function getPoliciesPrices( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external view returns (uint256[] memory _durations, uint256[] memory _allowances); /// @notice Buys a batch of policies function buyPolicyBatch( address[] calldata policyBooks, uint256[] calldata epochsNumbers, uint256[] calldata coversTokens ) external; /// @notice Checks if provided address is a PolicyBook function isPolicyBook(address policyBook) external view returns (bool); /// @notice Checks if provided address is a policyBookFacade function isPolicyBookFacade(address _facadeAddress) external view returns (bool); /// @notice Checks if provided address is a user leverage pool function isUserLeveragePool(address policyBookAddress) external view returns (bool); /// @notice Returns number of registered PolicyBooks with certain contract type function countByType(IPolicyBookFabric.ContractType contractType) external view returns (uint256); /// @notice Returns number of registered PolicyBooks, access: ANY function count() external view returns (uint256); function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType) external view returns (uint256); function countWhitelisted() external view returns (uint256); /// @notice Listing registered PolicyBooks with certain contract type, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type function listByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks, access: ANY /// @return _policyBooksArr is array of registered PolicyBook addresses function list(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); function listByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr); function listWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr); /// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY function listWithStatsByType( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Listing registered PolicyBooks with stats, access: ANY function listWithStats(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsByTypeWhitelisted( IPolicyBookFabric.ContractType contractType, uint256 offset, uint256 limit ) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); function listWithStatsWhitelisted(uint256 offset, uint256 limit) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats); /// @notice Getting stats from policy books, access: ANY /// @param policyBooks is list of PolicyBooks addresses function stats(address[] calldata policyBooks) external view returns (PolicyBookStats[] memory _stats); /// @notice Return existing Policy Book contract, access: ANY /// @param insuredContract is contract address to lookup for created IPolicyBook function policyBookFor(address insuredContract) external view returns (address); /// @notice Getting stats from policy books, access: ANY /// @param insuredContracts is list of insuredContracts in registry function statsByInsuredContracts(address[] calldata insuredContracts) external view returns (PolicyBookStats[] memory _stats); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "./IPolicyBookFabric.sol"; import "./IClaimingRegistry.sol"; import "./IPolicyBookFacade.sol"; interface IUserLeveragePool { enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED} struct WithdrawalInfo { uint256 withdrawalAmount; uint256 readyToWithdrawDate; bool withdrawalAllowed; } struct BMIMultiplierFactors { uint256 poolMultiplier; uint256 leverageProvided; uint256 multiplier; } /// @notice Returns type of contract this PolicyBook covers, access: ANY /// @return _type is type of contract function contractType() external view returns (IPolicyBookFabric.ContractType _type); function userLiquidity(address account) external view returns (uint256); function EPOCH_DURATION() external view returns (uint256); function READY_TO_WITHDRAW_PERIOD() external view returns (uint256); function epochStartTime() external view returns (uint256); function withdrawalsInfo(address _userAddr) external view returns ( uint256 _withdrawalAmount, uint256 _readyToWithdrawDate, bool _withdrawalAllowed ); function __UserLeveragePool_init( IPolicyBookFabric.ContractType _contractType, string calldata _description, string calldata _projectSymbol ) external; function getEpoch(uint256 time) external view returns (uint256); /// @notice get STBL equivalent function convertBMIXToSTBL(uint256 _amount) external view returns (uint256); /// @notice get BMIX equivalent function convertSTBLToBMIX(uint256 _amount) external view returns (uint256); /// @notice forces an update of RewardsGenerator multiplier function forceUpdateBMICoverStakingRewardMultiplier() external; /// @notice function to get precise current cover and liquidity function getNewCoverAndLiquidity() external view returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity); function updateEpochsInfo() external; function secondsToEndCurrentEpoch() external view returns (uint256); /// @notice Let user to add liquidity by supplying stable coin, access: ANY /// @param _liqudityAmount is amount of stable coin tokens to secure function addLiquidity(uint256 _liqudityAmount) external; // /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin // /// @param _liquidityHolderAddr is address of address to assign cover // /// @param _liqudityAmount is amount of stable coin tokens to secure // function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external; function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external; function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256); function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus); function requestWithdrawal(uint256 _tokensToWithdraw) external; // function requestWithdrawalWithPermit( // uint256 _tokensToWithdraw, // uint8 _v, // bytes32 _r, // bytes32 _s // ) external; function unlockTokens() external; /// @notice Let user to withdraw deposited liqiudity, access: ANY function withdrawLiquidity() external; function getAPY() external view returns (uint256); function whitelisted() external view returns (bool); function whitelist(bool _whitelisted) external; /// @notice set max total liquidity for the pool /// @param _maxCapacities uint256 the max total liquidity function setMaxCapacities(uint256 _maxCapacities) external; /// @notice Getting number stats, access: ANY /// @return _maxCapacities is a max liquidity of the pool /// @return _totalSTBLLiquidity is PolicyBook's liquidity /// @return _totalLeveragedLiquidity is becuase to follow the same function in policy book /// @return _stakedSTBL is how much stable coin are staked on this PolicyBook /// @return _annualProfitYields is its APY /// @return _annualInsuranceCost is becuase to follow the same function in policy book /// @return _bmiXRatio is multiplied by 10**18. To get STBL representation function numberStats() external view returns ( uint256 _maxCapacities, uint256 _totalSTBLLiquidity, uint256 _totalLeveragedLiquidity, uint256 _stakedSTBL, uint256 _annualProfitYields, uint256 _annualInsuranceCost, uint256 _bmiXRatio ); /// @notice Getting info, access: ANY /// @return _symbol is the symbol of PolicyBook (bmiXCover) /// @return _insuredContract is an addres of insured contract /// @return _contractType is becuase to follow the same function in policy book /// @return _whitelisted is a state of whitelisting function info() external view returns ( string memory _symbol, address _insuredContract, IPolicyBookFabric.ContractType _contractType, bool _whitelisted ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; interface IYieldGenerator { enum DefiProtocols {AAVE, COMPOUND, YEARN} struct DefiProtocol { uint256 targetAllocation; uint256 currentAllocation; uint256 rebalanceWeight; uint256 depositedAmount; bool whiteListed; bool threshold; bool withdrawMax; } /// @notice deposit stable coin into multiple defi protocols using formulas, access: capital pool /// @param amount uint256 the amount of stable coin to deposit function deposit(uint256 amount) external returns (uint256); /// @notice withdraw stable coin from mulitple defi protocols using formulas, access: capital pool /// @param amount uint256 the amount of stable coin to withdraw function withdraw(uint256 amount) external returns (uint256); /// @notice set the protocol settings for each defi protocol (allocations, whitelisted, threshold), access: owner /// @param whitelisted bool[] list of whitelisted values for each protocol /// @param allocations uint256[] list of allocations value for each protocol /// @param threshold bool[] list of threshold values for each protocol function setProtocolSettings( bool[] calldata whitelisted, uint256[] calldata allocations, bool[] calldata threshold ) external; /// @notice Claims farmed tokens and sends it to the reinsurance pool function claimRewards() external; /// @notice returns defi protocol info by its index /// @param index uint256 the index of the defi protocol function defiProtocol(uint256 index) external view returns (DefiProtocol memory _defiProtocol); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @notice the intention of this library is to be able to easily convert /// one amount of tokens with N decimal places /// to another amount with M decimal places library DecimalsConverter { using SafeMath for uint256; function convert( uint256 amount, uint256 baseDecimals, uint256 destinationDecimals ) internal pure returns (uint256) { if (baseDecimals > destinationDecimals) { amount = amount.div(10**(baseDecimals - destinationDecimals)); } else if (baseDecimals < destinationDecimals) { amount = amount.mul(10**(destinationDecimals - baseDecimals)); } return amount; } function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) { return convert(amount, baseDecimals, 18); } function convertFrom18(uint256 amount, uint256 destinationDecimals) internal pure returns (uint256) { return convert(amount, 18, destinationDecimals); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../GSN/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { 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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @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.7.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../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) { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev 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); } } } }
TODO if user not withdraw the amount after request withdraw , should the amount returned back to capital pool @notice rebalances pools acording to v2 specification and dao enforced policies @dev emits PoolBalancesUpdated
function rebalanceLiquidityCushion() public override broadcastBalancing onlyMaintainer { uint256 _pendingClaimAmount = claimingRegistry.getAllPendingClaimsAmount(); uint256 _pendingWithdrawlAmount = liquidityRegistry.getAllPendingWithdrawalRequestsAmount(); uint256 _requiredLiquidity = _pendingWithdrawlAmount.add(_pendingClaimAmount); _requiredLiquidity = DecimalsConverter.convertFrom18(_requiredLiquidity, stblDecimals); (uint256 _deposit, uint256 _withdraw) = getDepositAndWithdraw(_requiredLiquidity); liquidityCushionBalance = _requiredLiquidity; hardUsdtAccumulatedBalance = 0; uint256 _actualAmount; if (_deposit > 0) { stblToken.safeApprove(address(yieldGenerator), 0); stblToken.safeApprove(address(yieldGenerator), _deposit); _actualAmount = yieldGenerator.deposit(_deposit); if (_actualAmount < _deposit) { hardUsdtAccumulatedBalance += _deposit.sub(_actualAmount); } _actualAmount = yieldGenerator.withdraw(_withdraw); if (_actualAmount < _withdraw) { liquidityCushionBalance -= _withdraw.sub(_actualAmount); } } emit LiquidityCushionRebalanced(_requiredLiquidity, _withdraw, _deposit); }
14,414,565
[ 1, 6241, 309, 729, 486, 598, 9446, 326, 3844, 1839, 590, 598, 9446, 269, 1410, 326, 3844, 2106, 1473, 358, 12872, 2845, 225, 283, 70, 26488, 16000, 279, 4643, 358, 331, 22, 7490, 471, 15229, 570, 19778, 8923, 282, 24169, 8828, 38, 26488, 7381, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 12296, 48, 18988, 24237, 39, 1218, 285, 1435, 1071, 3849, 8959, 38, 16142, 1338, 49, 1598, 1521, 288, 203, 3639, 2254, 5034, 389, 9561, 9762, 6275, 273, 7516, 310, 4243, 18, 588, 1595, 8579, 15925, 6275, 5621, 203, 203, 3639, 2254, 5034, 389, 9561, 1190, 9446, 80, 6275, 273, 203, 5411, 4501, 372, 24237, 4243, 18, 588, 1595, 8579, 1190, 9446, 287, 6421, 6275, 5621, 203, 203, 3639, 2254, 5034, 389, 4718, 48, 18988, 24237, 273, 389, 9561, 1190, 9446, 80, 6275, 18, 1289, 24899, 9561, 9762, 6275, 1769, 203, 203, 3639, 389, 4718, 48, 18988, 24237, 273, 3416, 11366, 5072, 18, 6283, 1265, 2643, 24899, 4718, 48, 18988, 24237, 16, 384, 3083, 31809, 1769, 203, 203, 3639, 261, 11890, 5034, 389, 323, 1724, 16, 2254, 5034, 389, 1918, 9446, 13, 273, 336, 758, 1724, 1876, 1190, 9446, 24899, 4718, 48, 18988, 24237, 1769, 203, 203, 3639, 4501, 372, 24237, 39, 1218, 285, 13937, 273, 389, 4718, 48, 18988, 24237, 31, 203, 203, 3639, 7877, 3477, 7510, 8973, 5283, 690, 13937, 273, 374, 31, 203, 203, 3639, 2254, 5034, 389, 18672, 6275, 31, 203, 3639, 309, 261, 67, 323, 1724, 405, 374, 13, 288, 203, 5411, 384, 3083, 1345, 18, 4626, 12053, 537, 12, 2867, 12, 23604, 3908, 3631, 374, 1769, 203, 5411, 384, 3083, 1345, 18, 4626, 12053, 537, 12, 2867, 12, 23604, 3908, 3631, 389, 323, 1724, 1769, 203, 203, 5411, 389, 18672, 6275, 273, 2824, 3908, 18, 323, 1724, 24899, 323, 1724, 1769, 203, 5411, 309, 261, 67, 2 ]
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ pragma solidity 0.4.24; /// @title GoldenAcre land register Contract /// @author Jeremias Grenzebach, GoldenAcre B.V. /// @dev This contract uses the SQM-token contract (ERC777/ERC20) import { GAccounts } from "./GAccounts.sol"; /* -- External SQM-Token import -- */ // /// @notice importing the Golden Acre token SQM (SquareMetres) contract importToken { function mint(uint256, bytes) public pure { } function burn(uint256, bytes, bytes) public pure { } } contract LandRegister is GAccounts { importToken public sqmToken; uint public numEntries; uint256 public landEntryID; //unique identifier in land register //mapping(uint256 => EntryInLandRegister) landRecords; EntryInLandRegister[] public landRecords; struct EntryInLandRegister { bytes32 entryHash; //Hash über alle untigen Daten string cadastreID; //Katasternummer des Grundstücks uint256 coordinates; // Längen- und Breitengrade: 43.223383, 27.998749 - (zusätzlich verschiedene Systeme, damit zukunftssicher: OpenStreetMap, what3words) uint256 sqmOrSQM; //Quadratmeter des Grundstücks bool ownedByGoldenAcre;// Eigentum von GoldenAcre ja/nein string previousOwner; // Verkäufer an GoldenAcre uint256 dateOfPurchase; //Datum des Kaufs/Verkaufs uint256 dateAddedToRegister; //Datum der Grundbucheintragung string addressOfRegistrationOffice; //Ort des Eintragungsamtes string geohash; // Ein (ipfs-)Link zum PDF des Grundbuchauszuges } /* -- Constructor -- */ // /// @notice Constructor to create Land Register constructor() public { } function () public payable { // fallback function } /** * Add Record * * @param _cadastreID unique identifier from original land register * @param _coordinates geographical center of the land in format: 43.283383, 26.998749 * @param _sqmOrSQM area of the property in square metres * @param _ownedByGoldenAcre - * @param _previousOwner previous owner of the property who sold to goldenAcre B.V. * @param _dateOfPurchase date when GoldenAcre B.V. purchased this land * @param _addressOfRegistrationOffice address where land registry containing this property is based. * @param _geohash jhj * */ function newLandEntry( string _cadastreID, uint256 _coordinates, uint256 _sqmOrSQM, bool _ownedByGoldenAcre, string _previousOwner, uint256 _dateOfPurchase, string _addressOfRegistrationOffice, string _geohash ) public onlyMinter returns (uint256 landID) { landEntryID = landRecords.length++; EntryInLandRegister storage e = landRecords[landEntryID]; e.entryHash = keccak256(abi.encodePacked(_cadastreID, _coordinates, _sqmOrSQM, _ownedByGoldenAcre, _previousOwner, _dateOfPurchase, _addressOfRegistrationOffice, _geohash)); e.cadastreID = _cadastreID; e.coordinates = _coordinates; e.sqmOrSQM = _sqmOrSQM; e.ownedByGoldenAcre = _ownedByGoldenAcre; e.previousOwner = _previousOwner; e.dateOfPurchase = _dateOfPurchase; e.dateAddedToRegister = now; e.addressOfRegistrationOffice = _addressOfRegistrationOffice; e.geohash = _geohash; //ProposalAdded(proposalID, beneficiary, weiAmount, jobDescription); numEntries = landEntryID+1; //sqmToken.mint(_sqmOrSQM, "123"); return landEntryID; } function getLandEntry ( uint256 _landEntryID ) public view returns ( bytes32 entryHash, string cadastreID, uint256 coordinates, uint256 sqmOrSQM, bool ownedByGoldenAcre, string previousOwner, uint256 dateOfPurchase, uint256 dateAddedToRegister, string addressOfRegistrationOffice, string geohash ) { EntryInLandRegister storage e = landRecords[_landEntryID]; entryHash = e.entryHash; cadastreID = e.cadastreID; coordinates = e.coordinates; sqmOrSQM = e.sqmOrSQM; ownedByGoldenAcre = e.ownedByGoldenAcre; previousOwner = e.previousOwner; dateOfPurchase = e.dateOfPurchase; dateAddedToRegister = e.dateAddedToRegister; addressOfRegistrationOffice = e.addressOfRegistrationOffice; geohash = e.geohash; return ( entryHash, cadastreID, coordinates, sqmOrSQM, ownedByGoldenAcre, previousOwner, dateOfPurchase, dateAddedToRegister, addressOfRegistrationOffice, geohash ); } function removeSoldLandEntry( uint256 _landEntryID ) public onlyMinter returns (bool removed) { EntryInLandRegister storage e = landRecords[_landEntryID]; e.ownedByGoldenAcre = false; e.previousOwner = "GoldenAcre"; //ProposalAdded(proposalID, beneficiary, weiAmount, jobDescription); numEntries -= 1; uint256 sqmToRemove = e.sqmOrSQM; e.sqmOrSQM = 0; sqmToken.burn(sqmToRemove, "123", "123"); return true; } /** * Update SQM-token addrress * * @param _newTokenAddress Address of the new SQM-token */ function updateToken(address _newTokenAddress) public onlyOwner { sqmToken = importToken(_newTokenAddress); } }
mapping(uint256 => EntryInLandRegister) landRecords;
contract LandRegister is GAccounts { importToken public sqmToken; uint public numEntries; EntryInLandRegister[] public landRecords; struct EntryInLandRegister { } public constructor() { } function () public payable { } function newLandEntry( string _cadastreID, uint256 _coordinates, uint256 _sqmOrSQM, bool _ownedByGoldenAcre, string _previousOwner, uint256 _dateOfPurchase, string _addressOfRegistrationOffice, string _geohash ) public onlyMinter returns (uint256 landID) { landEntryID = landRecords.length++; EntryInLandRegister storage e = landRecords[landEntryID]; e.entryHash = keccak256(abi.encodePacked(_cadastreID, _coordinates, _sqmOrSQM, _ownedByGoldenAcre, _previousOwner, _dateOfPurchase, _addressOfRegistrationOffice, _geohash)); e.cadastreID = _cadastreID; e.coordinates = _coordinates; e.sqmOrSQM = _sqmOrSQM; e.ownedByGoldenAcre = _ownedByGoldenAcre; e.previousOwner = _previousOwner; e.dateOfPurchase = _dateOfPurchase; e.dateAddedToRegister = now; e.addressOfRegistrationOffice = _addressOfRegistrationOffice; e.geohash = _geohash; numEntries = landEntryID+1; return landEntryID; } function getLandEntry ( uint256 _landEntryID ) public view returns ( bytes32 entryHash, string cadastreID, uint256 coordinates, uint256 sqmOrSQM, bool ownedByGoldenAcre, string previousOwner, uint256 dateOfPurchase, uint256 dateAddedToRegister, string addressOfRegistrationOffice, string geohash ) { EntryInLandRegister storage e = landRecords[_landEntryID]; entryHash = e.entryHash; cadastreID = e.cadastreID; coordinates = e.coordinates; sqmOrSQM = e.sqmOrSQM; ownedByGoldenAcre = e.ownedByGoldenAcre; previousOwner = e.previousOwner; dateOfPurchase = e.dateOfPurchase; dateAddedToRegister = e.dateAddedToRegister; addressOfRegistrationOffice = e.addressOfRegistrationOffice; geohash = e.geohash; return ( entryHash, cadastreID, coordinates, sqmOrSQM, ownedByGoldenAcre, previousOwner, dateOfPurchase, dateAddedToRegister, addressOfRegistrationOffice, geohash ); } function removeSoldLandEntry( uint256 _landEntryID ) public onlyMinter returns (bool removed) { EntryInLandRegister storage e = landRecords[_landEntryID]; e.ownedByGoldenAcre = false; e.previousOwner = "GoldenAcre"; numEntries -= 1; uint256 sqmToRemove = e.sqmOrSQM; e.sqmOrSQM = 0; sqmToken.burn(sqmToRemove, "123", "123"); return true; } function updateToken(address _newTokenAddress) public onlyOwner { sqmToken = importToken(_newTokenAddress); } }
12,959,464
[ 1, 6770, 12, 11890, 5034, 516, 3841, 382, 29398, 3996, 13, 19193, 6499, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 464, 3996, 353, 611, 13971, 288, 203, 377, 203, 565, 1930, 1345, 1071, 4744, 81, 1345, 31, 203, 565, 2254, 1071, 818, 5400, 31, 203, 377, 203, 377, 203, 565, 3841, 382, 29398, 3996, 8526, 1071, 19193, 6499, 31, 203, 377, 203, 565, 1958, 3841, 382, 29398, 3996, 288, 203, 565, 289, 203, 377, 203, 377, 203, 377, 203, 377, 203, 565, 1071, 203, 565, 3885, 1435, 203, 565, 288, 203, 203, 565, 289, 203, 377, 203, 3639, 445, 1832, 7010, 565, 1071, 7010, 565, 8843, 429, 7010, 565, 288, 203, 565, 289, 203, 377, 203, 203, 377, 203, 377, 203, 377, 203, 1377, 203, 565, 445, 394, 29398, 1622, 12, 203, 3639, 533, 389, 71, 361, 689, 266, 734, 16, 203, 3639, 2254, 5034, 389, 16941, 16, 203, 3639, 2254, 5034, 389, 11410, 81, 1162, 55, 53, 49, 16, 203, 3639, 1426, 389, 995, 18696, 43, 1673, 275, 37, 1793, 16, 203, 3639, 533, 389, 11515, 5541, 16, 203, 3639, 2254, 5034, 389, 712, 951, 23164, 16, 203, 3639, 533, 389, 2867, 951, 7843, 30126, 16, 203, 3639, 533, 389, 12376, 2816, 203, 565, 262, 203, 3639, 1071, 1338, 49, 2761, 1135, 261, 11890, 5034, 19193, 734, 13, 203, 565, 288, 203, 3639, 19193, 1622, 734, 273, 19193, 6499, 18, 2469, 9904, 31, 203, 3639, 3841, 382, 29398, 3996, 2502, 425, 273, 19193, 6499, 63, 15733, 1622, 734, 15533, 203, 540, 203, 3639, 425, 18, 4099, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 24899, 71, 361, 2 ]
./full_match/1/0x7109DeEb07aa9Eed1e2613F88b2f3E1e6C05163f/sources/contracts/feeDistributor/OracleFeeDistributor.sol
revert if there is no ether to withdraw
if (balance == 0) { revert FeeDistributor__NothingToWithdraw(); } uint256 halfBalance = balance / 2; emit OracleFeeDistributor__ClientOnlyClRewardsUpdated(s_clientOnlyClRewards); bool someEthSent;
3,156,416
[ 1, 266, 1097, 309, 1915, 353, 1158, 225, 2437, 358, 598, 9446, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 12296, 422, 374, 13, 288, 203, 5411, 15226, 30174, 1669, 19293, 972, 23814, 774, 1190, 9446, 5621, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 8816, 13937, 273, 11013, 342, 576, 31, 203, 203, 203, 203, 203, 3639, 3626, 28544, 14667, 1669, 19293, 972, 1227, 3386, 2009, 17631, 14727, 7381, 12, 87, 67, 2625, 3386, 2009, 17631, 14727, 1769, 203, 203, 3639, 1426, 2690, 41, 451, 7828, 31, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20() public { totalSupply = 80000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = 'LEXIT'; // Set the name for display purposes symbol = 'LXT'; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ 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); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { 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; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { 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; } } /******************************************/ /* LEXIT TOKEN STARTS HERE */ /******************************************/ contract LexitToken is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function LexitToken() TokenERC20() public { } /* Internal transfer, only can be called by this contract */ 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); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } // ------------------------------------------------------------------------ // 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); } }
Public variables of the token 18 decimals is the strongly suggested default, avoid changing it This creates an array with all balances This generates a public event on the blockchain that will notify clients This notifies clients about the amount burnt
contract TokenERC20 { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function TokenERC20() public { } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; Transfer(_from, _to, _value); 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) { 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; 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 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) { Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { Burn(_from, _value); return true; } }
6,933,899
[ 1, 4782, 3152, 434, 326, 1147, 6549, 15105, 353, 326, 11773, 715, 22168, 805, 16, 4543, 12770, 518, 1220, 3414, 392, 526, 598, 777, 324, 26488, 1220, 6026, 279, 1071, 871, 603, 326, 16766, 716, 903, 5066, 7712, 1220, 19527, 7712, 2973, 326, 3844, 18305, 88, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 654, 39, 3462, 288, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 28, 1071, 15105, 273, 6549, 31, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 3155, 654, 39, 3462, 1435, 1071, 288, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 2713, 288, 203, 3639, 2583, 24899, 869, 480, 374, 92, 20, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 2080, 65, 1545, 389, 1132, 1769, 203, 3639, 2583, 12, 12296, 951, 63, 67, 869, 65, 397, 389, 1132, 405, 11013, 951, 63, 67, 869, 19226, 203, 3639, 2254, 2416, 38, 26488, 273, 11013, 951, 63, 67, 2080, 65, 397, 11013, 951, 63, 67, 869, 15533, 203, 3639, 11013, 951, 63, 67, 2080, 65, 3947, 389, 1132, 31, 203, 3639, 11013, 951, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 3639, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 1815, 12, 12296, 951, 63, 67, 2080, 65, 397, 11013, 951, 63, 67, 869, 65, 422, 2416, 2 ]
./full_match/80001/0xFf0c3692eE63916032B68FdA82b8d9b71c30a7D3/sources/contract/Canbeat-Staking/module/Canbeat-Stake-Core.sol
A constant to represent one basis point as a fraction.
uint256 private constant INVERSE_BASIS_POINT = 1000;
858,889
[ 1, 37, 5381, 358, 2406, 1245, 10853, 1634, 487, 279, 8330, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 5381, 2120, 28489, 67, 12536, 15664, 67, 8941, 273, 4336, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.2; interface ILendingPoolAddressesProviderV2 { /** * @notice Get the current address for Aave LendingPool * @dev Lending pool is the core contract on which to call deposit */ function getLendingPool() external view returns (address); } interface IAaveATokenV2 { /** * @notice returns the current total aToken balance of _user all interest collected included. * To obtain the user asset principal balance with interests excluded , ERC20 non-standard * method principalBalanceOf() can be used. */ function balanceOf(address _user) external view returns(uint256); } interface IAaveLendingPoolV2 { /** * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) * is minted. * @param reserve the address of the reserve * @param amount the amount to be deposited * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function deposit( address reserve, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev withdraws the assets of user. * @param reserve the address of the reserve * @param amount the underlying amount to be redeemed * @param to address that will receive the underlying **/ function withdraw( address reserve, uint256 amount, address to ) external; } /** * @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 Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library MassetHelpers { using SafeERC20 for IERC20; function transferReturnBalance( address _sender, address _recipient, address _bAsset, uint256 _qty ) internal returns (uint256 receivedQty, uint256 recipientBalance) { uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient); IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty); recipientBalance = IERC20(_bAsset).balanceOf(_recipient); receivedQty = recipientBalance - balBefore; } function safeInfiniteApprove(address _asset, address _spender) internal { IERC20(_asset).safeApprove(_spender, 0); IERC20(_asset).safeApprove(_spender, 2**256 - 1); } } interface IPlatformIntegration { /** * @dev Deposit the given bAsset to Lending platform * @param _bAsset bAsset address * @param _amount Amount to deposit */ function deposit( address _bAsset, uint256 _amount, bool isTokenFeeCharged ) external returns (uint256 quantityDeposited); /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from the cache */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external; /** * @dev Returns the current balance of the given bAsset */ function checkBalance(address _bAsset) external returns (uint256 balance); /** * @dev Returns the pToken */ function bAssetToPToken(address _bAsset) external returns (address pToken); } 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; } } } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; // keccak256("InterestValidator"); bytes32 internal constant KEY_INTEREST_VALIDATOR = 0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } } 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; } } abstract contract AbstractIntegration is IPlatformIntegration, Initializable, ImmutableModule, ReentrancyGuard { event PTokenAdded(address indexed _bAsset, address _pToken); event Deposit(address indexed _bAsset, address _pToken, uint256 _amount); event Withdrawal(address indexed _bAsset, address _pToken, uint256 _amount); event PlatformWithdrawal(address indexed bAsset, address pToken, uint256 totalAmount, uint256 userAmount); // LP has write access address public immutable lpAddress; // bAsset => pToken (Platform Specific Token Address) mapping(address => address) public override bAssetToPToken; // Full list of all bAssets supported here address[] internal bAssetsMapped; /** * @param _nexus Address of the Nexus * @param _lp Address of LP */ constructor( address _nexus, address _lp ) ReentrancyGuard() ImmutableModule(_nexus) { require(_lp != address(0), "Invalid LP address"); lpAddress = _lp; } /** * @dev Simple initializer to set first bAsset/pTokens */ function initialize( address[] calldata _bAssets, address[] calldata _pTokens ) public initializer { uint256 len = _bAssets.length; require(len == _pTokens.length, "Invalid inputs"); for(uint256 i = 0; i < len; i++){ _setPTokenAddress(_bAssets[i], _pTokens[i]); } } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyLP() { require(msg.sender == lpAddress, "Only the LP can execute"); _; } /*************************************** CONFIG ****************************************/ /** * @dev Provide support for bAsset by passing its pToken address. * This method can only be called by the system Governor * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function setPTokenAddress(address _bAsset, address _pToken) external onlyGovernor { _setPTokenAddress(_bAsset, _pToken); } /** * @dev Provide support for bAsset by passing its pToken address. * Add to internal mappings and execute the platform specific, * abstract method `_abstractSetPToken` * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function _setPTokenAddress(address _bAsset, address _pToken) internal { require(bAssetToPToken[_bAsset] == address(0), "pToken already set"); require(_bAsset != address(0) && _pToken != address(0), "Invalid addresses"); bAssetToPToken[_bAsset] = _pToken; bAssetsMapped.push(_bAsset); emit PTokenAdded(_bAsset, _pToken); _abstractSetPToken(_bAsset, _pToken); } function _abstractSetPToken(address _bAsset, address _pToken) internal virtual; /** * @dev Simple helper func to get the min of two values */ function _min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } } // External // Libs /** * @title AaveV2Integration * @author Stability Labs Pty. Ltd. * @notice A simple connection to deposit and withdraw bAssets from Aave * @dev VERSION: 1.0 * DATE: 2020-16-11 */ contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address */ constructor( address _nexus, address _lp, address _platformAddress ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); // Official checksummed AAVE token address // https://ethplorer.io/address/0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9 address aaveToken = address(0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9); MassetHelpers.safeInfiniteApprove(aaveToken, liquidator); emit RewardTokenApproved(address(aaveToken), liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if(_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if(_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken(address _bAsset, address /*_pToken*/) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } }
* @dev Simple initializer to set first bAsset/pTokens/
function initialize( address[] calldata _bAssets, address[] calldata _pTokens ) public initializer { uint256 len = _bAssets.length; require(len == _pTokens.length, "Invalid inputs"); for(uint256 i = 0; i < len; i++){ _setPTokenAddress(_bAssets[i], _pTokens[i]); } }
6,975,976
[ 1, 5784, 12562, 358, 444, 1122, 324, 6672, 19, 84, 5157, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4046, 12, 203, 3639, 1758, 8526, 745, 892, 389, 70, 10726, 16, 203, 3639, 1758, 8526, 745, 892, 389, 84, 5157, 203, 565, 262, 1071, 12562, 288, 203, 3639, 2254, 5034, 562, 273, 389, 70, 10726, 18, 2469, 31, 203, 3639, 2583, 12, 1897, 422, 389, 84, 5157, 18, 2469, 16, 315, 1941, 4540, 8863, 203, 3639, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 562, 31, 277, 27245, 95, 203, 5411, 389, 542, 52, 1345, 1887, 24899, 70, 10726, 63, 77, 6487, 389, 84, 5157, 63, 77, 19226, 203, 3639, 289, 21281, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/80001/0xC86Be0f94983e5279A6C897a980b72a325b59fC4/sources/MarbleCoin.sol
ERC20 implements the standard ERC20 interface Ownable provides superpowers to the contract deployer AdministratorRole allows for non-owners to be allowed to perform actions on the contract ERC20Detailed adds "name", "symbol", and "decimal" values ERC20Burnable allows for coins to be burned by anyone Defines the initial contract
contract MarbleCoin is ERC20, Ownable, AdministratorRole, ERC20Detailed, ERC20Burnable { bool private _supplycapped = false; uint256 private MBC = 1e18; constructor () public ERC20Detailed("MarbleCoin", "MBC", 18) { } modifier onlyAdministratorOrOwner() { require(isAdministrator(msg.sender) || isOwner()); _; } function addAdministrator(address account) public onlyAdministratorOrOwner { _addAdministrator(account); } function removeAdministrator(address account) public onlyAdministratorOrOwner { _removeAdministrator(account); } function renounceOwnership() public onlyOwner { } bool private _paused; modifier whenNotPaused() { require(!_paused); _; } modifier whenPaused() { require(_paused); _; } function paused() public view returns (bool) { return _paused; } function pause() external onlyAdministratorOrOwner whenNotPaused { _paused = true; } function unpause() public onlyOwner whenPaused { _paused = false; } function transfer(address recipient, uint256 amount) public whenNotPaused returns (bool) { return super.transfer(recipient, amount); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function mint(address account, uint256 amount) public onlyAdministratorOrOwner whenNotPaused returns (bool) { require(totalSupply() + amount > totalSupply(), "Increase in supply would cause overflow."); require(!isSupplyCapped(), "Supply has been capped."); _mint(account, amount); return true; } function freezeMint() public onlyAdministratorOrOwner returns (bool) { _supplycapped = true; return isSupplyCapped(); } function isSupplyCapped() public view returns (bool) { return _supplycapped; } }
8,824,571
[ 1, 654, 39, 3462, 4792, 326, 4529, 4232, 39, 3462, 1560, 14223, 6914, 8121, 2240, 23509, 414, 358, 326, 6835, 7286, 264, 7807, 14207, 2996, 5360, 364, 1661, 17, 995, 414, 358, 506, 2935, 358, 3073, 4209, 603, 326, 6835, 4232, 39, 3462, 40, 6372, 4831, 315, 529, 3113, 315, 7175, 3113, 471, 315, 12586, 6, 924, 4232, 39, 3462, 38, 321, 429, 5360, 364, 276, 9896, 358, 506, 18305, 329, 635, 1281, 476, 18003, 281, 326, 2172, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 490, 6779, 298, 27055, 353, 4232, 39, 3462, 16, 14223, 6914, 16, 7807, 14207, 2996, 16, 4232, 39, 3462, 40, 6372, 16, 4232, 39, 3462, 38, 321, 429, 288, 203, 203, 565, 1426, 3238, 389, 2859, 1283, 5909, 1845, 273, 629, 31, 203, 203, 565, 2254, 5034, 3238, 490, 16283, 273, 404, 73, 2643, 31, 203, 203, 565, 3885, 1832, 1071, 4232, 39, 3462, 40, 6372, 2932, 49, 6779, 298, 27055, 3113, 315, 7969, 39, 3113, 6549, 13, 288, 203, 565, 289, 203, 203, 565, 9606, 1338, 4446, 14207, 1162, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 4446, 14207, 12, 3576, 18, 15330, 13, 747, 353, 5541, 10663, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 527, 4446, 14207, 12, 2867, 2236, 13, 1071, 1338, 4446, 14207, 1162, 5541, 288, 203, 3639, 389, 1289, 4446, 14207, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 1206, 4446, 14207, 12, 2867, 2236, 13, 1071, 1338, 4446, 14207, 1162, 5541, 288, 203, 3639, 389, 4479, 4446, 14207, 12, 4631, 1769, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 565, 289, 203, 203, 203, 203, 565, 1426, 3238, 389, 8774, 3668, 31, 203, 565, 9606, 1347, 1248, 28590, 1435, 288, 203, 3639, 2583, 12, 5, 67, 8774, 3668, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1347, 28590, 1435, 288, 203, 3639, 2583, 24899, 8774, 3668, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 2 ]
./partial_match/56/0xF34CC13cd8a55E1f2DC7E711583b56eb4B6F7C33/sources/POLY.sol
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract POLY is ERC20Interface, Owned, 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 = "POLY"; name = "Poly Swap"; decimals = 8; _totalSupply = 10000000000000000; balances[0x1b5A3388D141654495D432f8A5d894a7b273d0a1] = _totalSupply; emit Transfer(address(0), 0x1b5A3388D141654495D432f8A5d894a7b273d0a1, _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 transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
11,184,052
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 19383, 61, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 14232, 61, 14432, 203, 3639, 508, 273, 315, 12487, 12738, 14432, 203, 3639, 15105, 273, 1725, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 9449, 31, 203, 3639, 324, 26488, 63, 20, 92, 21, 70, 25, 37, 3707, 5482, 40, 3461, 28275, 6334, 8778, 40, 24, 1578, 74, 28, 37, 25, 72, 6675, 24, 69, 27, 70, 5324, 23, 72, 20, 69, 21, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 92, 21, 70, 25, 37, 3707, 5482, 40, 3461, 28275, 6334, 8778, 40, 24, 1578, 74, 28, 37, 25, 72, 6675, 24, 69, 27, 70, 5324, 23, 72, 20, 69, 21, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 2 ]
./partial_match/4/0xA846cEe2AdD3CC7Ea2449B835a8528F3b5E91136/sources/CErc20Delegate.sol
require(msg.sender == admin, "only admin may initialize the market");
function initialize(string memory name_, string memory symbol_, uint8 decimals_) public { require(admin == address(0), "Invalid first initialize"); emit DebugOutX(5, msg.sender); emit DebugOutX(6, admin); admin = msg.sender; name = name_; symbol = symbol_; decimals = decimals_; }
8,587,564
[ 1, 6528, 12, 3576, 18, 15330, 422, 3981, 16, 315, 3700, 3981, 2026, 4046, 326, 13667, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4046, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 16, 2254, 28, 15105, 67, 13, 1071, 288, 203, 540, 203, 3639, 2583, 12, 3666, 422, 1758, 12, 20, 3631, 315, 1941, 1122, 4046, 8863, 203, 3639, 3626, 4015, 1182, 60, 12, 25, 16, 1234, 18, 15330, 1769, 203, 3639, 3626, 4015, 1182, 60, 12, 26, 16, 3981, 1769, 203, 3639, 3981, 273, 1234, 18, 15330, 31, 203, 3639, 508, 273, 508, 67, 31, 203, 3639, 3273, 273, 3273, 67, 31, 203, 3639, 15105, 273, 15105, 67, 31, 203, 565, 289, 203, 203, 7682, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xCA36f9442Df824BcF5fa19F46A96B4034eF420Bd/sources/src/contracts/factory/Factory.sol
mapping between a mint request hash and the corresponding request nonce.
mapping(bytes32 => uint256) public mintRequestNonce;
3,145,795
[ 1, 6770, 3086, 279, 312, 474, 590, 1651, 471, 326, 4656, 590, 7448, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 3890, 1578, 516, 2254, 5034, 13, 1071, 312, 474, 691, 13611, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import {IERC20} from "./interfaces/IERC20.sol"; import {SafeERC20} from "./libraries/SafeERC20.sol"; import {Address} from "./libraries/Address.sol"; import {MultisigUtils} from "./libraries/MultisigUtils.sol"; import {SafeMath} from "./libraries/SafeMath.sol"; contract ForceBridge { using Address for address; using SafeERC20 for IERC20; // refer to https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md uint256 public constant SIGNATURE_SIZE = 65; uint256 public constant VALIDATORS_SIZE_LIMIT = 50; string public constant NAME_712 = "Force Bridge"; // if the number of verified signatures has reached `multisigThreshold_`, validators approve the tx uint256 public multisigThreshold_; address[] validators_; // UNLOCK_TYPEHASH = keccak256("unlock(UnlockRecord[] calldata records)"); bytes32 public constant UNLOCK_TYPEHASH = 0xf1c18f82536658c0cb1a208d4a52b9915dc9e75640ed0daf3a6be45d02ca5c9f; // CHANGE_VALIDATORS_TYPEHASH = keccak256("changeValidators(address[] validators, uint256 multisigThreshold)"); bytes32 public constant CHANGE_VALIDATORS_TYPEHASH = 0xd2cedd075bf1780178b261ac9c9000261e7fd88d66f6309124bddf24f5d953f8; bytes32 private _CACHED_DOMAIN_SEPARATOR; uint256 private _CACHED_CHAIN_ID; bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private _TYPE_HASH; uint256 public latestUnlockNonce_; uint256 public latestChangeValidatorsNonce_; event Locked( address indexed token, address indexed sender, uint256 lockedAmount, bytes recipientLockscript, bytes sudtExtraData ); event Unlocked( address indexed token, address indexed recipient, address indexed sender, uint256 receivedAmount, bytes ckbTxHash ); struct UnlockRecord { address token; address recipient; uint256 amount; bytes ckbTxHash; } constructor(address[] memory validators, uint256 multisigThreshold) { // set DOMAIN_SEPARATOR // refer: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/24a0bc23cfe3fbc76f8f2510b78af1e948ae6651/contracts/utils/cryptography/draft-EIP712.sol bytes32 hashedName = keccak256(bytes(NAME_712)); bytes32 hashedVersion = keccak256(bytes("1")); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = _getChainId(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; // set validators require( validators.length > 0, "validators are none" ); require( multisigThreshold > 0, "invalid multisigThreshold" ); require( validators.length <= VALIDATORS_SIZE_LIMIT, "number of validators exceeds the limit" ); validators_ = validators; require( multisigThreshold <= validators.length, "invalid multisigThreshold" ); multisigThreshold_ = multisigThreshold; } function DOMAIN_SEPARATOR() external view returns (bytes32) { return _domainSeparator(); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparator() internal view virtual returns (bytes32) { if (_getChainId() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, _getChainId(), address(this) ) ); } function _getChainId() private view returns (uint256 chainId) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } function changeValidators( address[] memory validators, uint256 multisigThreshold, uint256 nonce, bytes memory signatures ) public { require(nonce == latestChangeValidatorsNonce_, "changeValidators nonce invalid"); latestChangeValidatorsNonce_ = SafeMath.add(nonce, 1); require( validators.length > 0, "validators are none" ); require( multisigThreshold > 0, "invalid multisigThreshold" ); require( validators.length <= VALIDATORS_SIZE_LIMIT, "number of validators exceeds the limit" ); require( multisigThreshold <= validators.length, "invalid multisigThreshold" ); for (uint256 i = 0; i < validators.length; i++) { for (uint256 j = i + 1; j < validators.length; j ++) { require( validators[i] != validators[j], "repeated validators" ); } } bytes32 msgHash = keccak256( abi.encodePacked( "\x19\x01", // solium-disable-line _domainSeparator(), keccak256( abi.encode( CHANGE_VALIDATORS_TYPEHASH, validators, multisigThreshold, nonce ) ) ) ); validatorsApprove(msgHash, signatures, multisigThreshold_); validators_ = validators; multisigThreshold_ = multisigThreshold; } /** * @notice if addr is not one of validators_, return validators_.length * @return index of addr in validators_ */ function _getIndexOfValidators(address user) internal view returns (uint256) { for (uint256 i = 0; i < validators_.length; i++) { if (validators_[i] == user) { return i; } } return validators_.length; } /** * @notice @dev signatures are a multiple of 65 bytes and are densely packed. * @param signatures The signatures bytes array */ function validatorsApprove( bytes32 msgHash, bytes memory signatures, uint256 threshold ) public view { require(signatures.length % SIGNATURE_SIZE == 0, "invalid signatures"); // 1. check length of signature uint256 length = signatures.length / SIGNATURE_SIZE; require( length >= threshold, "length of signatures must greater than threshold" ); // 3. check number of verified signatures >= threshold uint256 verifiedNum = 0; uint256 i = 0; uint8 v; bytes32 r; bytes32 s; address recoveredAddress; // set indexVisited[ index of recoveredAddress in validators_ ] = true bool[] memory validatorIndexVisited = new bool[](validators_.length); uint256 validatorIndex; while (i < length) { (v, r, s) = MultisigUtils.parseSignature(signatures, i); i++; recoveredAddress = ecrecover(msgHash, v, r, s); require(recoveredAddress != address(0), "invalid signature"); // get index of recoveredAddress in validators_ validatorIndex = _getIndexOfValidators(recoveredAddress); // recoveredAddress is not validator or has been visited if ( validatorIndex >= validators_.length || validatorIndexVisited[validatorIndex] ) { continue; } // recoveredAddress verified validatorIndexVisited[validatorIndex] = true; verifiedNum++; if (verifiedNum >= threshold) { return; } } require(verifiedNum >= threshold, "signatures not verified"); } function unlock(UnlockRecord[] calldata records, uint256 nonce, bytes calldata signatures) public { // check nonce hasn't been used require(latestUnlockNonce_ == nonce, "unlock nonce invalid"); latestUnlockNonce_ = SafeMath.add(nonce, 1); // 1. calc msgHash bytes32 msgHash = keccak256( abi.encodePacked( "\x19\x01", // solium-disable-line _domainSeparator(), keccak256(abi.encode(UNLOCK_TYPEHASH, records, nonce)) ) ); validatorsApprove(msgHash, signatures, multisigThreshold_); for (uint256 i = 0; i < records.length; i++) { UnlockRecord calldata r = records[i]; if (r.amount == 0) continue; if (r.token == address(0)) { payable(r.recipient).transfer(r.amount); } else { IERC20(r.token).safeTransfer(r.recipient, r.amount); } emit Unlocked( r.token, r.recipient, msg.sender, r.amount, r.ckbTxHash ); } } function lockETH( bytes memory recipientLockscript, bytes memory sudtExtraData ) public payable { emit Locked( address(0), msg.sender, msg.value, recipientLockscript, sudtExtraData ); } // before lockToken, user should approve -> TokenLocker Contract with 0xffffff token function lockToken( address token, uint256 amount, bytes memory recipientLockscript, bytes memory sudtExtraData ) public { IERC20(token).safeTransferFrom(msg.sender, address(this), amount); emit Locked( token, msg.sender, amount, recipientLockscript, sudtExtraData ); } }
* @notice if addr is not one of validators_, return validators_.length @return index of addr in validators_/
function _getIndexOfValidators(address user) internal view returns (uint256) { for (uint256 i = 0; i < validators_.length; i++) { if (validators_[i] == user) { return i; } } return validators_.length; }
6,406,800
[ 1, 430, 3091, 353, 486, 1245, 434, 11632, 67, 16, 327, 11632, 27799, 2469, 327, 225, 770, 434, 3091, 316, 11632, 67, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 31985, 19420, 12, 2867, 729, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 11632, 27799, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 23993, 67, 63, 77, 65, 422, 729, 13, 288, 203, 7734, 327, 277, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 11632, 27799, 2469, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; import "../libraries/Address.sol"; contract RevertFallback { function() public payable { revert(); } function receiveEth() public payable { // solhint-disable-previous-line no-empty-blocks } function sendEth(address _receiver, uint256 _value) public { // solhint-disable-next-line check-send-result require(_receiver.send(_value)); } function safeSendEth(address _receiver, uint256 _value) public { Address.safeSendValue(_receiver, _value); } }
solhint-disable-previous-line no-empty-blocks
function receiveEth() public payable { }
12,854,665
[ 1, 18281, 11317, 17, 8394, 17, 11515, 17, 1369, 1158, 17, 5531, 17, 7996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6798, 41, 451, 1435, 1071, 8843, 429, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; import "@c-layer/common/contracts/operable/Operable.sol"; import "@c-layer/common/contracts/lifecycle/Pausable.sol"; import "../interface/ITokensale.sol"; /** * @title BaseTokensale * @dev Base Tokensale contract * * @author Cyril Lapinte - <cyril.lapinte@openfiz.com> * SPDX-License-Identifier: MIT * * Error messages * TOS01: token price must be strictly positive * TOS02: price unit must be strictly positive * TOS03: Token transfer must be successfull * TOS04: No ETH to refund * TOS05: Cannot invest 0 tokens * TOS06: Cannot invest if there are no tokens to buy * TOS07: Only exact amount is authorized */ contract BaseTokensale is ITokensale, Operable, Pausable { /* General sale details */ IERC20 internal token_; address payable internal vaultETH_; address internal vaultERC20_; uint256 internal tokenPrice_; uint256 internal priceUnit_; uint256 internal totalRaised_; uint256 internal totalTokensSold_; uint256 internal totalUnspentETH_; uint256 internal totalRefundedETH_; struct Investor { uint256 unspentETH; uint256 invested; uint256 tokens; } mapping(address => Investor) internal investors; /** * @dev constructor */ constructor( IERC20 _token, address _vaultERC20, address payable _vaultETH, uint256 _tokenPrice, uint256 _priceUnit ) { require(_tokenPrice > 0, "TOS01"); require(_priceUnit > 0, "TOS02"); token_ = _token; vaultERC20_ = _vaultERC20; vaultETH_ = _vaultETH; tokenPrice_ = _tokenPrice; priceUnit_ = _priceUnit; } /** * @dev fallback function */ //solhint-disable-next-line no-complex-fallback receive() external override payable { investETH(); } /* Investment */ function investETH() public virtual override payable { Investor storage investor = investorInternal(msg.sender); uint256 amountETH = investor.unspentETH + msg.value; investInternal(msg.sender, amountETH, false); } /** * @dev returns the token sold */ function token() public override view returns (IERC20) { return token_; } /** * @dev returns the vault use to */ function vaultETH() public override view returns (address) { return vaultETH_; } /** * @dev returns the vault to receive ETH */ function vaultERC20() public override view returns (address) { return vaultERC20_; } /** * @dev returns token price */ function tokenPrice() public override view returns (uint256) { return tokenPrice_; } /** * @dev returns price unit */ function priceUnit() public override view returns (uint256) { return priceUnit_; } /** * @dev returns total raised */ function totalRaised() public override view returns (uint256) { return totalRaised_; } /** * @dev returns total tokens sold */ function totalTokensSold() public override view returns (uint256) { return totalTokensSold_; } /** * @dev returns total unspent ETH */ function totalUnspentETH() public override view returns (uint256) { return totalUnspentETH_; } /** * @dev returns total refunded ETH */ function totalRefundedETH() public override view returns (uint256) { return totalRefundedETH_; } /** * @dev returns the available supply */ function availableSupply() public override view returns (uint256) { uint256 vaultSupply = token_.balanceOf(vaultERC20_); uint256 allowance = token_.allowance(vaultERC20_, address(this)); return (vaultSupply < allowance) ? vaultSupply : allowance; } /* Investor specific attributes */ function investorUnspentETH(address _investor) public override view returns (uint256) { return investorInternal(_investor).unspentETH; } function investorInvested(address _investor) public override view returns (uint256) { return investorInternal(_investor).invested; } function investorTokens(address _investor) public override view returns (uint256) { return investorInternal(_investor).tokens; } /** * @dev tokenInvestment */ function tokenInvestment(address, uint256 _amount) public virtual override view returns (uint256) { uint256 availableSupplyValue = availableSupply(); uint256 contribution = _amount * priceUnit_ / tokenPrice_; return (contribution < availableSupplyValue) ? contribution : availableSupplyValue; } /** * @dev refund unspentETH ETH many */ function refundManyUnspentETH(address payable[] memory _receivers) public override onlyOperator returns (bool) { for (uint256 i = 0; i < _receivers.length; i++) { refundUnspentETHInternal(_receivers[i]); } return true; } /** * @dev refund unspentETH */ function refundUnspentETH() public override returns (bool) { refundUnspentETHInternal(payable(msg.sender)); return true; } /** * @dev withdraw all ETH funds */ function withdrawAllETHFunds() public override onlyOperator returns (bool) { uint256 balance = address(this).balance; withdrawETHInternal(balance); return true; } /** * @dev fund ETH */ function fundETH() public override payable onlyOperator { emit FundETH(msg.value); } /** * @dev investor internal */ function investorInternal(address _investor) internal virtual view returns (Investor storage) { return investors[_investor]; } /** * @dev eval unspent ETH internal */ function evalUnspentETHInternal( Investor storage _investor, uint256 _investedETH ) internal virtual view returns (uint256) { return _investor.unspentETH + msg.value - _investedETH; } /** * @dev eval investment internal */ function evalInvestmentInternal(uint256 _tokens) internal virtual view returns (uint256, uint256) { uint256 invested = _tokens * tokenPrice_ / priceUnit_; return (invested, _tokens); } /** * @dev distribute tokens internal */ function distributeTokensInternal(address _investor, uint256 _tokens) internal virtual { require( token_.transferFrom(vaultERC20_, _investor, _tokens), "TOS03"); } /** * @dev refund unspentETH internal */ function refundUnspentETHInternal(address payable _investor) internal virtual { Investor storage investor = investorInternal(_investor); require(investor.unspentETH > 0, "TOS04"); uint256 unspentETH = investor.unspentETH; totalRefundedETH_ = totalRefundedETH_ + unspentETH; totalUnspentETH_ = totalUnspentETH_ - unspentETH; investor.unspentETH = 0; // Multiple sends are required for refundManyUnspentETH // solhint-disable-next-line multiple-sends _investor.transfer(unspentETH); emit RefundETH(_investor, unspentETH); } /** * @dev withdraw ETH internal */ function withdrawETHInternal(uint256 _amount) internal virtual { // Send is used after the ERC20 transfer // solhint-disable-next-line multiple-sends vaultETH_.transfer(_amount); emit WithdrawETH(_amount); } /** * @dev invest internal */ function investInternal(address _investor, uint256 _amount, bool _exactAmountOnly) internal virtual whenNotPaused { require(_amount != 0, "TOS05"); Investor storage investor = investorInternal(_investor); uint256 investment = tokenInvestment(_investor, _amount); require(investment != 0, "TOS06"); (uint256 invested, uint256 tokens) = evalInvestmentInternal(investment); if (_exactAmountOnly) { require(invested == _amount, "TOS07"); } else { uint256 unspentETH = evalUnspentETHInternal(investor, invested); totalUnspentETH_ = totalUnspentETH_ - investor.unspentETH + unspentETH; investor.unspentETH = unspentETH; } investor.invested = investor.invested + invested; investor.tokens = investor.tokens + tokens; totalRaised_ = totalRaised_ + invested; totalTokensSold_ = totalTokensSold_ + tokens; emit Investment(_investor, invested, tokens); /* Reentrancy risks: No state change must come below */ distributeTokensInternal(_investor, tokens); uint256 balance = address(this).balance; uint256 withdrawableETH = balance - totalUnspentETH_; if (withdrawableETH != 0) { withdrawETHInternal(withdrawableETH); } } }
* @dev returns the token sold/
function token() public override view returns (IERC20) { return token_; }
2,531,938
[ 1, 6154, 326, 1147, 272, 1673, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1147, 1435, 1071, 3849, 1476, 1135, 261, 45, 654, 39, 3462, 13, 288, 203, 565, 327, 1147, 67, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; import "./Payables.sol"; library IssuanceProperty { //enum definition // Solidity enum definitions enum IssuanceState { IssuanceStateUnknown, Initiated, Engageable, Cancelled, Complete } // Solidity enum encoder function encode_IssuanceState(IssuanceState x) internal pure returns (int64) { if (x == IssuanceState.IssuanceStateUnknown) { return 0; } if (x == IssuanceState.Initiated) { return 1; } if (x == IssuanceState.Engageable) { return 2; } if (x == IssuanceState.Cancelled) { return 3; } if (x == IssuanceState.Complete) { return 4; } revert(); } // Solidity enum decoder function decode_IssuanceState(int64 x) internal pure returns (IssuanceState) { if (x == 0) { return IssuanceState.IssuanceStateUnknown; } if (x == 1) { return IssuanceState.Initiated; } if (x == 2) { return IssuanceState.Engageable; } if (x == 3) { return IssuanceState.Cancelled; } if (x == 4) { return IssuanceState.Complete; } revert(); } //struct definition struct Data { uint256 issuanceId; uint256 instrumentId; address makerAddress; address issuanceAddress; address issuanceEscrowAddress; uint256 issuanceCreationTimestamp; uint256 issuanceDueTimestamp; uint256 issuanceCancelTimestamp; uint256 issuanceCompleteTimestamp; uint256 completionRatio; IssuanceProperty.IssuanceState issuanceState; bytes issuanceCustomProperty; EngagementProperty.Data[] engagements; Payable.Data[] payables; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[15] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_issuanceId(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_instrumentId(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_makerAddress(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_issuanceAddress(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_issuanceEscrowAddress(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_issuanceCreationTimestamp(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_issuanceDueTimestamp(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_issuanceCancelTimestamp(pointer, bs, r, counters); } else if (fieldId == 9) { pointer += _read_issuanceCompleteTimestamp(pointer, bs, r, counters); } else if (fieldId == 10) { pointer += _read_completionRatio(pointer, bs, r, counters); } else if (fieldId == 11) { pointer += _read_issuanceState(pointer, bs, r, counters); } else if (fieldId == 12) { pointer += _read_issuanceCustomProperty(pointer, bs, r, counters); } else if (fieldId == 13) { pointer += _read_engagements(pointer, bs, nil(), counters); } else if (fieldId == 14) { pointer += _read_payables(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.engagements = new EngagementProperty.Data[](counters[13]); r.payables = new Payable.Data[](counters[14]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_issuanceId(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_instrumentId(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_makerAddress(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_issuanceAddress(pointer, bs, nil(), counters); } else if (fieldId == 5) { pointer += _read_issuanceEscrowAddress(pointer, bs, nil(), counters); } else if (fieldId == 6) { pointer += _read_issuanceCreationTimestamp(pointer, bs, nil(), counters); } else if (fieldId == 7) { pointer += _read_issuanceDueTimestamp(pointer, bs, nil(), counters); } else if (fieldId == 8) { pointer += _read_issuanceCancelTimestamp(pointer, bs, nil(), counters); } else if (fieldId == 9) { pointer += _read_issuanceCompleteTimestamp(pointer, bs, nil(), counters); } else if (fieldId == 10) { pointer += _read_completionRatio(pointer, bs, nil(), counters); } else if (fieldId == 11) { pointer += _read_issuanceState(pointer, bs, nil(), counters); } else if (fieldId == 12) { pointer += _read_issuanceCustomProperty(pointer, bs, nil(), counters); } else if (fieldId == 13) { pointer += _read_engagements(pointer, bs, r, counters); } else if (fieldId == 14) { pointer += _read_payables(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_issuanceId( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.issuanceId = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_instrumentId( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.instrumentId = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_makerAddress( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.makerAddress = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_issuanceAddress( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.issuanceAddress = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_issuanceEscrowAddress( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.issuanceEscrowAddress = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_issuanceCreationTimestamp( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.issuanceCreationTimestamp = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_issuanceDueTimestamp( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[7] += 1; } else { r.issuanceDueTimestamp = x; if (counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_issuanceCancelTimestamp( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.issuanceCancelTimestamp = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_issuanceCompleteTimestamp( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[9] += 1; } else { r.issuanceCompleteTimestamp = x; if (counters[9] > 0) counters[9] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_completionRatio( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[10] += 1; } else { r.completionRatio = x; if (counters[10] > 0) counters[10] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_issuanceState( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); IssuanceProperty.IssuanceState x = decode_IssuanceState(tmp); if (isNil(r)) { counters[11] += 1; } else { r.issuanceState = x; if(counters[11] > 0) counters[11] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_issuanceCustomProperty( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[12] += 1; } else { r.issuanceCustomProperty = x; if (counters[12] > 0) counters[12] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_engagements( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (EngagementProperty.Data memory x, uint256 sz) = _decode_EngagementProperty(p, bs); if (isNil(r)) { counters[13] += 1; } else { r.engagements[r.engagements.length - counters[13]] = x; if (counters[13] > 0) counters[13] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_payables( uint256 p, bytes memory bs, Data memory r, uint[15] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (Payable.Data memory x, uint256 sz) = _decode_Payable(p, bs); if (isNil(r)) { counters[14] += 1; } else { r.payables[r.payables.length - counters[14]] = x; if (counters[14] > 0) counters[14] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_EngagementProperty(uint256 p, bytes memory bs) internal pure returns (EngagementProperty.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (EngagementProperty.Data memory r, ) = EngagementProperty._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_Payable(uint256 p, bytes memory bs) internal pure returns (Payable.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (Payable.Data memory r, ) = Payable._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.issuanceId, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.instrumentId, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.makerAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.issuanceAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.issuanceEscrowAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.issuanceCreationTimestamp, pointer, bs); pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.issuanceDueTimestamp, pointer, bs); pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.issuanceCancelTimestamp, pointer, bs); pointer += ProtoBufRuntime._encode_key( 9, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.issuanceCompleteTimestamp, pointer, bs); pointer += ProtoBufRuntime._encode_key( 10, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.completionRatio, pointer, bs); pointer += ProtoBufRuntime._encode_key( 11, ProtoBufRuntime.WireType.Varint, pointer, bs ); int64 _enum_issuanceState = encode_IssuanceState(r.issuanceState); pointer += ProtoBufRuntime._encode_enum(_enum_issuanceState, pointer, bs); pointer += ProtoBufRuntime._encode_key( 12, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.issuanceCustomProperty, pointer, bs); for(i = 0; i < r.engagements.length; i++) { pointer += ProtoBufRuntime._encode_key( 13, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += EngagementProperty._encode_nested(r.engagements[i], pointer, bs); } for(i = 0; i < r.payables.length; i++) { pointer += ProtoBufRuntime._encode_key( 14, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += Payable._encode_nested(r.payables[i], pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + 35; e += 1 + 35; e += 1 + 23; e += 1 + 23; e += 1 + 23; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + ProtoBufRuntime._sz_enum(encode_IssuanceState(r.issuanceState)); e += 1 + ProtoBufRuntime._sz_lendelim(r.issuanceCustomProperty.length); for(i = 0; i < r.engagements.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(EngagementProperty._estimate(r.engagements[i])); } for(i = 0; i < r.payables.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(Payable._estimate(r.payables[i])); } return e; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.issuanceId = input.issuanceId; output.instrumentId = input.instrumentId; output.makerAddress = input.makerAddress; output.issuanceAddress = input.issuanceAddress; output.issuanceEscrowAddress = input.issuanceEscrowAddress; output.issuanceCreationTimestamp = input.issuanceCreationTimestamp; output.issuanceDueTimestamp = input.issuanceDueTimestamp; output.issuanceCancelTimestamp = input.issuanceCancelTimestamp; output.issuanceCompleteTimestamp = input.issuanceCompleteTimestamp; output.completionRatio = input.completionRatio; output.issuanceState = input.issuanceState; output.issuanceCustomProperty = input.issuanceCustomProperty; for(uint256 i13 = 0; i13 < input.engagements.length; i13++) { output.engagements.push(input.engagements[i13]); } for(uint256 i14 = 0; i14 < input.payables.length; i14++) { output.payables.push(input.payables[i14]); } } //array helpers for Engagements /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addEngagements(Data memory self, EngagementProperty.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ EngagementProperty.Data[] memory tmp = new EngagementProperty.Data[](self.engagements.length + 1); for (uint256 i = 0; i < self.engagements.length; i++) { tmp[i] = self.engagements[i]; } tmp[self.engagements.length] = value; self.engagements = tmp; } //array helpers for Payables /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addPayables(Data memory self, Payable.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ Payable.Data[] memory tmp = new Payable.Data[](self.payables.length + 1); for (uint256 i = 0; i < self.payables.length; i++) { tmp[i] = self.payables[i]; } tmp[self.payables.length] = value; self.payables = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library IssuanceProperty library EngagementProperty { //enum definition // Solidity enum definitions enum EngagementState { EngagementStateUnknown, Initiated, Active, Cancelled, Complete } // Solidity enum encoder function encode_EngagementState(EngagementState x) internal pure returns (int64) { if (x == EngagementState.EngagementStateUnknown) { return 0; } if (x == EngagementState.Initiated) { return 1; } if (x == EngagementState.Active) { return 2; } if (x == EngagementState.Cancelled) { return 3; } if (x == EngagementState.Complete) { return 4; } revert(); } // Solidity enum decoder function decode_EngagementState(int64 x) internal pure returns (EngagementState) { if (x == 0) { return EngagementState.EngagementStateUnknown; } if (x == 1) { return EngagementState.Initiated; } if (x == 2) { return EngagementState.Active; } if (x == 3) { return EngagementState.Cancelled; } if (x == 4) { return EngagementState.Complete; } revert(); } //struct definition struct Data { uint256 engagementId; address takerAddress; uint256 engagementCreationTimestamp; uint256 engagementDueTimestamp; uint256 engagementCancelTimestamp; uint256 engagementCompleteTimestamp; EngagementProperty.EngagementState engagementState; bytes engagementCustomProperty; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[9] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_engagementId(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_takerAddress(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_engagementCreationTimestamp(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_engagementDueTimestamp(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_engagementCancelTimestamp(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_engagementCompleteTimestamp(pointer, bs, r, counters); } else if (fieldId == 7) { pointer += _read_engagementState(pointer, bs, r, counters); } else if (fieldId == 8) { pointer += _read_engagementCustomProperty(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_engagementId( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.engagementId = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_takerAddress( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (address x, uint256 sz) = ProtoBufRuntime._decode_sol_address(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.takerAddress = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_engagementCreationTimestamp( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.engagementCreationTimestamp = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_engagementDueTimestamp( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.engagementDueTimestamp = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_engagementCancelTimestamp( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.engagementCancelTimestamp = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_engagementCompleteTimestamp( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (uint256 x, uint256 sz) = ProtoBufRuntime._decode_sol_uint256(p, bs); if (isNil(r)) { counters[6] += 1; } else { r.engagementCompleteTimestamp = x; if (counters[6] > 0) counters[6] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_engagementState( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); EngagementProperty.EngagementState x = decode_EngagementState(tmp); if (isNil(r)) { counters[7] += 1; } else { r.engagementState = x; if(counters[7] > 0) counters[7] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_engagementCustomProperty( uint256 p, bytes memory bs, Data memory r, uint[9] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[8] += 1; } else { r.engagementCustomProperty = x; if (counters[8] > 0) counters[8] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.engagementId, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_address(r.takerAddress, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.engagementCreationTimestamp, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.engagementDueTimestamp, pointer, bs); pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.engagementCancelTimestamp, pointer, bs); pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_sol_uint256(r.engagementCompleteTimestamp, pointer, bs); pointer += ProtoBufRuntime._encode_key( 7, ProtoBufRuntime.WireType.Varint, pointer, bs ); int64 _enum_engagementState = encode_EngagementState(r.engagementState); pointer += ProtoBufRuntime._encode_enum(_enum_engagementState, pointer, bs); pointer += ProtoBufRuntime._encode_key( 8, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.engagementCustomProperty, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + 35; e += 1 + 23; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + 35; e += 1 + ProtoBufRuntime._sz_enum(encode_EngagementState(r.engagementState)); e += 1 + ProtoBufRuntime._sz_lendelim(r.engagementCustomProperty.length); return e; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.engagementId = input.engagementId; output.takerAddress = input.takerAddress; output.engagementCreationTimestamp = input.engagementCreationTimestamp; output.engagementDueTimestamp = input.engagementDueTimestamp; output.engagementCancelTimestamp = input.engagementCancelTimestamp; output.engagementCompleteTimestamp = input.engagementCompleteTimestamp; output.engagementState = input.engagementState; output.engagementCustomProperty = input.engagementCustomProperty; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library EngagementProperty
Solidity enum decoder
function decode_IssuanceState(int64 x) internal pure returns (IssuanceState) { if (x == 0) { return IssuanceState.IssuanceStateUnknown; } if (x == 1) { return IssuanceState.Initiated; } if (x == 2) { return IssuanceState.Engageable; } if (x == 3) { return IssuanceState.Cancelled; } if (x == 4) { return IssuanceState.Complete; } revert(); }
12,793,047
[ 1, 25044, 560, 2792, 8320, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2495, 67, 7568, 89, 1359, 1119, 12, 474, 1105, 619, 13, 2713, 16618, 1135, 261, 7568, 89, 1359, 1119, 13, 288, 203, 377, 203, 565, 309, 261, 92, 422, 374, 13, 288, 203, 1377, 327, 9310, 89, 1359, 1119, 18, 7568, 89, 1359, 1119, 4874, 31, 203, 565, 289, 203, 203, 565, 309, 261, 92, 422, 404, 13, 288, 203, 1377, 327, 9310, 89, 1359, 1119, 18, 2570, 10206, 31, 203, 565, 289, 203, 203, 565, 309, 261, 92, 422, 576, 13, 288, 203, 1377, 327, 9310, 89, 1359, 1119, 18, 28429, 410, 429, 31, 203, 565, 289, 203, 203, 565, 309, 261, 92, 422, 890, 13, 288, 203, 1377, 327, 9310, 89, 1359, 1119, 18, 21890, 31, 203, 565, 289, 203, 203, 565, 309, 261, 92, 422, 1059, 13, 288, 203, 1377, 327, 9310, 89, 1359, 1119, 18, 6322, 31, 203, 565, 289, 203, 565, 15226, 5621, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x33Dbb0593D394b84bad7EBC49acacd2c5D12CABe/sources/contracts/opensea/ERC1155Tradable.sol
* @dev Will update the base URL of token's URI @param _newBaseMetadataURI New base URL of token's URI/
function setBaseMetadataURI( string memory _newBaseMetadataURI ) public onlyRole(DEFAULT_ADMIN_ROLE) { _setBaseMetadataURI(_newBaseMetadataURI); }
4,440,100
[ 1, 13670, 1089, 326, 1026, 1976, 434, 1147, 1807, 3699, 225, 389, 2704, 2171, 2277, 3098, 1166, 1026, 1976, 434, 1147, 1807, 3699, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 26435, 2277, 3098, 12, 203, 565, 533, 3778, 389, 2704, 2171, 2277, 3098, 203, 225, 262, 1071, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 288, 203, 565, 389, 542, 2171, 2277, 3098, 24899, 2704, 2171, 2277, 3098, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "../components/Governance.sol"; import "../components/GovernanceStorage.sol"; /** The Proxy contract is governed by one or more Governors of which the initial one is the deployer of the contract. A governor has the sole authority to perform the following operations: 1. Nominate additional governors (:sol:func:`proxyNominateNewGovernor`) 2. Remove other governors (:sol:func:`proxyRemoveGovernor`) 3. Add new `implementations` (proxied contracts) 4. Remove (new or old) `implementations` 5. Update `implementations` after a timelock allows it Adding governors is performed in a two step procedure: 1. First, an existing governor nominates a new governor (:sol:func:`proxyNominateNewGovernor`) 2. Then, the new governor must accept governance to become a governor (:sol:func:`proxyAcceptGovernance`) This two step procedure ensures that a governor public key cannot be nominated unless there is an entity that has the corresponding private key. This is intended to prevent errors in the addition process. The governor private key should typically be held in a secure cold wallet or managed via a multi-sig contract. */ /* Implements Governance for the proxy contract. It is a thin wrapper to the Governance contract, which is needed so that it can have non-colliding function names, and a specific tag (key) to allow unique state storage. */ contract ProxyGovernance is GovernanceStorage, Governance { // The tag is the string key that is used in the Governance storage mapping. string public constant PROXY_GOVERNANCE_TAG = "StarkEx.Proxy.2019.GovernorsInformation"; /* Returns the GovernanceInfoStruct associated with the governance tag. */ function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage) { return governanceInfo[PROXY_GOVERNANCE_TAG]; } function proxyIsGovernor(address testGovernor) external view returns (bool) { return _isGovernor(testGovernor); } function proxyNominateNewGovernor(address newGovernor) external { _nominateNewGovernor(newGovernor); } function proxyRemoveGovernor(address governorForRemoval) external { _removeGovernor(governorForRemoval); } function proxyAcceptGovernance() external { _acceptGovernance(); } function proxyCancelNomination() external { _cancelNomination(); } }
/ The tag is the string key that is used in the Governance storage mapping.
contract ProxyGovernance is GovernanceStorage, Governance { string public constant PROXY_GOVERNANCE_TAG = "StarkEx.Proxy.2019.GovernorsInformation"; Returns the GovernanceInfoStruct associated with the governance tag. pragma solidity ^0.6.12; The Proxy contract is governed by one or more Governors of which the initial one is the Implements Governance for the proxy contract. which is needed so that it can have non-colliding function names, and a specific tag (key) to allow unique state storage. function getGovernanceInfo() internal view override returns (GovernanceInfoStruct storage) { return governanceInfo[PROXY_GOVERNANCE_TAG]; } function proxyIsGovernor(address testGovernor) external view returns (bool) { return _isGovernor(testGovernor); } function proxyNominateNewGovernor(address newGovernor) external { _nominateNewGovernor(newGovernor); } function proxyRemoveGovernor(address governorForRemoval) external { _removeGovernor(governorForRemoval); } function proxyAcceptGovernance() external { _acceptGovernance(); } function proxyCancelNomination() external { _cancelNomination(); } }
12,985,598
[ 1, 19, 1021, 1047, 353, 326, 533, 498, 716, 353, 1399, 316, 326, 611, 1643, 82, 1359, 2502, 2874, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7659, 43, 1643, 82, 1359, 353, 611, 1643, 82, 1359, 3245, 16, 611, 1643, 82, 1359, 288, 203, 565, 533, 1071, 5381, 26910, 67, 43, 12959, 50, 4722, 67, 7927, 273, 315, 510, 1313, 424, 18, 3886, 18, 6734, 29, 18, 43, 1643, 82, 1383, 5369, 14432, 203, 203, 1377, 2860, 326, 611, 1643, 82, 1359, 966, 3823, 3627, 598, 326, 314, 1643, 82, 1359, 1047, 18, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 2138, 31, 203, 225, 1021, 7659, 6835, 353, 314, 1643, 11748, 635, 1245, 578, 1898, 611, 1643, 82, 1383, 434, 1492, 326, 2172, 1245, 353, 326, 203, 225, 29704, 611, 1643, 82, 1359, 364, 326, 2889, 6835, 18, 203, 225, 1492, 353, 3577, 1427, 716, 518, 848, 1240, 1661, 17, 12910, 10415, 445, 1257, 16, 203, 225, 471, 279, 2923, 1047, 261, 856, 13, 358, 1699, 3089, 919, 2502, 18, 203, 565, 445, 7162, 1643, 82, 1359, 966, 1435, 2713, 1476, 3849, 1135, 261, 43, 1643, 82, 1359, 966, 3823, 2502, 13, 288, 203, 3639, 327, 314, 1643, 82, 1359, 966, 63, 16085, 67, 43, 12959, 50, 4722, 67, 7927, 15533, 203, 565, 289, 203, 203, 565, 445, 2889, 2520, 43, 1643, 29561, 12, 2867, 1842, 43, 1643, 29561, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 291, 43, 1643, 29561, 12, 3813, 43, 1643, 29561, 1769, 203, 565, 289, 203, 203, 565, 445, 2889, 26685, 3322, 1908, 43, 1643, 29561, 12, 2867, 394, 43, 1643, 29561, 13, 3903, 288, 203, 3639, 2 ]
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } contract Time { /** * @dev Current time getter * @return Current time in seconds */ function _currentTime() internal view returns (uint256) { return block.timestamp; } } /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) view public { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) view public returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Lockable { // locked values specified by address mapping(address => uint256) public lockedValues; /** * @dev Method to lock specified value by specified address * @param _for Address for which the value will be locked * @param _value Value that be locked */ function _lock(address _for, uint256 _value) internal { require(_for != address(0) && _value > 0, "Invalid lock operation configuration."); if (_value != lockedValues[_for]) { lockedValues[_for] = _value; } } /** * @dev Method to unlock (reset) locked value * @param _for Address for which the value will be unlocked */ function _unlock(address _for) internal { require(_for != address(0), "Invalid unlock operation configuration."); if (lockedValues[_for] != 0) { lockedValues[_for] = 0; } } } contract Operable is Ownable, RBAC { // role key string public constant ROLE_OPERATOR = "operator"; /** * @dev Reverts in case account is not Owner or Operator role */ modifier hasOwnerOrOperatePermission() { require(msg.sender == owner || hasRole(msg.sender, ROLE_OPERATOR), "Access denied."); _; } /** * @dev Getter to determine if address is in whitelist */ function operator(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_OPERATOR); } /** * @dev Method to add accounts with Operator role * @param _operator Address that will receive Operator role access */ function addOperator(address _operator) public onlyOwner { addRole(_operator, ROLE_OPERATOR); } /** * @dev Method to remove accounts with Operator role * @param _operator Address that will loose Operator role access */ function removeOperator(address _operator) public onlyOwner { removeRole(_operator, ROLE_OPERATOR); } } contract Withdrawal is Ownable { // Address to which funds will be withdrawn address public withdrawWallet; /** * Event for withdraw logging * @param value Value that was withdrawn */ event WithdrawLog(uint256 value); /** * @param _withdrawWallet Address to which funds will be withdrawn */ constructor(address _withdrawWallet) public { require(_withdrawWallet != address(0), "Invalid funds holder wallet."); withdrawWallet = _withdrawWallet; } /** * @dev Transfers funds from the contract to the specified withdraw wallet address */ function withdrawAll() external onlyOwner { uint256 weiAmount = address(this).balance; withdrawWallet.transfer(weiAmount); emit WithdrawLog(weiAmount); } /** * @dev Transfers a part of the funds from the contract to the specified withdraw wallet address * @param _weiAmount Part of the funds to be withdrawn */ function withdraw(uint256 _weiAmount) external onlyOwner { require(_weiAmount <= address(this).balance, "Not enough funds."); withdrawWallet.transfer(_weiAmount); emit WithdrawLog(_weiAmount); } } contract PriceStrategy is Time, Operable { using SafeMath for uint256; /** * Describes stage parameters * @param start Stage start date * @param end Stage end date * @param volume Number of tokens available for the stage * @param priceInCHF Token price in CHF for the stage * @param minBonusVolume The minimum number of tokens after which the bonus tokens is added * @param bonus Percentage of bonus tokens */ struct Stage { uint256 start; uint256 end; uint256 volume; uint256 priceInCHF; uint256 minBonusVolume; uint256 bonus; bool lock; } /** * Describes lockup period parameters * @param periodInSec Lockup period in seconds * @param bonus Lockup bonus tokens percentage */ struct LockupPeriod { uint256 expires; uint256 bonus; } // describes stages available for ICO lifetime Stage[] public stages; // lockup periods specified by the period in month mapping(uint256 => LockupPeriod) public lockupPeriods; // number of decimals supported by CHF rates uint256 public constant decimalsCHF = 18; // minimum allowed investment in CHF (decimals 1e+18) uint256 public minInvestmentInCHF; // ETH rate in CHF uint256 public rateETHtoCHF; /** * Event for ETH to CHF rate changes logging * @param newRate New rate value */ event RateChangedLog(uint256 newRate); /** * @param _rateETHtoCHF Cost of ETH in CHF * @param _minInvestmentInCHF Minimal allowed investment in CHF */ constructor(uint256 _rateETHtoCHF, uint256 _minInvestmentInCHF) public { require(_minInvestmentInCHF > 0, "Minimum investment can not be set to 0."); minInvestmentInCHF = _minInvestmentInCHF; setETHtoCHFrate(_rateETHtoCHF); // PRE-ICO stages.push(Stage({ start: 1536969600, // 15th Sep, 2018 00:00:00 end: 1542239999, // 14th Nov, 2018 23:59:59 volume: uint256(25000000000).mul(10 ** 18), // (twenty five billion) priceInCHF: uint256(2).mul(10 ** 14), // CHF 0.00020 minBonusVolume: 0, bonus: 0, lock: false })); // ICO stages.push(Stage({ start: 1542240000, // 15th Nov, 2018 00:00:00 end: 1550188799, // 14th Feb, 2019 23:59:59 volume: uint256(65000000000).mul(10 ** 18), // (forty billion) priceInCHF: uint256(4).mul(10 ** 14), // CHF 0.00040 minBonusVolume: uint256(400000000).mul(10 ** 18), // (four hundred million) bonus: 2000, // 20% bonus tokens lock: true })); _setLockupPeriod(1550188799, 18, 3000); // 18 months after the end of the ICO / 30% _setLockupPeriod(1550188799, 12, 2000); // 12 months after the end of the ICO / 20% _setLockupPeriod(1550188799, 6, 1000); // 6 months after the end of the ICO / 10% } /** * @dev Updates ETH to CHF rate * @param _rateETHtoCHF Cost of ETH in CHF */ function setETHtoCHFrate(uint256 _rateETHtoCHF) public hasOwnerOrOperatePermission { require(_rateETHtoCHF > 0, "Rate can not be set to 0."); rateETHtoCHF = _rateETHtoCHF; emit RateChangedLog(rateETHtoCHF); } /** * @dev Tokens amount based on investment value in wei * @param _wei Investment value in wei * @param _lockup Lockup period in months * @param _sold Number of tokens sold by the moment * @return Amount of tokens and bonuses */ function getTokensAmount(uint256 _wei, uint256 _lockup, uint256 _sold) public view returns (uint256 tokens, uint256 bonus) { uint256 chfAmount = _wei.mul(rateETHtoCHF).div(10 ** decimalsCHF); require(chfAmount >= minInvestmentInCHF, "Investment value is below allowed minimum."); Stage memory currentStage = _getCurrentStage(); require(currentStage.priceInCHF > 0, "Invalid price value."); tokens = chfAmount.mul(10 ** decimalsCHF).div(currentStage.priceInCHF); uint256 bonusSize; if (tokens >= currentStage.minBonusVolume) { bonusSize = currentStage.bonus.add(lockupPeriods[_lockup].bonus); } else { bonusSize = lockupPeriods[_lockup].bonus; } bonus = tokens.mul(bonusSize).div(10 ** 4); uint256 total = tokens.add(bonus); require(currentStage.volume > _sold.add(total), "Not enough tokens available."); } /** * @dev Finds current stage parameters according to the rules and current date and time * @return Current stage parameters (available volume of tokens and price in CHF) */ function _getCurrentStage() internal view returns (Stage) { uint256 index = 0; uint256 time = _currentTime(); Stage memory result; while (index < stages.length) { Stage memory stage = stages[index]; if ((time >= stage.start && time <= stage.end)) { result = stage; break; } index++; } return result; } /** * @dev Sets bonus for specified lockup period. Allowed only for contract owner * @param _startPoint Lock start point (is seconds) * @param _period Lockup period (in months) * @param _bonus Percentage of bonus tokens */ function _setLockupPeriod(uint256 _startPoint, uint256 _period, uint256 _bonus) private { uint256 expires = _startPoint.add(_period.mul(2628000)); lockupPeriods[_period] = LockupPeriod({ expires: expires, bonus: _bonus }); } } contract BaseCrowdsale { using SafeMath for uint256; using SafeERC20 for CosquareToken; // The token being sold CosquareToken public token; // Total amount of tokens sold uint256 public tokensSold; /** * @dev Event for tokens purchase logging * @param purchaseType Who paid for the tokens * @param beneficiary Who got the tokens * @param value Value paid for purchase * @param tokens Amount of tokens purchased * @param bonuses Amount of bonuses received */ event TokensPurchaseLog(string purchaseType, address indexed beneficiary, uint256 value, uint256 tokens, uint256 bonuses); /** * @param _token Address of the token being sold */ constructor(CosquareToken _token) public { require(_token != address(0), "Invalid token address."); token = _token; } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { require(msg.data.length == 0, "Should not accept data."); _buyTokens(msg.sender, msg.value, "ETH"); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) external payable { _buyTokens(_beneficiary, msg.value, "ETH"); } /** * @dev Tokens purchase for wei investments * @param _beneficiary Address performing the token purchase * @param _amount Amount of tokens purchased * @param _investmentType Investment channel string */ function _buyTokens(address _beneficiary, uint256 _amount, string _investmentType) internal { _preValidatePurchase(_beneficiary, _amount); (uint256 tokensAmount, uint256 tokenBonus) = _getTokensAmount(_beneficiary, _amount); uint256 totalAmount = tokensAmount.add(tokenBonus); _processPurchase(_beneficiary, totalAmount); emit TokensPurchaseLog(_investmentType, _beneficiary, _amount, tokensAmount, tokenBonus); _postPurchaseUpdate(_beneficiary, totalAmount); } /** * @dev Validation of an executed purchase * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0), "Invalid beneficiary address."); require(_weiAmount > 0, "Invalid investment value."); } /** * @dev Abstract function to count the number of tokens depending on the funds deposited * @param _beneficiary Address for which to get the tokens amount * @param _weiAmount Value in wei involved in the purchase * @return Number of tokens */ function _getTokensAmount(address _beneficiary, uint256 _weiAmount) internal view returns (uint256 tokens, uint256 bonus); /** * @dev Executed when a purchase is ready to be executed * @param _beneficiary Address receiving the tokens * @param _tokensAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokensAmount) internal { _deliverTokens(_beneficiary, _tokensAmount); } /** * @dev Deliver tokens to investor * @param _beneficiary Address receiving the tokens * @param _tokensAmount Number of tokens to be purchased */ function _deliverTokens(address _beneficiary, uint256 _tokensAmount) internal { token.safeTransfer(_beneficiary, _tokensAmount); } /** * @dev Changes the contract state after purchase * @param _beneficiary Address received the tokens * @param _tokensAmount The number of tokens that were purchased */ function _postPurchaseUpdate(address _beneficiary, uint256 _tokensAmount) internal { tokensSold = tokensSold.add(_tokensAmount); } } contract LockableCrowdsale is Time, Lockable, Operable, PriceStrategy, BaseCrowdsale { using SafeMath for uint256; /** * @dev Locks the next purchase for the provision of bonus tokens * @param _beneficiary Address for which the next purchase will be locked * @param _lockupPeriod The period to which tokens will be locked from the next purchase */ function lockNextPurchase(address _beneficiary, uint256 _lockupPeriod) external hasOwnerOrOperatePermission { require(_lockupPeriod == 6 || _lockupPeriod == 12 || _lockupPeriod == 18, "Invalid lock interval"); Stage memory currentStage = _getCurrentStage(); require(currentStage.lock, "Lock operation is not allowed."); _lock(_beneficiary, _lockupPeriod); } /** * @dev Executed when a purchase is ready to be executed * @param _beneficiary Address receiving the tokens * @param _tokensAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokensAmount) internal { super._processPurchase(_beneficiary, _tokensAmount); uint256 lockedValue = lockedValues[_beneficiary]; if (lockedValue > 0) { uint256 expires = lockupPeriods[lockedValue].expires; token.lock(_beneficiary, _tokensAmount, expires); } } /** * @dev Counts the number of tokens depending on the funds deposited * @param _beneficiary Address for which to get the tokens amount * @param _weiAmount Value in wei involved in the purchase * @return Number of tokens */ function _getTokensAmount(address _beneficiary, uint256 _weiAmount) internal view returns (uint256 tokens, uint256 bonus) { (tokens, bonus) = getTokensAmount(_weiAmount, lockedValues[_beneficiary], tokensSold); } /** * @dev Changes the contract state after purchase * @param _beneficiary Address received the tokens * @param _tokensAmount The number of tokens that were purchased */ function _postPurchaseUpdate(address _beneficiary, uint256 _tokensAmount) internal { super._postPurchaseUpdate(_beneficiary, _tokensAmount); _unlock(_beneficiary); } } contract Whitelist is RBAC, Operable { // role key string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if operator is not whitelisted. * @param _operator Operator address */ modifier onlyIfWhitelisted(address _operator) { checkRole(_operator, ROLE_WHITELISTED); _; } /** * @dev Add an address to the whitelist * @param _operator Operator address */ function addAddressToWhitelist(address _operator) public hasOwnerOrOperatePermission { addRole(_operator, ROLE_WHITELISTED); } /** * @dev Getter to determine if address is in whitelist * @param _operator The address to be added to the whitelist * @return True if the address is in the whitelist */ function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } /** * @dev Add addresses to the whitelist * @param _operators Operators addresses */ function addAddressesToWhitelist(address[] _operators) public hasOwnerOrOperatePermission { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev Remove an address from the whitelist * @param _operator Operator address */ function removeAddressFromWhitelist(address _operator) public hasOwnerOrOperatePermission { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev Remove addresses from the whitelist * @param _operators Operators addresses */ function removeAddressesFromWhitelist(address[] _operators) public hasOwnerOrOperatePermission { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } contract WhitelistedCrowdsale is Whitelist, BaseCrowdsale { /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyIfWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract PausableCrowdsale is Pausable, BaseCrowdsale { /** * @dev Extend parent behavior requiring contract not to be paused * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @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 DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @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; } } contract CosquareToken is Time, StandardToken, DetailedERC20, Ownable { using SafeMath for uint256; /** * Describes locked balance * @param expires Time when tokens will be unlocked * @param value Amount of the tokens is locked */ struct LockedBalance { uint256 expires; uint256 value; } // locked balances specified be the address mapping(address => LockedBalance[]) public lockedBalances; // sale wallet (65%) address public saleWallet; // reserve wallet (15%) address public reserveWallet; // team wallet (15%) address public teamWallet; // strategic wallet (5%) address public strategicWallet; // end point, after which all tokens will be unlocked uint256 public lockEndpoint; /** * Event for lock logging * @param who The address on which part of the tokens is locked * @param value Amount of the tokens is locked * @param expires Time when tokens will be unlocked */ event LockLog(address indexed who, uint256 value, uint256 expires); /** * @param _saleWallet Sale wallet * @param _reserveWallet Reserve wallet * @param _teamWallet Team wallet * @param _strategicWallet Strategic wallet * @param _lockEndpoint End point, after which all tokens will be unlocked */ constructor(address _saleWallet, address _reserveWallet, address _teamWallet, address _strategicWallet, uint256 _lockEndpoint) DetailedERC20("cosquare", "CSQ", 18) public { require(_lockEndpoint > 0, "Invalid global lock end date."); lockEndpoint = _lockEndpoint; _configureWallet(_saleWallet, 65000000000000000000000000000); // 6.5e+28 saleWallet = _saleWallet; _configureWallet(_reserveWallet, 15000000000000000000000000000); // 1.5e+28 reserveWallet = _reserveWallet; _configureWallet(_teamWallet, 15000000000000000000000000000); // 1.5e+28 teamWallet = _teamWallet; _configureWallet(_strategicWallet, 5000000000000000000000000000); // 0.5e+28 strategicWallet = _strategicWallet; } /** * @dev Setting the initial value of the tokens to the wallet * @param _wallet Address to be set up * @param _amount The number of tokens to be assigned to this address */ function _configureWallet(address _wallet, uint256 _amount) private { require(_wallet != address(0), "Invalid wallet address."); totalSupply_ = totalSupply_.add(_amount); balances[_wallet] = _amount; emit Transfer(address(0), _wallet, _amount); } /** * @dev Throws if the address does not have enough not locked balance * @param _who The address to transfer from * @param _value The amount to be transferred */ modifier notLocked(address _who, uint256 _value) { uint256 time = _currentTime(); if (lockEndpoint > time) { uint256 index = 0; uint256 locked = 0; while (index < lockedBalances[_who].length) { if (lockedBalances[_who][index].expires > time) { locked = locked.add(lockedBalances[_who][index].value); } index++; } require(_value <= balances[_who].sub(locked), "Not enough unlocked tokens"); } _; } /** * @dev Overridden to check whether enough not locked balance * @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, uint256 _value) public notLocked(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Overridden to check whether enough not locked balance * @param _to The address to transfer to * @param _value The amount to be transferred */ function transfer(address _to, uint256 _value) public notLocked(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @dev Gets the locked balance of the specified address * @param _owner The address to query the locked balance of * @param _expires Time of expiration of the lock (If equals to 0 - returns all locked tokens at this moment) * @return An uint256 representing the amount of locked balance by the passed address */ function lockedBalanceOf(address _owner, uint256 _expires) external view returns (uint256) { uint256 time = _currentTime(); uint256 index = 0; uint256 locked = 0; if (lockEndpoint > time) { while (index < lockedBalances[_owner].length) { if (_expires > 0) { if (lockedBalances[_owner][index].expires == _expires) { locked = locked.add(lockedBalances[_owner][index].value); } } else { if (lockedBalances[_owner][index].expires >= time) { locked = locked.add(lockedBalances[_owner][index].value); } } index++; } } return locked; } /** * @dev Locks part of the balance for the specified address and for a certain period (3 periods expected) * @param _who The address of which will be locked part of the balance * @param _value The amount of tokens to be locked * @param _expires Time of expiration of the lock */ function lock(address _who, uint256 _value, uint256 _expires) public onlyOwner { uint256 time = _currentTime(); require(_who != address(0) && _value <= balances[_who] && _expires > time, "Invalid lock configuration."); uint256 index = 0; bool exist = false; while (index < lockedBalances[_who].length) { if (lockedBalances[_who][index].expires == _expires) { exist = true; break; } index++; } if (exist) { lockedBalances[_who][index].value = lockedBalances[_who][index].value.add(_value); } else { lockedBalances[_who].push(LockedBalance({ expires: _expires, value: _value })); } emit LockLog(_who, _value, _expires); } } contract Crowdsale is Lockable, Operable, Withdrawal, PriceStrategy, LockableCrowdsale, WhitelistedCrowdsale, PausableCrowdsale { using SafeMath for uint256; /** * @param _rateETHtoCHF Cost of ETH in CHF * @param _minInvestmentInCHF Minimal allowed investment in CHF * @param _withdrawWallet Address to which funds will be withdrawn * @param _token Address of the token being sold */ constructor(uint256 _rateETHtoCHF, uint256 _minInvestmentInCHF, address _withdrawWallet, CosquareToken _token) PriceStrategy(_rateETHtoCHF, _minInvestmentInCHF) Withdrawal(_withdrawWallet) BaseCrowdsale(_token) public { } /** * @dev Distributes tokens for wei investments * @param _beneficiary Address performing the token purchase * @param _ethAmount Investment value in ETH * @param _type Type of investment channel */ function distributeTokensForInvestment(address _beneficiary, uint256 _ethAmount, string _type) public hasOwnerOrOperatePermission { _buyTokens(_beneficiary, _ethAmount, _type); } /** * @dev Distributes tokens manually * @param _beneficiary Address performing the tokens distribution * @param _tokensAmount Amount of tokens distribution */ function distributeTokensManual(address _beneficiary, uint256 _tokensAmount) external hasOwnerOrOperatePermission { _preValidatePurchase(_beneficiary, _tokensAmount); _deliverTokens(_beneficiary, _tokensAmount); emit TokensPurchaseLog("MANUAL", _beneficiary, 0, _tokensAmount, 0); _postPurchaseUpdate(_beneficiary, _tokensAmount); } }
* Describes stage parameters @param start Stage start date @param end Stage end date @param volume Number of tokens available for the stage @param priceInCHF Token price in CHF for the stage @param minBonusVolume The minimum number of tokens after which the bonus tokens is added @param bonus Percentage of bonus tokens/
struct Stage { uint256 start; uint256 end; uint256 volume; uint256 priceInCHF; uint256 minBonusVolume; uint256 bonus; bool lock; }
2,492,432
[ 1, 4217, 24322, 6009, 1472, 225, 787, 16531, 787, 1509, 225, 679, 16531, 679, 1509, 225, 3940, 3588, 434, 2430, 2319, 364, 326, 6009, 225, 6205, 382, 1792, 42, 3155, 6205, 316, 6469, 42, 364, 326, 6009, 225, 1131, 38, 22889, 4545, 1021, 5224, 1300, 434, 2430, 1839, 1492, 326, 324, 22889, 2430, 353, 3096, 225, 324, 22889, 21198, 410, 434, 324, 22889, 2430, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 16531, 288, 203, 3639, 2254, 5034, 787, 31, 203, 3639, 2254, 5034, 679, 31, 203, 3639, 2254, 5034, 3940, 31, 203, 3639, 2254, 5034, 6205, 382, 1792, 42, 31, 203, 3639, 2254, 5034, 1131, 38, 22889, 4545, 31, 203, 3639, 2254, 5034, 324, 22889, 31, 203, 3639, 1426, 2176, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xf292055dbA34F5AA088a8D69Eb24c875677D03ba/sources/contracts/Dsitribute.sol
コントラクトに送金されたとき、その送金を自動的にdestinationAddressに転送します。 トレジャリーには必ず30%を送金 残りの70%を分配比率に応じて送金(_percentagesの合計が70でない場合は正規化)
receive() external payable { require(msg.value > 0, "No ethers transferred"); require(success, "Transfer failed"); for (uint256 i = 0; i < shares.length; i++) { totalPercentage += shares[i].percentage; } for (uint256 i = 0; i < shares.length; i++) { require(success_i, "Transfer failed in loop"); } }
9,486,912
[ 1, 164, 229, 116, 164, 230, 116, 164, 230, 235, 164, 230, 107, 164, 229, 112, 164, 230, 235, 164, 228, 109, 170, 227, 228, 170, 234, 244, 164, 228, 248, 164, 229, 239, 164, 228, 258, 164, 228, 106, 164, 228, 240, 164, 227, 228, 164, 228, 256, 164, 228, 111, 170, 227, 228, 170, 234, 244, 164, 229, 245, 169, 234, 108, 166, 238, 248, 168, 253, 231, 164, 228, 109, 10590, 1887, 164, 228, 109, 169, 124, 100, 170, 227, 228, 164, 228, 250, 164, 228, 127, 164, 228, 252, 164, 227, 229, 225, 164, 230, 235, 164, 230, 110, 164, 229, 121, 164, 230, 101, 164, 230, 108, 164, 230, 125, 164, 228, 109, 164, 228, 112, 166, 128, 232, 164, 228, 253, 5082, 176, 125, 232, 164, 229, 245, 170, 227, 228, 170, 234, 244, 225, 167, 111, 238, 164, 229, 237, 164, 228, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 6798, 1435, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 16, 315, 2279, 13750, 414, 906, 4193, 8863, 203, 203, 3639, 2583, 12, 4768, 16, 315, 5912, 2535, 8863, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 24123, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2078, 16397, 1011, 24123, 63, 77, 8009, 18687, 31, 203, 3639, 289, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 24123, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 12, 4768, 67, 77, 16, 315, 5912, 2535, 316, 2798, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "../interface/ERC1820Implementer.sol"; import "../IERC1400.sol"; /** * @title BatchTokenIssuer * @dev Proxy contract to issue multiple ERC1400/ERC20 tokens in a single transaction. */ contract BatchTokenIssuer is ERC1820Implementer { string constant internal BATCH_ISSUER = "BatchTokenIssuer"; // Mapping from token to token minters. mapping(address => address[]) internal _tokenMinters; // Mapping from (token, operator) to token minter status. mapping(address => mapping(address => bool)) internal _isTokenMinter; /** * @dev Modifier to verify if sender is a token minter. */ modifier onlyTokenMinter(address tokenAddress) { require(_tokenMinter(msg.sender, tokenAddress), "Sender is not a token minter." ); _; } constructor() public { ERC1820Implementer._setInterface(BATCH_ISSUER); } /** * @dev Issue tokens for multiple addresses. * @param tokenAddress Address of token where the tokens need to be issued. * @param partitions Name of the partitions. * @param tokenHolders Addresses for which we want to issue tokens. * @param values Number of tokens issued. */ function batchIssueByPartition( address tokenAddress, bytes32[] calldata partitions, address[] calldata tokenHolders, uint256[] calldata values ) external onlyTokenMinter(tokenAddress) returns (uint256[] memory) { require(partitions.length == tokenHolders.length, "partitions and tokenHolders arrays have different lengths"); require(partitions.length == values.length, "partitions and values arrays have different lengths"); for (uint i = 0; i < partitions.length; i++) { IERC1400(tokenAddress).issueByPartition(partitions[i], tokenHolders[i], values[i], ""); } } /************************** TOKEN MINTERS *******************************/ /** * @dev Get the list of token minters for a given token. * @param tokenAddress Token address. * @return List of addresses of all the token minters for a given token. */ function tokenMinters(address tokenAddress) external view returns (address[] memory) { return _tokenMinters[tokenAddress]; } /** * @dev Set list of token minters for a given token. * @param tokenAddress Token address. * @param operators Operators addresses. */ function setTokenMinters(address tokenAddress, address[] calldata operators) external onlyTokenMinter(tokenAddress) { _setTokenMinters(tokenAddress, operators); } /** * @dev Set list of token minters for a given token. * @param tokenAddress Token address. * @param operators Operators addresses. */ function _setTokenMinters(address tokenAddress, address[] memory operators) internal { for (uint i = 0; i<_tokenMinters[tokenAddress].length; i++){ _isTokenMinter[tokenAddress][_tokenMinters[tokenAddress][i]] = false; } for (uint j = 0; j<operators.length; j++){ _isTokenMinter[tokenAddress][operators[j]] = true; } _tokenMinters[tokenAddress] = operators; } /** * @dev Check if the sender is a token minter. * * @param sender Transaction sender. * @param tokenAddress Token address. * @return Returns 'true' if sender is a token minter. */ function _tokenMinter(address sender, address tokenAddress) internal view returns(bool) { if(sender == Ownable(tokenAddress).owner() || _isTokenMinter[tokenAddress][sender]) { return true; } else { return false; } } }
* @dev Get the list of token minters for a given token. @param tokenAddress Token address. @return List of addresses of all the token minters for a given token./
function tokenMinters(address tokenAddress) external view returns (address[] memory) { return _tokenMinters[tokenAddress]; }
5,454,236
[ 1, 967, 326, 666, 434, 1147, 1131, 5432, 364, 279, 864, 1147, 18, 225, 1147, 1887, 3155, 1758, 18, 327, 987, 434, 6138, 434, 777, 326, 1147, 1131, 5432, 364, 279, 864, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1147, 49, 2761, 87, 12, 2867, 1147, 1887, 13, 3903, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 565, 327, 389, 2316, 49, 2761, 87, 63, 2316, 1887, 15533, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-03-31 */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.5.12; contract GemLike { function allowance(address, address) public returns (uint); function approve(address, uint) public; function transfer(address, uint) public returns (bool); function transferFrom(address, address, uint) public returns (bool); } contract ValueLike { function peek() public returns (uint, bool); } contract SaiTubLike { function skr() public view returns (GemLike); function gem() public view returns (GemLike); function gov() public view returns (GemLike); function sai() public view returns (GemLike); function pep() public view returns (ValueLike); function vox() public view returns (VoxLike); function bid(uint) public view returns (uint); function ink(bytes32) public view returns (uint); function tag() public view returns (uint); function tab(bytes32) public returns (uint); function rap(bytes32) public returns (uint); function draw(bytes32, uint) public; function shut(bytes32) public; function exit(uint) public; function give(bytes32, address) public; } contract VoxLike { function par() public returns (uint); } contract JoinLike { function ilk() public returns (bytes32); function gem() public returns (GemLike); function dai() public returns (GemLike); function join(address, uint) public; function exit(address, uint) public; } contract VatLike { function ilks(bytes32) public view returns (uint, uint, uint, uint, uint); function hope(address) public; function frob(bytes32, address, address, address, int, int) public; } contract ManagerLike { function vat() public view returns (address); function urns(uint) public view returns (address); function open(bytes32, address) public returns (uint); function frob(uint, int, int) public; function give(uint, address) public; function move(uint, address, uint) public; } contract OtcLike { function getPayAmount(address, address, uint) public view returns (uint); function buyAllAmount(address, uint, address, uint) public; } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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; } } /** * @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. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /** * @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 is Initializable { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // 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"); } uint256[50] private ______gap; } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ contract ICErc20 { address public underlying; function mint(uint256 mintAmount) external returns (uint); function redeemUnderlying(uint256 redeemAmount) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getCash() external view returns (uint); function supplyRatePerBlock() external view returns (uint); } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { require(_upperBound > 0, "UniformRand/min-bound"); uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack.length = 0; tree.nodes.length = 0; tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.length--; tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (tree.nodes.length == 0) { return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } /** * @author Brendan Asselstine * @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances. * * Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw. * When a new draw is opened, the previous opened draw is committed. * * The committed balance for an address is the total of their balances for committed Draws. * An address's open balance is their balance in the open Draw. */ library DrawManager { using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; using SafeMath for uint256; /** * The ID to use for the selection tree. */ bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws"; uint8 public constant MAX_BRANCHES_PER_NODE = 10; /** * Stores information for all draws. */ struct State { /** * Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index. * There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS. */ SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees; /** * Stores the consolidated draw index that an address deposited to. */ mapping(address => uint256) consolidatedDrawIndices; /** * Stores the last Draw index that an address deposited to. */ mapping(address => uint256) latestDrawIndices; /** * Stores a mapping of Draw index => Draw total */ mapping(uint256 => uint256) __deprecated__drawTotals; /** * The current open Draw index */ uint256 openDrawIndex; /** * The total of committed balances */ uint256 __deprecated__committedSupply; } /** * @notice Opens the next Draw and commits the previous open Draw (if any). * @param self The drawState this library is attached to * @return The index of the new open Draw */ function openNextDraw(State storage self) public returns (uint256) { if (self.openDrawIndex == 0) { // If there is no previous draw, we must initialize self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_BRANCHES_PER_NODE); } else { // else add current draw to sortition sum trees bytes32 drawId = bytes32(self.openDrawIndex); uint256 drawTotal = openSupply(self); self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId); } // now create a new draw uint256 drawIndex = self.openDrawIndex.add(1); self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_BRANCHES_PER_NODE); self.openDrawIndex = drawIndex; return drawIndex; } /** * @notice Deposits the given amount into the current open draw by the given user. * @param self The DrawManager state * @param _addr The address to deposit for * @param _amount The amount to deposit */ function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openDrawIndex = self.openDrawIndex; // update the current draw uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId); currentAmount = currentAmount.add(_amount); drawSet(self, openDrawIndex, currentAmount, _addr); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; // if this is the user's first draw, set it if (consolidatedDrawIndex == 0) { self.consolidatedDrawIndices[_addr] = openDrawIndex; // otherwise, if the consolidated draw is not this draw } else if (consolidatedDrawIndex != openDrawIndex) { // if a second draw does not exist if (latestDrawIndex == 0) { // set the second draw to the current draw self.latestDrawIndices[_addr] = openDrawIndex; // otherwise if a second draw exists but is not the current one } else if (latestDrawIndex != openDrawIndex) { // merge it into the first draw, and update the second draw index to this one uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); uint256 latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId); drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(latestAmount), _addr); drawSet(self, latestDrawIndex, 0, _addr); self.latestDrawIndices[_addr] = openDrawIndex; } } } /** * @notice Deposits into a user's committed balance, thereby bypassing the open draw. * @param self The DrawManager state * @param _addr The address of the user for whom to deposit * @param _amount The amount to deposit */ function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; // if they have a committed balance if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(_amount), _addr); } else { // they must not have any committed balance self.latestDrawIndices[_addr] = consolidatedDrawIndex; self.consolidatedDrawIndices[_addr] = self.openDrawIndex.sub(1); drawSet(self, self.consolidatedDrawIndices[_addr], _amount, _addr); } } /** * @notice Withdraws a user's committed and open draws. * @param self The DrawManager state * @param _addr The address whose balance to withdraw */ function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) { uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; if (consolidatedDrawIndex != 0) { drawSet(self, consolidatedDrawIndex, 0, _addr); delete self.consolidatedDrawIndices[_addr]; } if (latestDrawIndex != 0) { drawSet(self, latestDrawIndex, 0, _addr); delete self.latestDrawIndices[_addr]; } } /** * @notice Withdraw's from a user's open balance * @param self The DrawManager state * @param _addr The user to withdrawn from * @param _amount The amount to withdraw */ function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId); require(_amount <= openTotal, "DrawMan/exceeds-open"); uint256 remaining = openTotal.sub(_amount); drawSet(self, self.openDrawIndex, remaining, _addr); } /** * @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available. * @param self The DrawManager state * @param _addr The user to withdraw from * @param _amount The amount to withdraw. */ function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) { bytes32 userId = bytes32(uint256(_addr)); uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; uint256 consolidatedAmount = 0; uint256 latestAmount = 0; uint256 total = 0; if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) { latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId); total = total.add(latestAmount); } if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId); total = total.add(consolidatedAmount); } // If the total is greater than zero, then consolidated *must* have the committed balance // However, if the total is zero then the consolidated balance may be the open balance if (total == 0) { return; } require(_amount <= total, "Pool/exceed"); uint256 remaining = total.sub(_amount); // if there was a second amount that needs to be updated if (remaining > consolidatedAmount) { uint256 secondRemaining = remaining.sub(consolidatedAmount); drawSet(self, latestDrawIndex, secondRemaining, _addr); } else if (latestAmount > 0) { // else delete the second amount if it exists delete self.latestDrawIndices[_addr]; drawSet(self, latestDrawIndex, 0, _addr); } // if the consolidated amount needs to be destroyed if (remaining == 0) { delete self.consolidatedDrawIndices[_addr]; drawSet(self, consolidatedDrawIndex, 0, _addr); } else if (remaining < consolidatedAmount) { drawSet(self, consolidatedDrawIndex, remaining, _addr); } } /** * @notice Returns the total balance for an address, including committed balances and the open balance. */ function balanceOf(State storage drawState, address _addr) public view returns (uint256) { return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr)); } /** * @notice Returns the total committed balance for an address. * @param self The DrawManager state * @param _addr The address whose committed balance should be returned * @return The total committed balance */ function committedBalanceOf(State storage self, address _addr) public view returns (uint256) { uint256 balance = 0; uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr]; uint256 latestDrawIndex = self.latestDrawIndices[_addr]; if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) { balance = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), bytes32(uint256(_addr))); } if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) { balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), bytes32(uint256(_addr)))); } return balance; } /** * @notice Returns the open balance for an address * @param self The DrawManager state * @param _addr The address whose open balance should be returned * @return The open balance */ function openBalanceOf(State storage self, address _addr) public view returns (uint256) { if (self.openDrawIndex == 0) { return 0; } else { return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr))); } } /** * @notice Returns the open Draw balance for the DrawManager * @param self The DrawManager state * @return The open draw total balance */ function openSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(bytes32(self.openDrawIndex)); } /** * @notice Returns the committed balance for the DrawManager * @param self The DrawManager state * @return The total committed balance */ function committedSupply(State storage self) public view returns (uint256) { return self.sortitionSumTrees.total(TREE_OF_DRAWS); } /** * @notice Updates the Draw balance for an address. * @param self The DrawManager state * @param _drawIndex The Draw index * @param _amount The new balance * @param _addr The address whose balance should be updated */ function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal { bytes32 drawId = bytes32(_drawIndex); bytes32 userId = bytes32(uint256(_addr)); uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId); if (oldAmount != _amount) { // If the amount has changed // Update the Draw's balance for that address self.sortitionSumTrees.set(drawId, _amount, userId); // if the draw is committed if (_drawIndex != self.openDrawIndex) { // Get the new draw total uint256 newDrawTotal = self.sortitionSumTrees.total(drawId); // update the draw in the committed tree self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId); } } } /** * @notice Selects an address by indexing into the committed tokens using the passed token. * If there is no committed supply, the zero address is returned. * @param self The DrawManager state * @param _token The token index to select * @return The selected address */ function draw(State storage self, uint256 _token) public view returns (address) { // If there is no one to select, just return the zero address if (committedSupply(self) == 0) { return address(0); } require(_token < committedSupply(self), "Pool/ineligible"); bytes32 drawIndex = self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token); uint256 drawSupply = self.sortitionSumTrees.total(drawIndex); uint256 drawToken = _token % drawSupply; return address(uint256(self.sortitionSumTrees.draw(drawIndex, drawToken))); } /** * @notice Selects an address using the entropy as an index into the committed tokens * The entropy is passed into the UniformRandomNumber library to remove modulo bias. * @param self The DrawManager state * @param _entropy The random entropy to use * @return The selected address */ function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) { uint256 bound = committedSupply(self); address selected; if (bound == 0) { selected = address(0); } else { selected = draw(self, UniformRandomNumber.uniform(uint256(_entropy), bound)); } return selected; } modifier requireOpenDraw(State storage self) { require(self.openDrawIndex > 0, "Pool/no-open"); _; } modifier requireCommittedDraw(State storage self) { require(self.openDrawIndex > 1, "Pool/no-commit"); _; } modifier onlyNonZero(address _addr) { require(_addr != address(0), "Pool/not-zero"); _; } } /** * @title FixidityLib * @author Gadi Guy, Alberto Cuesta Canada * @notice This library provides fixed point arithmetic with protection against * overflow. * All operations are done with int256 and the operands must have been created * with any of the newFrom* functions, which shift the comma digits() to the * right and check for limits. * When using this library be sure of using maxNewFixed() as the upper limit for * creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and * maxFixedAdd() if you want to be certain that those operations don't * overflow. */ library FixidityLib { /** * @notice Number of positions that the comma is shifted to the right. */ function digits() public pure returns(uint8) { return 24; } /** * @notice This is 1 in the fixed point units used in this library. * @dev Test fixed1() equals 10^digits() * Hardcoded to 24 digits. */ function fixed1() public pure returns(int256) { return 1000000000000000000000000; } /** * @notice The amount of decimals lost on each multiplication operand. * @dev Test mulPrecision() equals sqrt(fixed1) * Hardcoded to 24 digits. */ function mulPrecision() public pure returns(int256) { return 1000000000000; } /** * @notice Maximum value that can be represented in an int256 * @dev Test maxInt256() equals 2^255 -1 */ function maxInt256() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282019728792003956564819967; } /** * @notice Minimum value that can be represented in an int256 * @dev Test minInt256 equals (2^255) * (-1) */ function minInt256() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282019728792003956564819968; } /** * @notice Maximum value that can be converted to fixed point. Optimize for * @dev deployment. * Test maxNewFixed() equals maxInt256() / fixed1() * Hardcoded to 24 digits. */ function maxNewFixed() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Minimum value that can be converted to fixed point. Optimize for * deployment. * @dev Test minNewFixed() equals -(maxInt256()) / fixed1() * Hardcoded to 24 digits. */ function minNewFixed() public pure returns(int256) { return -57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as an addition operator. * @dev Test maxFixedAdd() equals maxInt256()-1 / 2 * Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd() * Test add(maxFixedAdd()+1,maxFixedAdd()) throws * Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd() * Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws */ function maxFixedAdd() public pure returns(int256) { return 28948022309329048855892746252171976963317496166410141009864396001978282409983; } /** * @notice Maximum negative value that can be safely in a subtraction. * @dev Test maxFixedSub() equals minInt256() / 2 */ function maxFixedSub() public pure returns(int256) { return -28948022309329048855892746252171976963317496166410141009864396001978282409984; } /** * @notice Maximum value that can be safely used as a multiplication operator. * @dev Calculated as sqrt(maxInt256()*fixed1()). * Be careful with your sqrt() implementation. I couldn't find a calculator * that would give the exact square root of maxInt256*fixed1 so this number * is below the real number by no more than 3*10**28. It is safe to use as * a limit for your multiplications, although powers of two of numbers over * this value might still work. * Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul() * Test multiply(maxFixedMul(),maxFixedMul()+1) throws * Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul() * Test multiply(-maxFixedMul(),maxFixedMul()+1) throws * Hardcoded to 24 digits. */ function maxFixedMul() public pure returns(int256) { return 240615969168004498257251713877715648331380787511296; } /** * @notice Maximum value that can be safely used as a dividend. * @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256(). * Test maxFixedDiv() equals maxInt256()/fixed1() * Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws * Hardcoded to 24 digits. */ function maxFixedDiv() public pure returns(int256) { return 57896044618658097711785492504343953926634992332820282; } /** * @notice Maximum value that can be safely used as a divisor. * @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2) * Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1() * Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws * Hardcoded to 24 digits. */ function maxFixedDivisor() public pure returns(int256) { return 1000000000000000000000000000000000000000000000000; } /** * @notice Converts an int256 to fixed point units, equivalent to multiplying * by 10^digits(). * @dev Test newFixed(0) returns 0 * Test newFixed(1) returns fixed1() * Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1() * Test newFixed(maxNewFixed()+1) fails */ function newFixed(int256 x) public pure returns (int256) { require(x <= maxNewFixed()); require(x >= minNewFixed()); return x * fixed1(); } /** * @notice Converts an int256 in the fixed point representation of this * library to a non decimal. All decimal digits will be truncated. */ function fromFixed(int256 x) public pure returns (int256) { return x / fixed1(); } /** * @notice Converts an int256 which is already in some fixed point * representation to a different fixed precision representation. * Both the origin and destination precisions must be 38 or less digits. * Origin values with a precision higher than the destination precision * will be truncated accordingly. * @dev * Test convertFixed(1,0,0) returns 1; * Test convertFixed(1,1,1) returns 1; * Test convertFixed(1,1,0) returns 0; * Test convertFixed(1,0,1) returns 10; * Test convertFixed(10,1,0) returns 1; * Test convertFixed(10,0,1) returns 100; * Test convertFixed(100,1,0) returns 10; * Test convertFixed(100,0,1) returns 1000; * Test convertFixed(1000,2,0) returns 10; * Test convertFixed(1000,0,2) returns 100000; * Test convertFixed(1000,2,1) returns 100; * Test convertFixed(1000,1,2) returns 10000; * Test convertFixed(maxInt256,1,0) returns maxInt256/10; * Test convertFixed(maxInt256,0,1) throws * Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38); * Test convertFixed(1,0,38) returns 10**38; * Test convertFixed(maxInt256,39,0) throws * Test convertFixed(1,0,39) throws */ function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits) public pure returns (int256) { require(_originDigits <= 38 && _destinationDigits <= 38); uint8 decimalDifference; if ( _originDigits > _destinationDigits ){ decimalDifference = _originDigits - _destinationDigits; return x/(uint128(10)**uint128(decimalDifference)); } else if ( _originDigits < _destinationDigits ){ decimalDifference = _destinationDigits - _originDigits; // Cast uint8 -> uint128 is safe // Exponentiation is safe: // _originDigits and _destinationDigits limited to 38 or less // decimalDifference = abs(_destinationDigits - _originDigits) // decimalDifference < 38 // 10**38 < 2**128-1 require(x <= maxInt256()/uint128(10)**uint128(decimalDifference)); require(x >= minInt256()/uint128(10)**uint128(decimalDifference)); return x*(uint128(10)**uint128(decimalDifference)); } // _originDigits == digits()) return x; } /** * @notice Converts an int256 which is already in some fixed point * representation to that of this library. The _originDigits parameter is the * precision of x. Values with a precision higher than FixidityLib.digits() * will be truncated accordingly. */ function newFixed(int256 x, uint8 _originDigits) public pure returns (int256) { return convertFixed(x, _originDigits, digits()); } /** * @notice Converts an int256 in the fixed point representation of this * library to a different representation. The _destinationDigits parameter is the * precision of the output x. Values with a precision below than * FixidityLib.digits() will be truncated accordingly. */ function fromFixed(int256 x, uint8 _destinationDigits) public pure returns (int256) { return convertFixed(x, digits(), _destinationDigits); } /** * @notice Converts two int256 representing a fraction to fixed point units, * equivalent to multiplying dividend and divisor by 10^digits(). * @dev * Test newFixedFraction(maxFixedDiv()+1,1) fails * Test newFixedFraction(1,maxFixedDiv()+1) fails * Test newFixedFraction(1,0) fails * Test newFixedFraction(0,1) returns 0 * Test newFixedFraction(1,1) returns fixed1() * Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1() * Test newFixedFraction(1,fixed1()) returns 1 * Test newFixedFraction(1,fixed1()-1) returns 0 */ function newFixedFraction( int256 numerator, int256 denominator ) public pure returns (int256) { require(numerator <= maxNewFixed()); require(denominator <= maxNewFixed()); require(denominator != 0); int256 convertedNumerator = newFixed(numerator); int256 convertedDenominator = newFixed(denominator); return divide(convertedNumerator, convertedDenominator); } /** * @notice Returns the integer part of a fixed point number. * @dev * Test integer(0) returns 0 * Test integer(fixed1()) returns fixed1() * Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test integer(-fixed1()) returns -fixed1() * Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1() */ function integer(int256 x) public pure returns (int256) { return (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Returns the fractional part of a fixed point number. * In the case of a negative number the fractional is also negative. * @dev * Test fractional(0) returns 0 * Test fractional(fixed1()) returns 0 * Test fractional(fixed1()-1) returns 10^24-1 * Test fractional(-fixed1()) returns 0 * Test fractional(-fixed1()+1) returns -10^24-1 */ function fractional(int256 x) public pure returns (int256) { return x - (x / fixed1()) * fixed1(); // Can't overflow } /** * @notice Converts to positive if negative. * Due to int256 having one more negative number than positive numbers * abs(minInt256) reverts. * @dev * Test abs(0) returns 0 * Test abs(fixed1()) returns -fixed1() * Test abs(-fixed1()) returns fixed1() * Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1() * Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1() */ function abs(int256 x) public pure returns (int256) { if (x >= 0) { return x; } else { int256 result = -x; assert (result > 0); return result; } } /** * @notice x+y. If any operator is higher than maxFixedAdd() it * might overflow. * In solidity maxInt256 + 1 = minInt256 and viceversa. * @dev * Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1 * Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails * Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256() * Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails * Test add(maxInt256(),maxInt256()) fails * Test add(minInt256(),minInt256()) fails */ function add(int256 x, int256 y) public pure returns (int256) { int256 z = x + y; if (x > 0 && y > 0) assert(z > x && z > y); if (x < 0 && y < 0) assert(z < x && z < y); return z; } /** * @notice x-y. You can use add(x,-y) instead. * @dev Tests covered by add(x,y) */ function subtract(int256 x, int256 y) public pure returns (int256) { return add(x,-y); } /** * @notice x*y. If any of the operators is higher than maxFixedMul() it * might overflow. * @dev * Test multiply(0,0) returns 0 * Test multiply(maxFixedMul(),0) returns 0 * Test multiply(0,maxFixedMul()) returns 0 * Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul() * Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul() * Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5) * Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision()) * Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1) * Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits * Test multiply(maxFixedMul()+1,maxFixedMul()) fails * Test multiply(maxFixedMul(),maxFixedMul()+1) fails */ function multiply(int256 x, int256 y) public pure returns (int256) { if (x == 0 || y == 0) return 0; if (y == fixed1()) return x; if (x == fixed1()) return y; // Separate into integer and fractional parts // x = x1 + x2, y = y1 + y2 int256 x1 = integer(x) / fixed1(); int256 x2 = fractional(x); int256 y1 = integer(y) / fixed1(); int256 y2 = fractional(y); // (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2) int256 x1y1 = x1 * y1; if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1 // x1y1 needs to be multiplied back by fixed1 // solium-disable-next-line mixedcase int256 fixed_x1y1 = x1y1 * fixed1(); if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1 x1y1 = fixed_x1y1; int256 x2y1 = x2 * y1; if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1 int256 x1y2 = x1 * y2; if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2 x2 = x2 / mulPrecision(); y2 = y2 / mulPrecision(); int256 x2y2 = x2 * y2; if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2 // result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1(); int256 result = x1y1; result = add(result, x2y1); // Add checks for overflow result = add(result, x1y2); // Add checks for overflow result = add(result, x2y2); // Add checks for overflow return result; } /** * @notice 1/x * @dev * Test reciprocal(0) fails * Test reciprocal(fixed1()) returns fixed1() * Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated * Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated */ function reciprocal(int256 x) public pure returns (int256) { require(x != 0); return (fixed1()*fixed1()) / x; // Can't overflow } /** * @notice x/y. If the dividend is higher than maxFixedDiv() it * might overflow. You can use multiply(x,reciprocal(y)) instead. * There is a loss of precision on division for the lower mulPrecision() decimals. * @dev * Test divide(fixed1(),0) fails * Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits()) * Test divide(maxFixedDiv()+1,1) throws * Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1() */ function divide(int256 x, int256 y) public pure returns (int256) { if (y == fixed1()) return x; require(y != 0); require(y <= maxFixedDivisor()); return multiply(x, reciprocal(y)); } } /** * @title Blocklock * @author Brendan Asselstine * @notice A time lock with a cooldown period. When locked, the contract will remain locked until it is unlocked manually * or the lock duration expires. After the contract is unlocked, it cannot be locked until the cooldown duration expires. */ library Blocklock { using SafeMath for uint256; struct State { uint256 lockedAt; uint256 unlockedAt; uint256 lockDuration; uint256 cooldownDuration; } /** * @notice Sets the duration of the lock. This how long the lock lasts before it expires and automatically unlocks. * @param self The Blocklock state * @param lockDuration The duration, in blocks, that the lock should last. */ function setLockDuration(State storage self, uint256 lockDuration) public { require(lockDuration > 0, "Blocklock/lock-min"); self.lockDuration = lockDuration; } /** * @notice Sets the cooldown duration in blocks. This is the number of blocks that must pass before being able to * lock again. The cooldown duration begins when the lock duration expires, or when it is unlocked manually. * @param self The Blocklock state * @param cooldownDuration The duration of the cooldown, in blocks. */ function setCooldownDuration(State storage self, uint256 cooldownDuration) public { require(cooldownDuration > 0, "Blocklock/cool-min"); self.cooldownDuration = cooldownDuration; } /** * @notice Returns whether the state is locked at the given block number. * @param self The Blocklock state * @param blockNumber The current block number. */ function isLocked(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt != 0 && blockNumber >= self.lockedAt && blockNumber < endAt ); } /** * @notice Locks the state at the given block number. * @param self The Blocklock state * @param blockNumber The block number to use as the lock start time */ function lock(State storage self, uint256 blockNumber) public { require(canLock(self, blockNumber), "Blocklock/no-lock"); self.lockedAt = blockNumber; } /** * @notice Manually unlocks the lock. * @param self The Blocklock state * @param blockNumber The block number at which the lock is being unlocked. */ function unlock(State storage self, uint256 blockNumber) public { self.unlockedAt = blockNumber; } /** * @notice Returns whether the Blocklock can be locked at the given block number * @param self The Blocklock state * @param blockNumber The block number to check against * @return True if we can lock at the given block number, false otherwise. */ function canLock(State storage self, uint256 blockNumber) public view returns (bool) { uint256 endAt = lockEndAt(self); return ( self.lockedAt == 0 || blockNumber >= endAt.add(self.cooldownDuration) ); } function cooldownEndAt(State storage self) internal view returns (uint256) { return lockEndAt(self).add(self.cooldownDuration); } function lockEndAt(State storage self) internal view returns (uint256) { uint256 endAt = self.lockedAt.add(self.lockDuration); // if we unlocked early if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) { endAt = self.unlockedAt; } return endAt; } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @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"); } } /** * @dev Implementation of the {IERC777} interface. * * Largely taken from the OpenZeppelin ERC777 contract. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. * * It is important to note that no Mint events are emitted. Tokens are minted in batches * by a state change in a tree data structure, so emitting a Mint event for each user * is not possible. * */ contract PoolToken is Initializable, IERC20, IERC777 { using SafeMath for uint256; using Address for address; /** * Event emitted when a user or operator redeems tokens */ event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256("ERC777Token") bytes32 constant internal TOKENS_INTERFACE_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054; // keccak256("ERC20Token") bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH = 0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a; string internal _name; string internal _symbol; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] internal _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) internal _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) internal _operators; mapping(address => mapping(address => bool)) internal _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) internal _allowances; // The Pool that is bound to this token BasePool internal _pool; /** * @notice Initializes the PoolToken. * @param name The name of the token * @param symbol The token symbol * @param defaultOperators The default operators who are allowed to move tokens */ function init ( string memory name, string memory symbol, address[] memory defaultOperators, BasePool pool ) public initializer { require(bytes(name).length != 0, "PoolToken/name"); require(bytes(symbol).length != 0, "PoolToken/symbol"); require(address(pool) != address(0), "PoolToken/pool-zero"); _name = name; _symbol = symbol; _pool = pool; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this)); ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this)); } /** * @notice Returns the address of the Pool contract * @return The address of the pool contract */ function pool() public view returns (BasePool) { return _pool; } /** * @notice Calls the ERC777 transfer hook, and emits Redeemed and Transfer. Can only be called by the Pool contract. * @param from The address from which to redeem tokens * @param amount The amount of tokens to redeem */ function poolRedeem(address from, uint256 amount) external onlyPool { _callTokensToSend(from, from, address(0), amount, '', ''); emit Redeemed(from, from, amount, '', ''); emit Transfer(from, address(0), amount); } /** * @dev See {IERC777-name}. */ function name() public view returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev See {ERC20Detailed-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public view returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view returns (uint256) { return _pool.committedSupply(); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address _addr) external view returns (uint256) { return _pool.committedBalanceOf(_addr); } /** * @dev See {IERC777-send}. * * Also emits a {Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes calldata data) external { _send(msg.sender, msg.sender, recipient, amount, data, ""); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/transfer-zero"); address from = msg.sender; _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev Allows a user to withdraw their tokens as the underlying asset. * * Also emits a {Transfer} event for ERC20 compatibility. */ function redeem(uint256 amount, bytes calldata data) external { _redeem(msg.sender, msg.sender, amount, data, ""); } /** * @dev See {IERC777-burn}. Not currently implemented. * * Also emits a {Transfer} event for ERC20 compatibility. */ function burn(uint256, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) external { require(msg.sender != operator, "PoolToken/auth-self"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[msg.sender][operator]; } else { _operators[msg.sender][operator] = true; } emit AuthorizedOperator(operator, msg.sender); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) external { require(operator != msg.sender, "PoolToken/revoke-self"); if (_defaultOperators[operator]) { _revokedDefaultOperators[msg.sender][operator] = true; } else { delete _operators[msg.sender][operator]; } emit RevokedOperator(operator, msg.sender); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external { require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator"); _send(msg.sender, sender, recipient, amount, data, operatorData); } /** * @dev See {IERC777-operatorBurn}. * * Currently not supported */ function operatorBurn(address, uint256, bytes calldata, bytes calldata) external { revert("PoolToken/no-support"); } /** * @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user. * * Emits {Redeemed} and {Transfer} events. */ function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external { require(isOperatorFor(msg.sender, account), "PoolToken/not-operator"); _redeem(msg.sender, account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) external returns (bool) { address holder = msg.sender; _approve(holder, spender, value); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "PoolToken/negative")); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {Transfer} and {Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) { require(recipient != address(0), "PoolToken/to-zero"); require(holder != address(0), "PoolToken/from-zero"); address spender = msg.sender; _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * Called by the associated Pool to emit `Mint` events. * @param amount The amount that was minted */ function poolMint(uint256 amount) external onlyPool { _mintEvents(address(_pool), address(_pool), amount, '', ''); } /** * Emits {Minted} and {IERC20-Transfer} events. */ function _mintEvents( address operator, address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal { emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _send( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); require(to != address(0), "PoolToken/to-zero"); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, false); } /** * @dev Redeems tokens for the underlying asset. * @param operator address operator requesting the operation * @param from address token holder address * @param amount uint256 amount of tokens to redeem * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _redeem( address operator, address from, uint256 amount, bytes memory data, bytes memory operatorData ) private { require(from != address(0), "PoolToken/from-zero"); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _pool.withdrawCommittedDepositFrom(from, amount); emit Redeemed(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } /** * @notice Moves tokens from one user to another. Emits Sent and Transfer events. */ function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _pool.moveCommitted(from, to, amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * Approves of a token spend by a spender for a holder. * @param holder The address from which the tokens are spent * @param spender The address that is spending the tokens * @param value The amount of tokens to spend */ function _approve(address holder, address spender, uint256 value) private { require(spender != address(0), "PoolToken/from-zero"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal notLocked { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck whether to require that, if the recipient is a contract, it has registered a IERC777Recipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "PoolToken/no-recip-inter"); } } /** * @notice Requires the sender to be the pool contract */ modifier onlyPool() { require(msg.sender == address(_pool), "PoolToken/only-pool"); _; } /** * @notice Requires the contract to be unlocked */ modifier notLocked() { require(!_pool.isLocked(), "PoolToken/is-locked"); _; } } /** * @title The Pool contract * @author Brendan Asselstine * @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws. * Funds are immediately deposited and withdrawn from the Compound cToken contract. * Draws go through three stages: open, committed and rewarded in that order. * Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance. * When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated. * When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being * proportional to their committed balance vs the total committed balance of all users. * * * With the above in mind, there is always an open draw and possibly a committed draw. The progression is: * * Step 1: Draw 1 Open * Step 2: Draw 2 Open | Draw 1 Committed * Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded * Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded * Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded * Step X: ... */ contract BasePool is Initializable, ReentrancyGuard { using DrawManager for DrawManager.State; using SafeMath for uint256; using Roles for Roles.Role; using Blocklock for Blocklock.State; bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1)); IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("PoolTogetherRewardListener") bytes32 constant internal REWARD_LISTENER_INTERFACE_HASH = 0x68f03b0b1a978ee238a70b362091d993343460bc1a2830ab3f708936d9f564a4; /** * Emitted when a user deposits into the Pool. * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event Deposited(address indexed sender, uint256 amount); /** * Emitted when a user deposits into the Pool and the deposit is immediately committed * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event DepositedAndCommitted(address indexed sender, uint256 amount); /** * Emitted when Sponsors have deposited into the Pool * @param sender The purchaser of the tickets * @param amount The size of the deposit */ event SponsorshipDeposited(address indexed sender, uint256 amount); /** * Emitted when an admin has been added to the Pool. * @param admin The admin that was added */ event AdminAdded(address indexed admin); /** * Emitted when an admin has been removed from the Pool. * @param admin The admin that was removed */ event AdminRemoved(address indexed admin); /** * Emitted when a user withdraws from the pool. * @param sender The user that is withdrawing from the pool * @param amount The amount that the user withdrew */ event Withdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws their sponsorship and fees from the pool. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their open deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event OpenDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when a user withdraws from their committed deposit. * @param sender The user that is withdrawing * @param amount The amount they are withdrawing */ event CommittedDepositWithdrawn(address indexed sender, uint256 amount); /** * Emitted when an address collects a fee * @param sender The address collecting the fee * @param amount The fee amount * @param drawId The draw from which the fee was awarded */ event FeeCollected(address indexed sender, uint256 amount, uint256 drawId); /** * Emitted when a new draw is opened for deposit. * @param drawId The draw id * @param feeBeneficiary The fee beneficiary for this draw * @param secretHash The committed secret hash * @param feeFraction The fee fraction of the winnings to be given to the beneficiary */ event Opened( uint256 indexed drawId, address indexed feeBeneficiary, bytes32 secretHash, uint256 feeFraction ); /** * Emitted when a draw is committed. * @param drawId The draw id */ event Committed( uint256 indexed drawId ); /** * Emitted when a draw is rewarded. * @param drawId The draw id * @param winner The address of the winner * @param entropy The entropy used to select the winner * @param winnings The net winnings given to the winner * @param fee The fee being given to the draw beneficiary */ event Rewarded( uint256 indexed drawId, address indexed winner, bytes32 entropy, uint256 winnings, uint256 fee ); /** * Emitted when a RewardListener call fails * @param drawId The draw id * @param winner The address that one the draw * @param impl The implementation address of the RewardListener */ event RewardListenerFailed( uint256 indexed drawId, address indexed winner, address indexed impl ); /** * Emitted when the fee fraction is changed. Takes effect on the next draw. * @param feeFraction The next fee fraction encoded as a fixed point 18 decimal */ event NextFeeFractionChanged(uint256 feeFraction); /** * Emitted when the next fee beneficiary changes. Takes effect on the next draw. * @param feeBeneficiary The next fee beneficiary */ event NextFeeBeneficiaryChanged(address indexed feeBeneficiary); /** * Emitted when an admin pauses the contract */ event DepositsPaused(address indexed sender); /** * Emitted when an admin unpauses the contract */ event DepositsUnpaused(address indexed sender); /** * Emitted when the draw is rolled over in the event that the secret is forgotten. */ event RolledOver(uint256 indexed drawId); struct Draw { uint256 feeFraction; //fixed point 18 address feeBeneficiary; uint256 openedBlock; bytes32 secretHash; bytes32 entropy; address winner; uint256 netWinnings; uint256 fee; } /** * The Compound cToken that this Pool is bound to. */ ICErc20 public cToken; /** * The fee beneficiary to use for subsequent Draws. */ address public nextFeeBeneficiary; /** * The fee fraction to use for subsequent Draws. */ uint256 public nextFeeFraction; /** * The total of all balances */ uint256 public accountedBalance; /** * The total deposits and winnings for each user. */ mapping (address => uint256) internal balances; /** * A mapping of draw ids to Draw structures */ mapping(uint256 => Draw) internal draws; /** * A structure that is used to manage the user's odds of winning. */ DrawManager.State internal drawState; /** * A structure containing the administrators */ Roles.Role internal admins; /** * Whether the contract is paused */ bool public paused; Blocklock.State internal blocklock; PoolToken public poolToken; /** * @notice Initializes a new Pool contract. * @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries. * @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens. * @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number. * @param _feeBeneficiary The address that will receive the fee fraction */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 _lockDuration, uint256 _cooldownDuration ) public initializer { require(_owner != address(0), "Pool/owner-zero"); require(_cToken != address(0), "Pool/ctoken-zero"); cToken = ICErc20(_cToken); _addAdmin(_owner); _setNextFeeFraction(_feeFraction); _setNextFeeBeneficiary(_feeBeneficiary); initBlocklock(_lockDuration, _cooldownDuration); } function setPoolToken(PoolToken _poolToken) external onlyAdmin { require(address(poolToken) == address(0), "Pool/token-was-set"); require(address(_poolToken.pool()) == address(this), "Pool/token-mismatch"); poolToken = _poolToken; } function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal { blocklock.setLockDuration(_lockDuration); blocklock.setCooldownDuration(_cooldownDuration); } /** * @notice Opens a new Draw. * @param _secretHash The secret hash to commit to the Draw. */ function open(bytes32 _secretHash) internal { drawState.openNextDraw(); draws[drawState.openDrawIndex] = Draw( nextFeeFraction, nextFeeBeneficiary, block.number, _secretHash, bytes32(0), address(0), uint256(0), uint256(0) ); emit Opened( drawState.openDrawIndex, nextFeeBeneficiary, _secretHash, nextFeeFraction ); } /** * @notice Emits the Committed event for the current open draw. */ function emitCommitted() internal { uint256 drawId = currentOpenDrawId(); emit Committed(drawId); if (address(poolToken) != address(0)) { poolToken.poolMint(openSupply()); } } /** * @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice: * the first after Pool contract creation and the second immediately after. * Can only be called by an admin. * May fire the Committed event, and always fires the Open event. * @param nextSecretHash The secret hash to use to open a new Draw */ function openNextDraw(bytes32 nextSecretHash) public onlyAdmin { if (currentCommittedDrawId() > 0) { require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward"); } if (currentOpenDrawId() != 0) { emitCommitted(); } open(nextSecretHash); } /** * @notice Ignores the current draw, and opens the next draw. * @dev This function will be removed once the winner selection has been decentralized. * @param nextSecretHash The hash to commit for the next draw */ function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin { rollover(); openNextDraw(nextSecretHash); } /** * @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash. * Can only be called by an admin. * Fires the Rewarded event, the Committed event, and the Open event. * @param nextSecretHash The secret hash to use to open a new Draw * @param lastSecret The secret to reveal to reward the current committed Draw. * @param _salt The salt that was used to conceal the secret */ function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin { reward(lastSecret, _salt); openNextDraw(nextSecretHash); } /** * @notice Rewards the winner for the current committed Draw using the passed secret. * The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. * A winner is calculated using the revealed secret. * If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. * The draw beneficiary's balance is updated with the fee. * The accounted balance is updated to include the fee and, if there was a winner, the net winnings. * Fires the Rewarded event. * @param _secret The secret to reveal for the current committed Draw * @param _salt The salt that was used to conceal the secret */ function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant { // require that there is a committed draw // require that the committed draw has not been rewarded uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret"); // derive entropy from the revealed secret bytes32 entropy = keccak256(abi.encodePacked(_secret)); _reward(drawId, draw, entropy); } function _reward(uint256 drawId, Draw storage draw, bytes32 entropy) internal { blocklock.unlock(block.number); // Select the winner using the hash as entropy address winningAddress = calculateWinner(entropy); // Calculate the gross winnings uint256 underlyingBalance = balance(); uint256 grossWinnings; // It's possible when the APR is zero that the underlying balance will be slightly lower than the accountedBalance // due to rounding errors in the Compound contract. if (underlyingBalance > accountedBalance) { grossWinnings = capWinnings(underlyingBalance.sub(accountedBalance)); } // Calculate the beneficiary fee uint256 fee = calculateFee(draw.feeFraction, grossWinnings); // Update balance of the beneficiary balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee); // Calculate the net winnings uint256 netWinnings = grossWinnings.sub(fee); draw.winner = winningAddress; draw.netWinnings = netWinnings; draw.fee = fee; draw.entropy = entropy; // If there is a winner who is to receive non-zero winnings if (winningAddress != address(0) && netWinnings != 0) { // Updated the accounted total accountedBalance = underlyingBalance; // Update balance of the winner balances[winningAddress] = balances[winningAddress].add(netWinnings); // Enter their winnings into the open draw drawState.deposit(winningAddress, netWinnings); callRewarded(winningAddress, netWinnings, drawId); } else { // Only account for the fee accountedBalance = accountedBalance.add(fee); } emit Rewarded( drawId, winningAddress, entropy, netWinnings, fee ); emit FeeCollected(draw.feeBeneficiary, fee, drawId); } /** * @notice Calls the reward listener for the winner, if a listener exists. * @dev Checks for a listener using the ERC1820 registry. The listener is given a gas stipend of 200,000 to run the function. * The number 200,000 was selected because it's safely above the gas requirements for PoolTogether [Pod](https://github.com/pooltogether/pods) contract. * * @param winner The winner. If they have a listener registered in the ERC1820 registry it will be called. * @param netWinnings The amount that was won. * @param drawId The draw id that was won. */ function callRewarded(address winner, uint256 netWinnings, uint256 drawId) internal { address impl = ERC1820_REGISTRY.getInterfaceImplementer(winner, REWARD_LISTENER_INTERFACE_HASH); if (impl != address(0)) { (bool success,) = impl.call.gas(200000)(abi.encodeWithSignature("rewarded(address,uint256,uint256)", winner, netWinnings, drawId)); if (!success) { emit RewardListenerFailed(drawId, winner, impl); } } } /** * @notice A function that skips the reward for the committed draw id. * @dev This function will be removed once the entropy is decentralized. */ function rollover() public onlyAdmin requireCommittedNoReward { uint256 drawId = currentCommittedDrawId(); Draw storage draw = draws[drawId]; draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER; emit RolledOver( drawId ); emit Rewarded( drawId, address(0), ROLLED_OVER_ENTROPY_MAGIC_NUMBER, 0, 0 ); } /** * @notice Ensures that the winnings don't overflow. Note that we can make this integer max, because the fee * is always less than zero (meaning the FixidityLib.multiply will always make the number smaller) */ function capWinnings(uint256 _grossWinnings) internal pure returns (uint256) { uint256 max = uint256(FixidityLib.maxNewFixed()); if (_grossWinnings > max) { return max; } return _grossWinnings; } /** * @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings. * @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number. * @param _grossWinnings The gross winnings to take a fraction of. */ function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) { int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings)); // _feeFraction *must* be less than 1 ether, so it will never overflow int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18))); return uint256(FixidityLib.fromFixed(feeFixed)); } /** * @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken. * Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time. * The deposit will immediately be added to Compound and the interest will contribute to the next draw. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositSponsorship(uint256 _amount) public unlessDepositsPaused nonReentrant { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the sponsorship amount _depositSponsorshipFrom(msg.sender, _amount); } /** * @notice Deposits the token balance for this contract as a sponsorship. * If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship. */ function transferBalanceToSponsorship() public unlessDepositsPaused { // Deposit the sponsorship amount _depositSponsorshipFrom(address(this), token().balanceOf(address(this))); } /** * @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken. * Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning * proportional to the total committed balance of all users. * @param _amount The amount of the token underlying the cToken to deposit. */ function depositPool(uint256 _amount) public requireOpenDraw unlessDepositsPaused nonReentrant notLocked { // Transfer the tokens into this contract require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail"); // Deposit the funds _depositPoolFrom(msg.sender, _amount); } /** * @notice Deposits sponsorship for a user * @param _spender The user who is sponsoring * @param _amount The amount they are sponsoring */ function _depositSponsorshipFrom(address _spender, uint256 _amount) internal { // Deposit the funds _depositFrom(_spender, _amount); emit SponsorshipDeposited(_spender, _amount); } /** * @notice Deposits into the pool for a user. The deposit will be open until the next draw is committed. * @param _spender The user who is depositing * @param _amount The amount the user is depositing */ function _depositPoolFrom(address _spender, uint256 _amount) internal { // Update the user's eligibility drawState.deposit(_spender, _amount); _depositFrom(_spender, _amount); emit Deposited(_spender, _amount); } /** * @notice Deposits into the pool for a user. The deposit is made part of the currently committed draw * @param _spender The user who is depositing * @param _amount The amount to deposit */ function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked { // Update the user's eligibility drawState.depositCommitted(_spender, _amount); _depositFrom(_spender, _amount); emit DepositedAndCommitted(_spender, _amount); } /** * @notice Deposits into the pool for a user. Updates their balance and transfers their tokens into this contract. * @param _spender The user who is depositing * @param _amount The amount they are depositing */ function _depositFrom(address _spender, uint256 _amount) internal { // Update the user's balance balances[_spender] = balances[_spender].add(_amount); // Update the total of this contract accountedBalance = accountedBalance.add(_amount); // Deposit into Compound require(token().approve(address(cToken), _amount), "Pool/approve"); require(cToken.mint(_amount) == 0, "Pool/supply"); } /** * Withdraws the given amount from the user's deposits. It first withdraws from their sponsorship, * then their open deposits, then their committed deposits. * * @param amount The amount to withdraw. */ function withdraw(uint256 amount) public nonReentrant notLocked { uint256 remainingAmount = amount; // first sponsorship uint256 sponsorshipAndFeesBalance = sponsorshipAndFeeBalanceOf(msg.sender); if (sponsorshipAndFeesBalance < remainingAmount) { withdrawSponsorshipAndFee(sponsorshipAndFeesBalance); remainingAmount = remainingAmount.sub(sponsorshipAndFeesBalance); } else { withdrawSponsorshipAndFee(remainingAmount); return; } // now pending uint256 pendingBalance = drawState.openBalanceOf(msg.sender); if (pendingBalance < remainingAmount) { _withdrawOpenDeposit(msg.sender, pendingBalance); remainingAmount = remainingAmount.sub(pendingBalance); } else { _withdrawOpenDeposit(msg.sender, remainingAmount); return; } // now committed. remainingAmount should not be greater than committed balance. _withdrawCommittedDeposit(msg.sender, remainingAmount); } /** * @notice Withdraw the sender's entire balance back to them. */ function withdraw() public nonReentrant notLocked { uint256 committedBalance = drawState.committedBalanceOf(msg.sender); uint256 balance = balances[msg.sender]; // Update their chances of winning drawState.withdraw(msg.sender); _withdraw(msg.sender, balance); if (address(poolToken) != address(0)) { poolToken.poolRedeem(msg.sender, committedBalance); } emit Withdrawn(msg.sender, balance); } /** * Withdraws only from the sender's sponsorship and fee balances * @param _amount The amount to withdraw */ function withdrawSponsorshipAndFee(uint256 _amount) public { uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender); require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee"); _withdraw(msg.sender, _amount); emit SponsorshipAndFeesWithdrawn(msg.sender, _amount); } /** * Returns the total balance of the user's sponsorship and fees * @param _sender The user whose balance should be returned */ function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) { return balances[_sender].sub(drawState.balanceOf(_sender)); } /** * Withdraws from the user's open deposits * @param _amount The amount to withdraw */ function withdrawOpenDeposit(uint256 _amount) public nonReentrant notLocked { _withdrawOpenDeposit(msg.sender, _amount); } function _withdrawOpenDeposit(address sender, uint256 _amount) internal { drawState.withdrawOpen(sender, _amount); _withdraw(sender, _amount); emit OpenDepositWithdrawn(sender, _amount); } /** * Withdraws from the user's committed deposits * @param _amount The amount to withdraw */ function withdrawCommittedDeposit(uint256 _amount) public nonReentrant notLocked returns (bool) { _withdrawCommittedDeposit(msg.sender, _amount); return true; } function _withdrawCommittedDeposit(address sender, uint256 _amount) internal { _withdrawCommittedDepositAndEmit(sender, _amount); if (address(poolToken) != address(0)) { poolToken.poolRedeem(sender, _amount); } } /** * Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token. * @param _from The user to withdraw from * @param _amount The amount to withdraw */ function withdrawCommittedDepositFrom( address _from, uint256 _amount ) external onlyToken notLocked returns (bool) { return _withdrawCommittedDepositAndEmit(_from, _amount); } /** * A function that withdraws committed deposits for a user and emits the corresponding events. * @param _from User to withdraw for * @param _amount The amount to withdraw */ function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) { drawState.withdrawCommitted(_from, _amount); _withdraw(_from, _amount); emit CommittedDepositWithdrawn(_from, _amount); return true; } /** * @notice Allows the associated PoolToken to move committed tokens from one user to another. * @param _from The account to move tokens from * @param _to The account that is receiving the tokens * @param _amount The amount of tokens to transfer */ function moveCommitted( address _from, address _to, uint256 _amount ) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) { balances[_from] = balances[_from].sub(_amount, "move could not sub amount"); balances[_to] = balances[_to].add(_amount); drawState.withdrawCommitted(_from, _amount); drawState.depositCommitted(_to, _amount); return true; } /** * @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance. */ function _withdraw(address _sender, uint256 _amount) internal { uint256 balance = balances[_sender]; require(_amount <= balance, "Pool/no-funds"); // Update the user's balance balances[_sender] = balance.sub(_amount); // Update the total of this contract accountedBalance = accountedBalance.sub(_amount); // Withdraw from Compound and transfer require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem"); require(token().transfer(_sender, _amount), "Pool/transfer"); } /** * @notice Returns the id of the current open Draw. * @return The current open Draw id */ function currentOpenDrawId() public view returns (uint256) { return drawState.openDrawIndex; } /** * @notice Returns the id of the current committed Draw. * @return The current committed Draw id */ function currentCommittedDrawId() public view returns (uint256) { if (drawState.openDrawIndex > 1) { return drawState.openDrawIndex - 1; } else { return 0; } } /** * @notice Returns whether the current committed draw has been rewarded * @return True if the current committed draw has been rewarded, false otherwise */ function currentCommittedDrawHasBeenRewarded() internal view returns (bool) { Draw storage draw = draws[currentCommittedDrawId()]; return draw.entropy != bytes32(0); } /** * @notice Gets information for a given draw. * @param _drawId The id of the Draw to retrieve info for. * @return Fields including: * feeFraction: the fee fraction * feeBeneficiary: the beneficiary of the fee * openedBlock: The block at which the draw was opened * secretHash: The hash of the secret committed to this draw. * entropy: the entropy used to select the winner * winner: the address of the winner * netWinnings: the total winnings less the fee * fee: the fee taken by the beneficiary */ function getDraw(uint256 _drawId) public view returns ( uint256 feeFraction, address feeBeneficiary, uint256 openedBlock, bytes32 secretHash, bytes32 entropy, address winner, uint256 netWinnings, uint256 fee ) { Draw storage draw = draws[_drawId]; feeFraction = draw.feeFraction; feeBeneficiary = draw.feeBeneficiary; openedBlock = draw.openedBlock; secretHash = draw.secretHash; entropy = draw.entropy; winner = draw.winner; netWinnings = draw.netWinnings; fee = draw.fee; } /** * @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning. * @param _addr The address of the user * @return The total committed balance for the user */ function committedBalanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning. * @param _addr The address of the user * @return The total open balance for the user */ function openBalanceOf(address _addr) external view returns (uint256) { return drawState.openBalanceOf(_addr); } /** * @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits. * @param _addr The address of the user to check. * @return The user's current balance. */ function totalBalanceOf(address _addr) external view returns (uint256) { return balances[_addr]; } /** * @notice Returns a user's committed balance. This is the balance of their Pool tokens. * @param _addr The address of the user to check. * @return The user's current balance. */ function balanceOf(address _addr) external view returns (uint256) { return drawState.committedBalanceOf(_addr); } /** * @notice Calculates a winner using the passed entropy for the current committed balances. * @param _entropy The entropy to use to select the winner * @return The winning address */ function calculateWinner(bytes32 _entropy) public view returns (address) { return drawState.drawWithEntropy(_entropy); } /** * @notice Returns the total committed balance. Used to compute an address's chances of winning. * @return The total committed balance. */ function committedSupply() public view returns (uint256) { return drawState.committedSupply(); } /** * @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw. * @return The total open balance */ function openSupply() public view returns (uint256) { return drawState.openSupply(); } /** * @notice Calculates the total estimated interest earned for the given number of blocks * @param _blocks The number of block that interest accrued for * @return The total estimated interest as a 18 point fixed decimal. */ function estimatedInterestRate(uint256 _blocks) public view returns (uint256) { return supplyRatePerBlock().mul(_blocks); } /** * @notice Convenience function to return the supplyRatePerBlock value from the money market contract. * @return The cToken supply rate per block */ function supplyRatePerBlock() public view returns (uint256) { return cToken.supplyRatePerBlock(); } /** * @notice Sets the beneficiary fee fraction for subsequent Draws. * Fires the NextFeeFractionChanged event. * Can only be called by an admin. * @param _feeFraction The fee fraction to use. * Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether). */ function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin { _setNextFeeFraction(_feeFraction); } function _setNextFeeFraction(uint256 _feeFraction) internal { require(_feeFraction <= 1 ether, "Pool/less-1"); nextFeeFraction = _feeFraction; emit NextFeeFractionChanged(_feeFraction); } /** * @notice Sets the fee beneficiary for subsequent Draws. * Can only be called by admins. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin { _setNextFeeBeneficiary(_feeBeneficiary); } /** * @notice Sets the fee beneficiary for subsequent Draws. * @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address. */ function _setNextFeeBeneficiary(address _feeBeneficiary) internal { require(_feeBeneficiary != address(0), "Pool/not-zero"); nextFeeBeneficiary = _feeBeneficiary; emit NextFeeBeneficiaryChanged(_feeBeneficiary); } /** * @notice Adds an administrator. * Can only be called by administrators. * Fires the AdminAdded event. * @param _admin The address of the admin to add */ function addAdmin(address _admin) public onlyAdmin { _addAdmin(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function isAdmin(address _admin) public view returns (bool) { return admins.has(_admin); } /** * @notice Checks whether a given address is an administrator. * @param _admin The address to check * @return True if the address is an admin, false otherwise. */ function _addAdmin(address _admin) internal { admins.add(_admin); emit AdminAdded(_admin); } /** * @notice Removes an administrator * Can only be called by an admin. * Admins cannot remove themselves. This ensures there is always one admin. * @param _admin The address of the admin to remove */ function removeAdmin(address _admin) public onlyAdmin { require(admins.has(_admin), "Pool/no-admin"); require(_admin != msg.sender, "Pool/remove-self"); admins.remove(_admin); emit AdminRemoved(_admin); } /** * Requires that there is a committed draw that has not been rewarded. */ modifier requireCommittedNoReward() { require(currentCommittedDrawId() > 0, "Pool/committed"); require(!currentCommittedDrawHasBeenRewarded(), "Pool/already"); _; } /** * @notice Returns the token underlying the cToken. * @return An ERC20 token address */ function token() public view returns (IERC20) { return IERC20(cToken.underlying()); } /** * @notice Returns the underlying balance of this contract in the cToken. * @return The cToken underlying balance for this contract. */ function balance() public returns (uint256) { return cToken.balanceOfUnderlying(address(this)); } /** * @notice Locks the movement of tokens (essentially the committed deposits and winnings) * @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes. */ function lockTokens() public onlyAdmin { blocklock.lock(block.number); } /** * @notice Unlocks the movement of tokens (essentially the committed deposits) */ function unlockTokens() public onlyAdmin { blocklock.unlock(block.number); } /** * Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue * to collect rewards and withdraw, but eventually the Pool will grow smaller. * * emits DepositsPaused */ function pauseDeposits() public unlessDepositsPaused onlyAdmin { paused = true; emit DepositsPaused(msg.sender); } /** * @notice Unpauses all deposits into the contract * * emits DepositsUnpaused */ function unpauseDeposits() public whenDepositsPaused onlyAdmin { paused = false; emit DepositsUnpaused(msg.sender); } /** * @notice Check if the contract is locked. * @return True if the contract is locked, false otherwise */ function isLocked() public view returns (bool) { return blocklock.isLocked(block.number); } /** * @notice Returns the block number at which the lock expires * @return The block number at which the lock expires */ function lockEndAt() public view returns (uint256) { return blocklock.lockEndAt(); } /** * @notice Check cooldown end block * @return The block number at which the cooldown ends and the contract can be re-locked */ function cooldownEndAt() public view returns (uint256) { return blocklock.cooldownEndAt(); } /** * @notice Returns whether the contract can be locked * @return True if the contract can be locked, false otherwise */ function canLock() public view returns (bool) { return blocklock.canLock(block.number); } /** * @notice Duration of the lock * @return Returns the duration of the lock in blocks. */ function lockDuration() public view returns (uint256) { return blocklock.lockDuration; } /** * @notice Returns the cooldown duration. The cooldown period starts after the Pool has been unlocked. * The Pool cannot be locked during the cooldown period. * @return The cooldown duration in blocks */ function cooldownDuration() public view returns (uint256) { return blocklock.cooldownDuration; } /** * @notice requires the pool not to be locked */ modifier notLocked() { require(!blocklock.isLocked(block.number), "Pool/locked"); _; } /** * @notice requires the pool to be locked */ modifier onlyLocked() { require(blocklock.isLocked(block.number), "Pool/unlocked"); _; } /** * @notice requires the caller to be an admin */ modifier onlyAdmin() { require(admins.has(msg.sender), "Pool/admin"); _; } /** * @notice Requires an open draw to exist */ modifier requireOpenDraw() { require(currentOpenDrawId() != 0, "Pool/no-open"); _; } /** * @notice Requires deposits to be paused */ modifier whenDepositsPaused() { require(paused, "Pool/d-not-paused"); _; } /** * @notice Requires deposits not to be paused */ modifier unlessDepositsPaused() { require(!paused, "Pool/d-paused"); _; } /** * @notice Requires the caller to be the pool token */ modifier onlyToken() { require(msg.sender == address(poolToken), "Pool/only-token"); _; } /** * @notice requires the passed user's committed balance to be greater than or equal to the passed amount * @param _from The user whose committed balance should be checked * @param _amount The minimum amount they must have */ modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) { uint256 committedBalance = drawState.committedBalanceOf(_from); require(_amount <= committedBalance, "not enough funds"); _; } } contract ScdMcdMigration { SaiTubLike public tub; VatLike public vat; ManagerLike public cdpManager; JoinLike public saiJoin; JoinLike public wethJoin; JoinLike public daiJoin; constructor( address tub_, // SCD tub contract address address cdpManager_, // MCD manager contract address address saiJoin_, // MCD SAI collateral adapter contract address address wethJoin_, // MCD ETH collateral adapter contract address address daiJoin_ // MCD DAI adapter contract address ) public { tub = SaiTubLike(tub_); cdpManager = ManagerLike(cdpManager_); vat = VatLike(cdpManager.vat()); saiJoin = JoinLike(saiJoin_); wethJoin = JoinLike(wethJoin_); daiJoin = JoinLike(daiJoin_); require(wethJoin.gem() == tub.gem(), "non-matching-weth"); require(saiJoin.gem() == tub.sai(), "non-matching-sai"); tub.gov().approve(address(tub), uint(-1)); tub.skr().approve(address(tub), uint(-1)); tub.sai().approve(address(tub), uint(-1)); tub.sai().approve(address(saiJoin), uint(-1)); wethJoin.gem().approve(address(wethJoin), uint(-1)); daiJoin.dai().approve(address(daiJoin), uint(-1)); vat.hope(address(daiJoin)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } // Function to swap SAI to DAI // This function is to be used by users that want to get new DAI in exchange of old one (aka SAI) // wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one) function swapSaiToDai( uint wad ) external { // Get wad amount of SAI from user's wallet: saiJoin.gem().transferFrom(msg.sender, address(this), wad); // Join the SAI wad amount to the `vat`: saiJoin.join(address(this), wad); // Lock the SAI wad amount to the CDP and generate the same wad amount of DAI vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad)); // Send DAI wad amount as a ERC20 token to the user's wallet daiJoin.exit(msg.sender, wad); } // Function to swap DAI to SAI // This function is to be used by users that want to get SAI in exchange of DAI // wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP function swapDaiToSai( uint wad ) external { // Get wad amount of DAI from user's wallet: daiJoin.dai().transferFrom(msg.sender, address(this), wad); // Join the DAI wad amount to the vat: daiJoin.join(address(this), wad); // Payback the DAI wad amount and unlocks the same value of SAI collateral vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad)); // Send SAI wad amount as a ERC20 token to the user's wallet saiJoin.exit(msg.sender, wad); } // Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage. // In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio) function migrate( bytes32 cup ) external returns (uint cdp) { // Get values uint debtAmt = tub.tab(cup); // CDP SAI debt uint pethAmt = tub.ink(cup); // CDP locked collateral uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH // Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio // This is not actually a problem as this ilk will only be accessed by this migration contract, // which will make sure to have the amounts balanced out at the end of the execution. vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), -toInt(debtAmt), 0 ); saiJoin.exit(address(this), debtAmt); // SAI is exited as a token // Shut SAI CDP and gets WETH back tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call) tub.exit(pethAmt); // Converts PETH to WETH // Open future user's CDP in MCD cdp = cdpManager.open(wethJoin.ilk(), address(this)); // Join WETH to Adapter wethJoin.join(cdpManager.urns(cdp), ethAmt); // Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP (, uint rate,,,) = vat.ilks(wethJoin.ilk()); cdpManager.frob( cdp, toInt(ethAmt), toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt ); // Move DAI generated to migration contract (to recover the used funds) cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27)); // Re-balance MCD SAI migration contract's CDP vat.frob( bytes32(saiJoin.ilk()), address(this), address(this), address(this), 0, -toInt(debtAmt) ); // Set ownership of CDP to the user cdpManager.give(cdp, msg.sender); } } /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } /** * @title MCDAwarePool * @author Brendan Asselstine [email protected] * @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to * detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai * and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for * users to encourage them to migrate to the MCD Pool. */ contract MCDAwarePool is BasePool, IERC777Recipient { IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensRecipient") bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; uint256 internal constant DEFAULT_LOCK_DURATION = 40; uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80; /** * @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts) */ ScdMcdMigration public scdMcdMigration; /** * @notice The address of the Sai Pool contract */ MCDAwarePool public saiPool; /** * @notice Initializes the contract. * @param _owner The initial administrator of the contract * @param _cToken The Compound cToken to bind this Pool to * @param _feeFraction The fraction of the winnings to give to the beneficiary * @param _feeBeneficiary The beneficiary who receives the fee */ function init ( address _owner, address _cToken, uint256 _feeFraction, address _feeBeneficiary, uint256 lockDuration, uint256 cooldownDuration ) public initializer { super.init( _owner, _cToken, _feeFraction, _feeBeneficiary, lockDuration, cooldownDuration ); initRegistry(); initBlocklock(lockDuration, cooldownDuration); } /** * @notice Used to initialize the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock. */ function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public { initRegistry(); if (blocklock.lockDuration == 0) { initBlocklock(lockDuration, cooldownDuration); } } function initRegistry() internal { ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin { _initMigration(_scdMcdMigration, _saiPool); } function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal { require(address(scdMcdMigration) == address(0), "Pool/init"); require(address(_scdMcdMigration) != address(0), "Pool/mig-def"); scdMcdMigration = _scdMcdMigration; saiPool = _saiPool; // may be null } /** * @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool * and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of * the sender. It will reject all other tokens. * * If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the * open prize. This is to encourage migration. * * @param from The sender * @param amount The amount they are transferring */ function tokensReceived( address, // operator address from, address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface uint256 amount, bytes calldata, bytes calldata ) external unlessDepositsPaused { require(msg.sender == address(saiPoolToken()), "Pool/sai-only"); require(address(token()) == address(daiToken()), "Pool/not-dai"); // cash out of the Pool. This call transfers sai to this contract saiPoolToken().redeem(amount, ''); // approve of the transfer to the migration contract saiToken().approve(address(scdMcdMigration), amount); // migrate the sai to dai. The contract now has dai scdMcdMigration.swapSaiToDai(amount); if (currentCommittedDrawId() > 0) { // now deposit the dai as tickets _depositPoolFromCommitted(from, amount); } else { _depositPoolFrom(from, amount); } } /** * @notice Returns the address of the PoolSai pool token contract * @return The address of the Sai PoolToken contract */ function saiPoolToken() internal view returns (PoolToken) { if (address(saiPool) != address(0)) { return saiPool.poolToken(); } else { return PoolToken(0); } } /** * @notice Returns the address of the Sai token * @return The address of the sai token */ function saiToken() public returns (GemLike) { return scdMcdMigration.saiJoin().gem(); } /** * @notice Returns the address of the Dai token * @return The address of the Dai token. */ function daiToken() public returns (GemLike) { return scdMcdMigration.daiJoin().dai(); } }
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but tokensReceived() was not registered for the recipient @param operator address operator requesting the transfer @param from address token holder address @param to address recipient address @param amount uint256 amount of tokens to transfer @param userData bytes extra information provided by the token holder (if any) @param operatorData bytes extra information provided by the operator (if any) @param requireReceptionAck whether to require that, if the recipient is a contract, it has registered a IERC777Recipient/
function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); require(!to.isContract(), "PoolToken/no-recip-inter"); } }
8,015,362
[ 1, 1477, 358, 18, 7860, 8872, 1435, 309, 326, 1560, 353, 4104, 18, 868, 31537, 309, 326, 8027, 353, 279, 6835, 1496, 2430, 8872, 1435, 1703, 486, 4104, 364, 326, 8027, 225, 3726, 1758, 3726, 18709, 326, 7412, 225, 628, 1758, 1147, 10438, 1758, 225, 358, 1758, 8027, 1758, 225, 3844, 2254, 5034, 3844, 434, 2430, 358, 7412, 225, 13530, 1731, 2870, 1779, 2112, 635, 326, 1147, 10438, 261, 430, 1281, 13, 225, 3726, 751, 1731, 2870, 1779, 2112, 635, 326, 3726, 261, 430, 1281, 13, 225, 2583, 426, 472, 11931, 2856, 358, 2583, 716, 16, 309, 326, 8027, 353, 279, 6835, 16, 518, 711, 4104, 279, 467, 654, 39, 14509, 18241, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 1991, 5157, 8872, 12, 203, 1377, 1758, 3726, 16, 203, 1377, 1758, 628, 16, 203, 1377, 1758, 358, 16, 203, 1377, 2254, 5034, 3844, 16, 203, 1377, 1731, 3778, 13530, 16, 203, 1377, 1731, 3778, 3726, 751, 16, 203, 1377, 1426, 2583, 426, 472, 11931, 203, 225, 262, 203, 1377, 3238, 203, 225, 288, 203, 1377, 1758, 2348, 264, 273, 4232, 39, 2643, 3462, 67, 5937, 25042, 18, 588, 1358, 5726, 264, 12, 869, 16, 14275, 55, 67, 862, 7266, 1102, 2222, 67, 18865, 67, 15920, 1769, 203, 1377, 309, 261, 10442, 264, 480, 1758, 12, 20, 3719, 288, 203, 1850, 467, 654, 39, 14509, 18241, 12, 10442, 264, 2934, 7860, 8872, 12, 9497, 16, 628, 16, 358, 16, 3844, 16, 13530, 16, 3726, 751, 1769, 203, 1850, 2583, 12, 5, 869, 18, 291, 8924, 9334, 315, 2864, 1345, 19, 2135, 17, 266, 3449, 17, 2761, 8863, 203, 1377, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; import "../interfaces/ClientPhoenixAuthenticationInterface.sol"; import "../interfaces/PhoenixInterface.sol"; import "../interfaces/IdentityRegistryInterface.sol"; import "../zeppelin/math/SafeMath.sol"; import "../zeppelin/ownership/Ownable.sol"; import "./interfaces/PhoenixIdentityResolverInterface.sol"; import "./interfaces/PhoenixIdentityViaInterface.sol"; contract PhoenixIdentity is Ownable { using SafeMath for uint; // mapping of EIN to phoenix token deposits mapping (uint => uint) public deposits; // mapping from EIN to resolver to allowance mapping (uint => mapping (address => uint)) public resolverAllowances; // SC variables address public identityRegistryAddress; IdentityRegistryInterface private identityRegistry; address public phoenixTokenAddress; PhoenixInterface private phoenixToken; address public clientPhoenixAuthenticationAddress; ClientPhoenixAuthenticationInterface private clientPhoenixAuthentication; // signature variables uint public signatureTimeout = 1 days; mapping (uint => uint) public signatureNonce; constructor (address _identityRegistryAddress, address _phoenixTokenAddress) public { setAddresses(_identityRegistryAddress, _phoenixTokenAddress); } // enforces that a particular EIN exists modifier identityExists(uint ein, bool check) { require(identityRegistry.identityExists(ein) == check, "The EIN does not exist."); _; } // enforces signature timeouts modifier ensureSignatureTimeValid(uint timestamp) { require( // solium-disable-next-line security/no-block-members block.timestamp >= timestamp && block.timestamp < timestamp + signatureTimeout, "Timestamp is not valid." ); _; } // set the phoenix token and identity registry addresses function setAddresses(address _identityRegistryAddress, address _phoenixTokenAddress) public onlyOwner { identityRegistryAddress = _identityRegistryAddress; identityRegistry = IdentityRegistryInterface(identityRegistryAddress); phoenixTokenAddress = _phoenixTokenAddress; phoenixToken = PhoenixInterface(phoenixTokenAddress); } function setClientPhoenixAuthenticationAddress(address _clientPhoenixAuthenticationAddress) public onlyOwner { clientPhoenixAuthenticationAddress = _clientPhoenixAuthenticationAddress; clientPhoenixAuthentication = ClientPhoenixAuthenticationInterface(clientPhoenixAuthenticationAddress); } // wrap createIdentityDelegated and initialize the client phoenixAuthentication resolver function createIdentityDelegated( address recoveryAddress, address associatedAddress, address[] memory providers, string memory casedPhoenixId, uint8 v, bytes32 r, bytes32 s, uint timestamp ) public returns (uint ein) { address[] memory _providers = new address[](providers.length + 1); _providers[0] = address(this); for (uint i; i < providers.length; i++) { _providers[i + 1] = providers[i]; } uint _ein = identityRegistry.createIdentityDelegated( recoveryAddress, associatedAddress, _providers, new address[](0), v, r, s, timestamp ); _addResolver(_ein, clientPhoenixAuthenticationAddress, true, 0, abi.encode(associatedAddress, casedPhoenixId)); return _ein; } // permission addProvidersFor by signature function addProvidersFor( address approvingAddress, address[] memory providers, uint8 v, bytes32 r, bytes32 s, uint timestamp ) public ensureSignatureTimeValid(timestamp) { uint ein = identityRegistry.getEIN(approvingAddress); require( identityRegistry.isSigned( approvingAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize that these Providers be added to my Identity.", ein, providers, timestamp ) ), v, r, s ), "Permission denied." ); identityRegistry.addProvidersFor(ein, providers); } // permission removeProvidersFor by signature function removeProvidersFor( address approvingAddress, address[] memory providers, uint8 v, bytes32 r, bytes32 s, uint timestamp ) public ensureSignatureTimeValid(timestamp) { uint ein = identityRegistry.getEIN(approvingAddress); require( identityRegistry.isSigned( approvingAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize that these Providers be removed from my Identity.", ein, providers, timestamp ) ), v, r, s ), "Permission denied." ); identityRegistry.removeProvidersFor(ein, providers); } // permissioned addProvidersFor and removeProvidersFor by signature function upgradeProvidersFor( address approvingAddress, address[] memory newProviders, address[] memory oldProviders, uint8[2] memory v, bytes32[2] memory r, bytes32[2] memory s, uint[2] memory timestamp ) public { addProvidersFor(approvingAddress, newProviders, v[0], r[0], s[0], timestamp[0]); removeProvidersFor(approvingAddress, oldProviders, v[1], r[1], s[1], timestamp[1]); uint ein = identityRegistry.getEIN(approvingAddress); emit PhoenixIdentityProvidersUpgraded(ein, newProviders, oldProviders, approvingAddress); } // permission adding a resolver for identity of msg.sender function addResolver(address resolver, bool isPhoenixIdentity, uint withdrawAllowance, bytes memory extraData) public { _addResolver(identityRegistry.getEIN(msg.sender), resolver, isPhoenixIdentity, withdrawAllowance, extraData); } // permission adding a resolver for identity passed by a provider function addResolverAsProvider( uint ein, address resolver, bool isPhoenixIdentity, uint withdrawAllowance, bytes memory extraData ) public { require(identityRegistry.isProviderFor(ein, msg.sender), "The msg.sender is not a Provider for the passed EIN"); _addResolver(ein, resolver, isPhoenixIdentity, withdrawAllowance, extraData); } // permission addResolversFor by signature function addResolverFor( address approvingAddress, address resolver, bool isPhoenixIdentity, uint withdrawAllowance, bytes memory extraData, uint8 v, bytes32 r, bytes32 s, uint timestamp ) public { uint ein = identityRegistry.getEIN(approvingAddress); validateAddResolverForSignature( approvingAddress, ein, resolver, isPhoenixIdentity, withdrawAllowance, extraData, v, r, s, timestamp ); _addResolver(ein, resolver, isPhoenixIdentity, withdrawAllowance, extraData); } function validateAddResolverForSignature( address approvingAddress, uint ein, address resolver, bool isPhoenixIdentity, uint withdrawAllowance, bytes memory extraData, uint8 v, bytes32 r, bytes32 s, uint timestamp ) private view ensureSignatureTimeValid(timestamp) { require( identityRegistry.isSigned( approvingAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize that this resolver be added to my Identity.", ein, resolver, isPhoenixIdentity, withdrawAllowance, extraData, timestamp ) ), v, r, s ), "Permission denied." ); } // common logic for adding resolvers function _addResolver(uint ein, address resolver, bool isPhoenixIdentity, uint withdrawAllowance, bytes memory extraData) private { require(!identityRegistry.isResolverFor(ein, resolver), "Identity has already set this resolver."); address[] memory resolvers = new address[](1); resolvers[0] = resolver; identityRegistry.addResolversFor(ein, resolvers); if (isPhoenixIdentity) { resolverAllowances[ein][resolver] = withdrawAllowance; PhoenixIdentityResolverInterface phoenixIdentityResolver = PhoenixIdentityResolverInterface(resolver); if (phoenixIdentityResolver.callOnAddition()) require(phoenixIdentityResolver.onAddition(ein, withdrawAllowance, extraData), "Sign up failure."); emit PhoenixIdentityResolverAdded(ein, resolver, withdrawAllowance); } } // permission changing resolver allowances for identity of msg.sender function changeResolverAllowances(address[] memory resolvers, uint[] memory withdrawAllowances) public { changeResolverAllowances(identityRegistry.getEIN(msg.sender), resolvers, withdrawAllowances); } // change resolver allowances delegated function changeResolverAllowancesDelegated( address approvingAddress, address[] memory resolvers, uint[] memory withdrawAllowances, uint8 v, bytes32 r, bytes32 s ) public { uint ein = identityRegistry.getEIN(approvingAddress); uint nonce = signatureNonce[ein]++; require( identityRegistry.isSigned( approvingAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize this change in Resolver allowances.", ein, resolvers, withdrawAllowances, nonce ) ), v, r, s ), "Permission denied." ); changeResolverAllowances(ein, resolvers, withdrawAllowances); } // common logic to change resolver allowances function changeResolverAllowances(uint ein, address[] memory resolvers, uint[] memory withdrawAllowances) private { require(resolvers.length == withdrawAllowances.length, "Malformed inputs."); for (uint i; i < resolvers.length; i++) { require(identityRegistry.isResolverFor(ein, resolvers[i]), "Identity has not set this resolver."); resolverAllowances[ein][resolvers[i]] = withdrawAllowances[i]; emit PhoenixIdentityResolverAllowanceChanged(ein, resolvers[i], withdrawAllowances[i]); } } // permission removing a resolver for identity of msg.sender function removeResolver(address resolver, bool isPhoenixIdentity, bytes memory extraData) public { removeResolver(identityRegistry.getEIN(msg.sender), resolver, isPhoenixIdentity, extraData); } // permission removeResolverFor by signature function removeResolverFor( address approvingAddress, address resolver, bool isPhoenixIdentity, bytes memory extraData, uint8 v, bytes32 r, bytes32 s, uint timestamp ) public ensureSignatureTimeValid(timestamp) { uint ein = identityRegistry.getEIN(approvingAddress); validateRemoveResolverForSignature(approvingAddress, ein, resolver, isPhoenixIdentity, extraData, v, r, s, timestamp); removeResolver(ein, resolver, isPhoenixIdentity, extraData); } function validateRemoveResolverForSignature( address approvingAddress, uint ein, address resolver, bool isPhoenixIdentity, bytes memory extraData, uint8 v, bytes32 r, bytes32 s, uint timestamp ) private view { require( identityRegistry.isSigned( approvingAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize that these Resolvers be removed from my Identity.", ein, resolver, isPhoenixIdentity, extraData, timestamp ) ), v, r, s ), "Permission denied." ); } // common logic to remove resolvers function removeResolver(uint ein, address resolver, bool isPhoenixIdentity, bytes memory extraData) private { require(identityRegistry.isResolverFor(ein, resolver), "Identity has not yet set this resolver."); delete resolverAllowances[ein][resolver]; if (isPhoenixIdentity) { PhoenixIdentityResolverInterface phoenixIdentityResolver = PhoenixIdentityResolverInterface(resolver); if (phoenixIdentityResolver.callOnRemoval()) require(phoenixIdentityResolver.onRemoval(ein, extraData), "Removal failure."); emit PhoenixIdentityResolverRemoved(ein, resolver); } address[] memory resolvers = new address[](1); resolvers[0] = resolver; identityRegistry.removeResolversFor(ein, resolvers); } function triggerRecoveryAddressChangeFor( address approvingAddress, address newRecoveryAddress, uint8 v, bytes32 r, bytes32 s ) public { uint ein = identityRegistry.getEIN(approvingAddress); uint nonce = signatureNonce[ein]++; require( identityRegistry.isSigned( approvingAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize this change of Recovery Address.", ein, newRecoveryAddress, nonce ) ), v, r, s ), "Permission denied." ); identityRegistry.triggerRecoveryAddressChangeFor(ein, newRecoveryAddress); } // allow contract to receive PHNX tokens function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public { require(msg.sender == _tokenAddress, "Malformed inputs."); require(_tokenAddress == phoenixTokenAddress, "Sender is not the PHNX token smart contract."); // depositing to an EIN if (_bytes.length <= 32) { require(phoenixToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership."); uint recipient; if (_bytes.length < 32) { recipient = identityRegistry.getEIN(sender); } else { recipient = abi.decode(_bytes, (uint)); require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist."); } deposits[recipient] = deposits[recipient].add(amount); emit PhoenixIdentityDeposit(sender, recipient, amount); } // transferring to a via else { ( bool isTransfer, address resolver, address via, uint to, bytes memory phoenixIdentityCallBytes ) = abi.decode(_bytes, (bool, address, address, uint, bytes)); require(phoenixToken.transferFrom(sender, via, amount), "Unable to transfer token ownership."); PhoenixIdentityViaInterface viaContract = PhoenixIdentityViaInterface(via); if (isTransfer) { viaContract.phoenixIdentityCall(resolver, to, amount, phoenixIdentityCallBytes); emit PhoenixIdentityTransferToVia(resolver, via, to, amount); } else { address payable payableTo = address(to); viaContract.phoenixIdentityCall(resolver, payableTo, amount, phoenixIdentityCallBytes); emit PhoenixIdentityWithdrawToVia(resolver, via, address(to), amount); } } } // transfer phoenixIdentity balance from one phoenixIdentity holder to another function transferPhoenixIdentityBalance(uint einTo, uint amount) public { _transfer(identityRegistry.getEIN(msg.sender), einTo, amount); } // withdraw PhoenixIdentity balance to an external address function withdrawPhoenixIdentityBalance(address to, uint amount) public { _withdraw(identityRegistry.getEIN(msg.sender), to, amount); } // allows resolvers to transfer allowance amounts to other phoenixIdentitys (throws if unsuccessful) function transferPhoenixIdentityBalanceFrom(uint einFrom, uint einTo, uint amount) public { handleAllowance(einFrom, amount); _transfer(einFrom, einTo, amount); emit PhoenixIdentityTransferFrom(msg.sender); } // allows resolvers to withdraw allowance amounts to external addresses (throws if unsuccessful) function withdrawPhoenixIdentityBalanceFrom(uint einFrom, address to, uint amount) public { handleAllowance(einFrom, amount); _withdraw(einFrom, to, amount); emit PhoenixIdentityWithdrawFrom(msg.sender); } // allows resolvers to send withdrawal amounts to arbitrary smart contracts 'to' identities (throws if unsuccessful) function transferPhoenixIdentityBalanceFromVia(uint einFrom, address via, uint einTo, uint amount, bytes memory _bytes) public { handleAllowance(einFrom, amount); _withdraw(einFrom, via, amount); PhoenixIdentityViaInterface viaContract = PhoenixIdentityViaInterface(via); viaContract.phoenixIdentityCall(msg.sender, einFrom, einTo, amount, _bytes); emit PhoenixIdentityTransferFromVia(msg.sender, einTo); } // allows resolvers to send withdrawal amounts 'to' addresses via arbitrary smart contracts function withdrawPhoenixIdentityBalanceFromVia( uint einFrom, address via, address payable to, uint amount, bytes memory _bytes ) public { handleAllowance(einFrom, amount); _withdraw(einFrom, via, amount); PhoenixIdentityViaInterface viaContract = PhoenixIdentityViaInterface(via); viaContract.phoenixIdentityCall(msg.sender, einFrom, to, amount, _bytes); emit PhoenixIdentityWithdrawFromVia(msg.sender, to); } function _transfer(uint einFrom, uint einTo, uint amount) private identityExists(einTo, true) returns (bool) { require(deposits[einFrom] >= amount, "Cannot withdraw more than the current deposit balance."); deposits[einFrom] = deposits[einFrom].sub(amount); deposits[einTo] = deposits[einTo].add(amount); emit PhoenixIdentityTransfer(einFrom, einTo, amount); } function _withdraw(uint einFrom, address to, uint amount) internal { require(to != address(this), "Cannot transfer to the PhoenixIdentity smart contract itself."); require(deposits[einFrom] >= amount, "Cannot withdraw more than the current deposit balance."); deposits[einFrom] = deposits[einFrom].sub(amount); require(phoenixToken.transfer(to, amount), "Transfer was unsuccessful"); emit PhoenixIdentityWithdraw(einFrom, to, amount); } function handleAllowance(uint einFrom, uint amount) internal { // check that resolver-related details are correct require(identityRegistry.isResolverFor(einFrom, msg.sender), "Resolver has not been set by from tokenholder."); if (resolverAllowances[einFrom][msg.sender] < amount) { emit PhoenixIdentityInsufficientAllowance(einFrom, msg.sender, resolverAllowances[einFrom][msg.sender], amount); revert("Insufficient Allowance"); } resolverAllowances[einFrom][msg.sender] = resolverAllowances[einFrom][msg.sender].sub(amount); } // allowAndCall from msg.sender function allowAndCall(address destination, uint amount, bytes memory data) public returns (bytes memory returnData) { return allowAndCall(identityRegistry.getEIN(msg.sender), amount, destination, data); } // allowAndCall from approvingAddress with meta-transaction function allowAndCallDelegated( address destination, uint amount, bytes memory data, address approvingAddress, uint8 v, bytes32 r, bytes32 s ) public returns (bytes memory returnData) { uint ein = identityRegistry.getEIN(approvingAddress); uint nonce = signatureNonce[ein]++; validateAllowAndCallDelegatedSignature(approvingAddress, ein, destination, amount, data, nonce, v, r, s); return allowAndCall(ein, amount, destination, data); } function validateAllowAndCallDelegatedSignature( address approvingAddress, uint ein, address destination, uint amount, bytes memory data, uint nonce, uint8 v, bytes32 r, bytes32 s ) private view { require( identityRegistry.isSigned( approvingAddress, keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), "I authorize this allow and call.", ein, destination, amount, data, nonce ) ), v, r, s ), "Permission denied." ); } // internal logic for allowAndCall function allowAndCall(uint ein, uint amount, address destination, bytes memory data) private returns (bytes memory returnData) { // check that resolver-related details are correct require(identityRegistry.isResolverFor(ein, destination), "Destination has not been set by from tokenholder."); if (amount != 0) { resolverAllowances[ein][destination] = resolverAllowances[ein][destination].add(amount); } // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory _returnData) = destination.call(data); require(success, "Call was not successful."); return _returnData; } // events event PhoenixIdentityProvidersUpgraded(uint indexed ein, address[] newProviders, address[] oldProviders, address approvingAddress); event PhoenixIdentityResolverAdded(uint indexed ein, address indexed resolver, uint withdrawAllowance); event PhoenixIdentityResolverAllowanceChanged(uint indexed ein, address indexed resolver, uint withdrawAllowance); event PhoenixIdentityResolverRemoved(uint indexed ein, address indexed resolver); event PhoenixIdentityDeposit(address indexed from, uint indexed einTo, uint amount); event PhoenixIdentityTransfer(uint indexed einFrom, uint indexed einTo, uint amount); event PhoenixIdentityWithdraw(uint indexed einFrom, address indexed to, uint amount); event PhoenixIdentityTransferFrom(address indexed resolverFrom); event PhoenixIdentityWithdrawFrom(address indexed resolverFrom); event PhoenixIdentityTransferFromVia(address indexed resolverFrom, uint indexed einTo); event PhoenixIdentityWithdrawFromVia(address indexed resolverFrom, address indexed to); event PhoenixIdentityTransferToVia(address indexed resolverFrom, address indexed via, uint indexed einTo, uint amount); event PhoenixIdentityWithdrawToVia(address indexed resolverFrom, address indexed via, address indexed to, uint amount); event PhoenixIdentityInsufficientAllowance( uint indexed ein, address indexed resolver, uint currentAllowance, uint requestedWithdraw ); }
permission removing a resolver for identity of msg.sender
function removeResolver(address resolver, bool isPhoenixIdentity, bytes memory extraData) public { removeResolver(identityRegistry.getEIN(msg.sender), resolver, isPhoenixIdentity, extraData); }
13,045,011
[ 1, 9827, 9427, 279, 5039, 364, 4215, 434, 1234, 18, 15330, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 4301, 12, 2867, 5039, 16, 1426, 353, 3731, 83, 275, 697, 4334, 16, 1731, 3778, 2870, 751, 13, 1071, 288, 203, 3639, 1206, 4301, 12, 10781, 4243, 18, 588, 41, 706, 12, 3576, 18, 15330, 3631, 5039, 16, 353, 3731, 83, 275, 697, 4334, 16, 2870, 751, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x986cE329cF2B038910A79c873526C73D7C17e424/sources/contracts/RemarkableWomen.sol
max per presale address
uint256 public presaleAllowance = 5;
12,524,982
[ 1, 1896, 1534, 4075, 5349, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 4075, 5349, 7009, 1359, 273, 1381, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Verified using https://dapp.tools // hevm: flattened sources of src/saviours/NativeUnderlyingUniswapV2SafeSaviour.sol pragma solidity =0.6.7 >=0.6.0 <0.8.0 >=0.6.7 <0.7.0; ////// src/interfaces/CoinJoinLike.sol /* pragma solidity 0.6.7; */ abstract contract CoinJoinLike { function systemCoin() virtual public view returns (address); function safeEngine() virtual public view returns (address); function join(address, uint256) virtual external; } ////// src/interfaces/CollateralJoinLike.sol /* pragma solidity ^0.6.7; */ abstract contract CollateralJoinLike { function safeEngine() virtual public view returns (address); function collateralType() virtual public view returns (bytes32); function collateral() virtual public view returns (address); function decimals() virtual public view returns (uint256); function contractEnabled() virtual public view returns (uint256); function join(address, uint256) virtual external; } ////// src/interfaces/ERC20Like.sol /* pragma solidity ^0.6.7; */ abstract contract ERC20Like { function approve(address guy, uint wad) virtual public returns (bool); function transfer(address dst, uint wad) virtual public returns (bool); function balanceOf(address) virtual external view returns (uint256); function transferFrom(address src, address dst, uint wad) virtual public returns (bool); } ////// src/interfaces/GebSafeManagerLike.sol /* pragma solidity ^0.6.7; */ abstract contract GebSafeManagerLike { function safes(uint256) virtual public view returns (address); function ownsSAFE(uint256) virtual public view returns (address); function safeCan(address,uint256,address) virtual public view returns (uint256); } ////// src/interfaces/LiquidationEngineLike.sol /* pragma solidity ^0.6.7; */ abstract contract LiquidationEngineLike_3 { function safeSaviours(address) virtual public view returns (uint256); } ////// src/interfaces/OracleRelayerLike.sol /* pragma solidity ^0.6.7; */ abstract contract OracleRelayerLike_2 { function collateralTypes(bytes32) virtual public view returns (address, uint256, uint256); function liquidationCRatio(bytes32) virtual public view returns (uint256); function redemptionPrice() virtual public returns (uint256); } ////// src/interfaces/PriceFeedLike.sol /* pragma solidity ^0.6.7; */ abstract contract PriceFeedLike { function priceSource() virtual public view returns (address); function read() virtual public view returns (uint256); function getResultWithValidity() virtual external view returns (uint256,bool); } ////// src/interfaces/SAFEEngineLike.sol /* pragma solidity ^0.6.7; */ abstract contract SAFEEngineLike_8 { function approveSAFEModification(address) virtual external; function safeRights(address,address) virtual public view returns (uint256); function collateralTypes(bytes32) virtual public view returns ( uint256 debtAmount, // [wad] uint256 accumulatedRate, // [ray] uint256 safetyPrice, // [ray] uint256 debtCeiling, // [rad] uint256 debtFloor, // [rad] uint256 liquidationPrice // [ray] ); function safes(bytes32,address) virtual public view returns ( uint256 lockedCollateral, // [wad] uint256 generatedDebt // [wad] ); function modifySAFECollateralization( bytes32 collateralType, address safe, address collateralSource, address debtDestination, int256 deltaCollateral, // [wad] int256 deltaDebt // [wad] ) virtual external; } ////// src/interfaces/SAFESaviourRegistryLike.sol /* pragma solidity ^0.6.7; */ abstract contract SAFESaviourRegistryLike { function markSave(bytes32 collateralType, address safeHandler) virtual external; } ////// src/interfaces/TaxCollectorLike.sol /* pragma solidity 0.6.7; */ abstract contract TaxCollectorLike { function taxSingle(bytes32) public virtual returns (uint256); } ////// src/utils/ReentrancyGuard.sol // 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; } } ////// src/interfaces/SafeSaviourLike.sol // Copyright (C) 2020 Reflexer Labs, INC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity ^0.6.7; */ /* import "./CollateralJoinLike.sol"; */ /* import "./CoinJoinLike.sol"; */ /* import "./OracleRelayerLike.sol"; */ /* import "./SAFEEngineLike.sol"; */ /* import "./LiquidationEngineLike.sol"; */ /* import "./PriceFeedLike.sol"; */ /* import "./ERC20Like.sol"; */ /* import "./GebSafeManagerLike.sol"; */ /* import "./TaxCollectorLike.sol"; */ /* import "./SAFESaviourRegistryLike.sol"; */ /* import "../utils/ReentrancyGuard.sol"; */ abstract contract SafeSaviourLike is ReentrancyGuard { // Checks whether a saviour contract has been approved by governance in the LiquidationEngine modifier liquidationEngineApproved(address saviour) { require(liquidationEngine.safeSaviours(saviour) == 1, "SafeSaviour/not-approved-in-liquidation-engine"); _; } // Checks whether someone controls a safe handler inside the GebSafeManager modifier controlsSAFE(address owner, uint256 safeID) { require(owner != address(0), "SafeSaviour/null-owner"); require(either(owner == safeManager.ownsSAFE(safeID), safeManager.safeCan(safeManager.ownsSAFE(safeID), safeID, owner) == 1), "SafeSaviour/not-owning-safe"); _; } // --- Variables --- LiquidationEngineLike_3 public liquidationEngine; TaxCollectorLike public taxCollector; OracleRelayerLike_2 public oracleRelayer; GebSafeManagerLike public safeManager; SAFEEngineLike_8 public safeEngine; SAFESaviourRegistryLike public saviourRegistry; // The amount of tokens the keeper gets in exchange for the gas spent to save a SAFE uint256 public keeperPayout; // [wad] // The minimum fiat value that the keeper must get in exchange for saving a SAFE uint256 public minKeeperPayoutValue; // [wad] /* The proportion between the keeperPayout (if it's in collateral) and the amount of collateral or debt that's in a SAFE to be saved. Alternatively, it can be the proportion between the fiat value of keeperPayout and the fiat value of the profit that a keeper could make if a SAFE is liquidated right now. It ensures there's no incentive to intentionally put a SAFE underwater and then save it just to make a profit that's greater than the one from participating in collateral auctions */ uint256 public payoutToSAFESize; // --- Constants --- uint256 public constant ONE = 1; uint256 public constant HUNDRED = 100; uint256 public constant THOUSAND = 1000; uint256 public constant WAD_COMPLEMENT = 10**9; uint256 public constant WAD = 10**18; uint256 public constant RAY = 10**27; uint256 public constant MAX_UINT = uint(-1); // --- Boolean Logic --- function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y) } } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } // --- Events --- event SaveSAFE(address indexed keeper, bytes32 indexed collateralType, address indexed safeHandler, uint256 collateralAddedOrDebtRepaid); // --- Functions to Implement --- function saveSAFE(address,bytes32,address) virtual external returns (bool,uint256,uint256); function getKeeperPayoutValue() virtual public returns (uint256); function keeperPayoutExceedsMinValue() virtual public returns (bool); function canSave(bytes32,address) virtual external returns (bool); function tokenAmountUsedToSave(bytes32,address) virtual public returns (uint256); } ////// src/interfaces/SaviourCRatioSetterLike.sol /* pragma solidity 0.6.7; */ /* import "./OracleRelayerLike.sol"; */ /* import "./GebSafeManagerLike.sol"; */ /* import "../utils/ReentrancyGuard.sol"; */ abstract contract SaviourCRatioSetterLike is ReentrancyGuard { // --- Auth --- mapping (address => uint256) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "SaviourCRatioSetter/account-not-authorized"); _; } // Checks whether someone controls a safe handler inside the GebSafeManager modifier controlsSAFE(address owner, uint256 safeID) { require(owner != address(0), "SaviourCRatioSetter/null-owner"); require(either(owner == safeManager.ownsSAFE(safeID), safeManager.safeCan(safeManager.ownsSAFE(safeID), safeID, owner) == 1), "SaviourCRatioSetter/not-owning-safe"); _; } // --- Variables --- OracleRelayerLike_2 public oracleRelayer; GebSafeManagerLike public safeManager; // Default desired cratio for each individual collateral type mapping(bytes32 => uint256) public defaultDesiredCollateralizationRatios; // Minimum bound for the desired cratio for each collateral type mapping(bytes32 => uint256) public minDesiredCollateralizationRatios; // Desired CRatios for each SAFE after they're saved mapping(bytes32 => mapping(address => uint256)) public desiredCollateralizationRatios; // --- Constants --- uint256 public constant MAX_CRATIO = 1000; uint256 public constant CRATIO_SCALE_DOWN = 10**25; // --- Boolean Logic --- function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y) } } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 indexed parameter, address data); event SetDefaultCRatio(bytes32 indexed collateralType, uint256 cRatio); event SetMinDesiredCollateralizationRatio( bytes32 indexed collateralType, uint256 cRatio ); event SetDesiredCollateralizationRatio( address indexed caller, bytes32 indexed collateralType, uint256 safeID, address indexed safeHandler, uint256 cRatio ); // --- Functions --- function setDefaultCRatio(bytes32, uint256) virtual external; function setMinDesiredCollateralizationRatio(bytes32 collateralType, uint256 cRatio) virtual external; function setDesiredCollateralizationRatio(bytes32 collateralType, uint256 safeID, uint256 cRatio) virtual external; } ////// src/interfaces/UniswapLiquidityManagerLike.sol /* pragma solidity 0.6.7; */ abstract contract UniswapLiquidityManagerLike { function getToken0FromLiquidity(uint256) virtual public view returns (uint256); function getToken1FromLiquidity(uint256) virtual public view returns (uint256); function getLiquidityFromToken0(uint256) virtual public view returns (uint256); function getLiquidityFromToken1(uint256) virtual public view returns (uint256); function removeLiquidity( uint256 liquidity, uint128 amount0Min, uint128 amount1Min, address to ) public virtual returns (uint256, uint256); } ////// src/math/SafeMath.sol // 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. */ contract SafeMath_2 { /** * @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; } } ////// src/saviours/NativeUnderlyingUniswapV2SafeSaviour.sol // Copyright (C) 2021 Reflexer Labs, INC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity 0.6.7; */ /* import "../interfaces/UniswapLiquidityManagerLike.sol"; */ /* import "../interfaces/SaviourCRatioSetterLike.sol"; */ /* import "../interfaces/SafeSaviourLike.sol"; */ /* import "../math/SafeMath.sol"; */ contract NativeUnderlyingUniswapV2SafeSaviour is SafeMath_2, SafeSaviourLike { // --- Auth --- mapping (address => uint256) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "NativeUnderlyingUniswapV2SafeSaviour/account-not-authorized"); _; } mapping (address => uint256) public allowedUsers; /** * @notice Allow a user to deposit assets * @param usr User to whitelist */ function allowUser(address usr) external isAuthorized { allowedUsers[usr] = 1; emit AllowUser(usr); } /** * @notice Disallow a user from depositing assets * @param usr User to disallow */ function disallowUser(address usr) external isAuthorized { allowedUsers[usr] = 0; emit DisallowUser(usr); } /** * @notice Checks whether an address is an allowed user **/ modifier isAllowed { require( either(restrictUsage == 0, both(restrictUsage == 1, allowedUsers[msg.sender] == 1)), "NativeUnderlyingUniswapV2SafeSaviour/account-not-allowed" ); _; } // --- Structs --- struct Reserves { uint256 systemCoins; uint256 collateralCoins; } // --- Variables --- // Flag that tells whether usage of the contract is restricted to allowed users uint256 public restrictUsage; // Whether the system coin is token0 in the Uniswap pool or not bool public isSystemCoinToken0; // Amount of LP tokens currently protecting each position mapping(address => uint256) public lpTokenCover; // Amount of system coin/collateral tokens that Safe owners can get back mapping(address => Reserves) public underlyingReserves; // Liquidity manager contract for Uniswap v2/v3 UniswapLiquidityManagerLike public liquidityManager; // The ERC20 system coin ERC20Like public systemCoin; // The system coin join contract CoinJoinLike public coinJoin; // The collateral join contract for adding collateral in the system CollateralJoinLike public collateralJoin; // The LP token ERC20Like public lpToken; // The collateral token ERC20Like public collateralToken; // Oracle providing the system coin price feed PriceFeedLike public systemCoinOrcl; // Contract that defines desired CRatios for each Safe after it is saved SaviourCRatioSetterLike public cRatioSetter; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event AllowUser(address usr); event DisallowUser(address usr); event ModifyParameters(bytes32 indexed parameter, uint256 val); event ModifyParameters(bytes32 indexed parameter, address data); event Deposit( address indexed caller, address indexed safeHandler, uint256 lpTokenAmount ); event Withdraw( address indexed caller, address indexed safeHandler, address dst, uint256 lpTokenAmount ); event GetReserves( address indexed caller, address indexed safeHandler, uint256 systemCoinAmount, uint256 collateralAmount, address dst ); constructor( bool isSystemCoinToken0_, address coinJoin_, address collateralJoin_, address cRatioSetter_, address systemCoinOrcl_, address liquidationEngine_, address taxCollector_, address oracleRelayer_, address safeManager_, address saviourRegistry_, address liquidityManager_, address lpToken_, uint256 minKeeperPayoutValue_ ) public { require(coinJoin_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-coin-join"); require(collateralJoin_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-collateral-join"); require(cRatioSetter_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-cratio-setter"); require(systemCoinOrcl_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-system-coin-oracle"); require(oracleRelayer_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-oracle-relayer"); require(liquidationEngine_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-liquidation-engine"); require(taxCollector_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-tax-collector"); require(safeManager_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-safe-manager"); require(saviourRegistry_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-saviour-registry"); require(liquidityManager_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-liq-manager"); require(lpToken_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-lp-token"); require(minKeeperPayoutValue_ > 0, "NativeUnderlyingUniswapV2SafeSaviour/invalid-min-payout-value"); authorizedAccounts[msg.sender] = 1; isSystemCoinToken0 = isSystemCoinToken0_; minKeeperPayoutValue = minKeeperPayoutValue_; coinJoin = CoinJoinLike(coinJoin_); collateralJoin = CollateralJoinLike(collateralJoin_); cRatioSetter = SaviourCRatioSetterLike(cRatioSetter_); liquidationEngine = LiquidationEngineLike_3(liquidationEngine_); taxCollector = TaxCollectorLike(taxCollector_); oracleRelayer = OracleRelayerLike_2(oracleRelayer_); systemCoinOrcl = PriceFeedLike(systemCoinOrcl_); systemCoin = ERC20Like(coinJoin.systemCoin()); safeEngine = SAFEEngineLike_8(coinJoin.safeEngine()); safeManager = GebSafeManagerLike(safeManager_); saviourRegistry = SAFESaviourRegistryLike(saviourRegistry_); liquidityManager = UniswapLiquidityManagerLike(liquidityManager_); lpToken = ERC20Like(lpToken_); collateralToken = ERC20Like(collateralJoin.collateral()); systemCoinOrcl.getResultWithValidity(); oracleRelayer.redemptionPrice(); require(collateralJoin.contractEnabled() == 1, "NativeUnderlyingUniswapV2SafeSaviour/join-disabled"); require(address(collateralToken) != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-col-token"); require(address(safeEngine) != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-safe-engine"); require(address(systemCoin) != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-sys-coin"); emit AddAuthorization(msg.sender); emit ModifyParameters("minKeeperPayoutValue", minKeeperPayoutValue); emit ModifyParameters("oracleRelayer", oracleRelayer_); emit ModifyParameters("taxCollector", taxCollector_); emit ModifyParameters("systemCoinOrcl", systemCoinOrcl_); emit ModifyParameters("liquidationEngine", liquidationEngine_); emit ModifyParameters("liquidityManager", liquidityManager_); } // --- Administration --- /** * @notice Modify an uint256 param * @param parameter The name of the parameter * @param val New value for the parameter */ function modifyParameters(bytes32 parameter, uint256 val) external isAuthorized { if (parameter == "minKeeperPayoutValue") { require(val > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-min-payout"); minKeeperPayoutValue = val; } else if (parameter == "restrictUsage") { require(val <= 1, "NativeUnderlyingUniswapV2SafeSaviour/invalid-restriction"); restrictUsage = val; } else revert("NativeUnderlyingUniswapV2SafeSaviour/modify-unrecognized-param"); emit ModifyParameters(parameter, val); } /** * @notice Modify an address param * @param parameter The name of the parameter * @param data New address for the parameter */ function modifyParameters(bytes32 parameter, address data) external isAuthorized { require(data != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-data"); if (parameter == "systemCoinOrcl") { systemCoinOrcl = PriceFeedLike(data); systemCoinOrcl.getResultWithValidity(); } else if (parameter == "oracleRelayer") { oracleRelayer = OracleRelayerLike_2(data); oracleRelayer.redemptionPrice(); } else if (parameter == "liquidityManager") { liquidityManager = UniswapLiquidityManagerLike(data); } else if (parameter == "liquidationEngine") { liquidationEngine = LiquidationEngineLike_3(data); } else if (parameter == "taxCollector") { taxCollector = TaxCollectorLike(data); } else revert("NativeUnderlyingUniswapV2SafeSaviour/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } // --- Transferring Reserves --- /* * @notify Get back system coins or collateral tokens that were withdrawn from Uniswap and not used to save a specific SAFE * @param safeID The ID of the safe that was previously saved and has leftover funds that can be withdrawn * @param dst The address that will receive */ function getReserves(uint256 safeID, address dst) external controlsSAFE(msg.sender, safeID) nonReentrant { address safeHandler = safeManager.safes(safeID); (uint256 systemCoins, uint256 collateralCoins) = (underlyingReserves[safeHandler].systemCoins, underlyingReserves[safeHandler].collateralCoins); require(either(systemCoins > 0, collateralCoins > 0), "NativeUnderlyingUniswapV2SafeSaviour/no-reserves"); delete(underlyingReserves[safeManager.safes(safeID)]); if (systemCoins > 0) { systemCoin.transfer(dst, systemCoins); } if (collateralCoins > 0) { collateralToken.transfer(dst, collateralCoins); } emit GetReserves(msg.sender, safeHandler, systemCoins, collateralCoins, dst); } // --- Adding/Withdrawing Cover --- /* * @notice Deposit lpToken in the contract in order to provide cover for a specific SAFE managed by the SAFE Manager * @param safeID The ID of the SAFE to protect. This ID should be registered inside GebSafeManager * @param lpTokenAmount The amount of collateralToken to deposit */ function deposit(uint256 safeID, uint256 lpTokenAmount) external isAllowed() liquidationEngineApproved(address(this)) nonReentrant { require(lpTokenAmount > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-lp-amount"); // Check that the SAFE exists inside GebSafeManager address safeHandler = safeManager.safes(safeID); require(safeHandler != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-handler"); // Check that the SAFE has debt (, uint256 safeDebt) = SAFEEngineLike_8(collateralJoin.safeEngine()).safes(collateralJoin.collateralType(), safeHandler); require(safeDebt > 0, "NativeUnderlyingUniswapV2SafeSaviour/safe-does-not-have-debt"); // Update the lpToken balance used to cover the SAFE and transfer tokens to this contract lpTokenCover[safeHandler] = add(lpTokenCover[safeHandler], lpTokenAmount); require(lpToken.transferFrom(msg.sender, address(this), lpTokenAmount), "NativeUnderlyingUniswapV2SafeSaviour/could-not-transfer-lp"); emit Deposit(msg.sender, safeHandler, lpTokenAmount); } /* * @notice Withdraw lpToken from the contract and provide less cover for a SAFE * @dev Only an address that controls the SAFE inside the SAFE Manager can call this * @param safeID The ID of the SAFE to remove cover from. This ID should be registered inside the SAFE Manager * @param lpTokenAmount The amount of lpToken to withdraw * @param dst The address that will receive the LP tokens */ function withdraw(uint256 safeID, uint256 lpTokenAmount, address dst) external controlsSAFE(msg.sender, safeID) nonReentrant { require(lpTokenAmount > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-lp-amount"); // Fetch the handler from the SAFE manager address safeHandler = safeManager.safes(safeID); require(lpTokenCover[safeHandler] >= lpTokenAmount, "NativeUnderlyingUniswapV2SafeSaviour/not-enough-to-withdraw"); // Withdraw cover and transfer collateralToken to the caller lpTokenCover[safeHandler] = sub(lpTokenCover[safeHandler], lpTokenAmount); lpToken.transfer(dst, lpTokenAmount); emit Withdraw(msg.sender, safeHandler, dst, lpTokenAmount); } // --- Saving Logic --- /* * @notice Saves a SAFE by withdrawing liquidity and repaying debt and/or adding more collateral * @dev Only the LiquidationEngine can call this * @param keeper The keeper that called LiquidationEngine.liquidateSAFE and that should be rewarded for spending gas to save a SAFE * @param collateralType The collateral type backing the SAFE that's being liquidated * @param safeHandler The handler of the SAFE that's being liquidated * @return Whether the SAFE has been saved, the amount of LP tokens that were used to withdraw liquidity as well as the amount of * system coins sent to the keeper as their payment (this implementation always returns 0) */ function saveSAFE(address keeper, bytes32 collateralType, address safeHandler) override external returns (bool, uint256, uint256) { require(address(liquidationEngine) == msg.sender, "NativeUnderlyingUniswapV2SafeSaviour/caller-not-liquidation-engine"); require(keeper != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-keeper-address"); if (both(both(collateralType == "", safeHandler == address(0)), keeper == address(liquidationEngine))) { return (true, uint(-1), uint(-1)); } // Check that this is handling the correct collateral require(collateralType == collateralJoin.collateralType(), "NativeUnderlyingUniswapV2SafeSaviour/invalid-collateral-type"); // Check that the SAFE has a non null amount of LP tokens covering it require(lpTokenCover[safeHandler] > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-cover"); // Tax the collateral taxCollector.taxSingle(collateralType); // Get the amount of tokens used to top up the SAFE (uint256 safeDebtRepaid, uint256 safeCollateralAdded) = getTokensForSaving(safeHandler, oracleRelayer.redemptionPrice()); // There must be tokens used to save the SAVE require(either(safeDebtRepaid > 0, safeCollateralAdded > 0), "NativeUnderlyingUniswapV2SafeSaviour/cannot-save-safe"); // Get the amounts of tokens sent to the keeper as payment (uint256 keeperSysCoins, uint256 keeperCollateralCoins) = getKeeperPayoutTokens(safeHandler, oracleRelayer.redemptionPrice(), safeDebtRepaid, safeCollateralAdded); // There must be tokens that go to the keeper require(either(keeperSysCoins > 0, keeperCollateralCoins > 0), "NativeUnderlyingUniswapV2SafeSaviour/cannot-pay-keeper"); // Store cover amount in local var uint256 totalCover = lpTokenCover[safeHandler]; delete(lpTokenCover[safeHandler]); // Mark the SAFE in the registry as just having been saved saviourRegistry.markSave(collateralType, safeHandler); // Withdraw all liquidity uint256 sysCoinBalance = systemCoin.balanceOf(address(this)); uint256 collateralCoinBalance = collateralToken.balanceOf(address(this)); lpToken.approve(address(liquidityManager), totalCover); liquidityManager.removeLiquidity(totalCover, 0, 0, address(this)); // Checks after removing liquidity require( either(systemCoin.balanceOf(address(this)) > sysCoinBalance, collateralToken.balanceOf(address(this)) > collateralCoinBalance), "NativeUnderlyingUniswapV2SafeSaviour/faulty-remove-liquidity" ); // Compute remaining balances of tokens that will go into reserves sysCoinBalance = sub(sub(systemCoin.balanceOf(address(this)), sysCoinBalance), add(safeDebtRepaid, keeperSysCoins)); collateralCoinBalance = sub( sub(collateralToken.balanceOf(address(this)), collateralCoinBalance), add(safeCollateralAdded, keeperCollateralCoins) ); // Update reserves if (sysCoinBalance > 0) { underlyingReserves[safeHandler].systemCoins = add( underlyingReserves[safeHandler].systemCoins, sysCoinBalance ); } if (collateralCoinBalance > 0) { underlyingReserves[safeHandler].collateralCoins = add( underlyingReserves[safeHandler].collateralCoins, collateralCoinBalance ); } // Save the SAFE if (safeDebtRepaid > 0) { // Approve the coin join contract to take system coins and repay debt systemCoin.approve(address(coinJoin), safeDebtRepaid); // Calculate the non adjusted system coin amount uint256 nonAdjustedSystemCoinsToRepay = div(mul(safeDebtRepaid, RAY), getAccumulatedRate(collateralType)); // Join system coins in the system and repay the SAFE's debt coinJoin.join(address(this), safeDebtRepaid); safeEngine.modifySAFECollateralization( collateralType, safeHandler, address(0), address(this), int256(0), -int256(nonAdjustedSystemCoinsToRepay) ); } if (safeCollateralAdded > 0) { // Approve collateralToken to the collateral join contract collateralToken.approve(address(collateralJoin), safeCollateralAdded); // Join collateralToken in the system and add it in the saved SAFE collateralJoin.join(address(this), safeCollateralAdded); safeEngine.modifySAFECollateralization( collateralType, safeHandler, address(this), address(0), int256(safeCollateralAdded), int256(0) ); } // Pay keeper if (keeperSysCoins > 0) { systemCoin.transfer(keeper, keeperSysCoins); } if (keeperCollateralCoins > 0) { collateralToken.transfer(keeper, keeperCollateralCoins); } // Emit an event emit SaveSAFE(keeper, collateralType, safeHandler, totalCover); return (true, totalCover, 0); } // --- Getters --- /* * @notify Must be implemented according to the interface although it always returns 0 */ function getKeeperPayoutValue() override public returns (uint256) { return 0; } /* * @notify Must be implemented according to the interface although it always returns false */ function keeperPayoutExceedsMinValue() override public returns (bool) { return false; } /* * @notice Determine whether a SAFE can be saved with the current amount of lpTokenCover deposited as cover for it * @param safeHandler The handler of the SAFE which the function takes into account * @return Whether the SAFE can be saved or not */ function canSave(bytes32, address safeHandler) override external returns (bool) { // Fetch the redemption price first uint256 redemptionPrice = oracleRelayer.redemptionPrice(); // Fetch the amount of tokens used to save the SAFE (uint256 safeDebtRepaid, uint256 safeCollateralAdded) = getTokensForSaving(safeHandler, redemptionPrice); // Fetch the amount of tokens sent to the keeper (uint256 keeperSysCoins, uint256 keeperCollateralCoins) = getKeeperPayoutTokens(safeHandler, redemptionPrice, safeDebtRepaid, safeCollateralAdded); // If there are some tokens used to save the SAFE and some tokens used to repay the keeper, return true if (both( either(safeDebtRepaid > 0, safeCollateralAdded > 0), either(keeperSysCoins > 0, keeperCollateralCoins > 0) )) { return true; } return false; } /* * @notice Return the total amount of LP tokens covering a specific SAFE * @param collateralType The SAFE collateral type (ignored in this implementation) * @param safeHandler The handler of the SAFE which the function takes into account * @return The total LP token cover for a specific SAFE */ function tokenAmountUsedToSave(bytes32, address safeHandler) override public returns (uint256) { return lpTokenCover[safeHandler]; } /* * @notify Fetch the collateral's price */ function getCollateralPrice() public view returns (uint256) { (address ethFSM,,) = oracleRelayer.collateralTypes(collateralJoin.collateralType()); if (ethFSM == address(0)) return 0; (uint256 priceFeedValue, bool hasValidValue) = PriceFeedLike(ethFSM).getResultWithValidity(); if (!hasValidValue) return 0; return priceFeedValue; } /* * @notify Fetch the system coin's market price */ function getSystemCoinMarketPrice() public view returns (uint256) { (uint256 priceFeedValue, bool hasValidValue) = systemCoinOrcl.getResultWithValidity(); if (!hasValidValue) return 0; return priceFeedValue; } /* * @notify Get the target collateralization ratio that a SAFE should have after it's saved * @param safeHandler The handler/address of the SAFE whose target collateralization ratio is retrieved */ function getTargetCRatio(address safeHandler) public view returns (uint256) { bytes32 collateralType = collateralJoin.collateralType(); uint256 defaultCRatio = cRatioSetter.defaultDesiredCollateralizationRatios(collateralType); uint256 targetCRatio = (cRatioSetter.desiredCollateralizationRatios(collateralType, safeHandler) == 0) ? defaultCRatio : cRatioSetter.desiredCollateralizationRatios(collateralType, safeHandler); return targetCRatio; } /* * @notify Return the amount of system coins and collateral tokens retrieved from the LP position covering a specific SAFE * @param safeHandler The handler/address of the targeted SAFE */ function getLPUnderlying(address safeHandler) public view returns (uint256, uint256) { uint256 coverAmount = lpTokenCover[safeHandler]; if (coverAmount == 0) return (0, 0); (uint256 sysCoinsFromLP, uint256 collateralFromLP) = (isSystemCoinToken0) ? (liquidityManager.getToken0FromLiquidity(coverAmount), liquidityManager.getToken1FromLiquidity(coverAmount)) : (liquidityManager.getToken1FromLiquidity(coverAmount), liquidityManager.getToken0FromLiquidity(coverAmount)); return (sysCoinsFromLP, collateralFromLP); } /* * @notice Return the amount of system coins and/or collateral tokens used to save a SAFE * @param safeHandler The handler/address of the targeted SAFE * @param redemptionPrice The system coin redemption price used in calculations */ function getTokensForSaving(address safeHandler, uint256 redemptionPrice) public view returns (uint256, uint256) { if (either(lpTokenCover[safeHandler] == 0, redemptionPrice == 0)) { return (0, 0); } // Get the default CRatio for the SAFE (uint256 depositedCollateralToken, uint256 safeDebt) = SAFEEngineLike_8(collateralJoin.safeEngine()).safes(collateralJoin.collateralType(), safeHandler); uint256 targetCRatio = getTargetCRatio(safeHandler); if (either(safeDebt == 0, targetCRatio == 0)) { return (0, 0); } // Get the collateral market price uint256 collateralPrice = getCollateralPrice(); if (collateralPrice == 0) { return (0, 0); } // Calculate how much debt would need to be repaid uint256 debtToRepay = mul( mul(HUNDRED, mul(depositedCollateralToken, collateralPrice) / WAD) / targetCRatio, RAY ) / redemptionPrice; if (either(debtToRepay >= safeDebt, debtBelowFloor(collateralJoin.collateralType(), debtToRepay))) { return (0, 0); } safeDebt = mul(safeDebt, getAccumulatedRate(collateralJoin.collateralType())) / RAY; debtToRepay = sub(safeDebt, debtToRepay); // Calculate underlying amounts received from LP withdrawal (uint256 sysCoinsFromLP, uint256 collateralFromLP) = getLPUnderlying(safeHandler); // Determine total debt to repay; return if the SAFE can be saved solely by repaying debt, continue calculations otherwise if (sysCoinsFromLP >= debtToRepay) { return (debtToRepay, 0); } else { // Calculate the amount of collateral that would need to be added to the SAFE uint256 scaledDownDebtValue = mul(add(mul(redemptionPrice, sub(safeDebt, sysCoinsFromLP)) / RAY, ONE), targetCRatio) / HUNDRED; uint256 collateralTokenNeeded = div(mul(scaledDownDebtValue, WAD), collateralPrice); collateralTokenNeeded = (depositedCollateralToken < collateralTokenNeeded) ? sub(collateralTokenNeeded, depositedCollateralToken) : MAX_UINT; // See if there's enough collateral to add to the SAFE in order to save it if (collateralTokenNeeded <= collateralFromLP) { return (sysCoinsFromLP, collateralTokenNeeded); } else { return (0, 0); } } } /* * @notice Return the amount of system coins and/or collateral tokens used to pay a keeper * @param safeHandler The handler/address of the targeted SAFE * @param redemptionPrice The system coin redemption price used in calculations * @param safeDebtRepaid The amount of system coins that are already used to save the targeted SAFE * @param safeCollateralAdded The amount of collateral tokens that are already used to save the targeted SAFE */ function getKeeperPayoutTokens(address safeHandler, uint256 redemptionPrice, uint256 safeDebtRepaid, uint256 safeCollateralAdded) public view returns (uint256, uint256) { // Get the system coin and collateral market prices uint256 collateralPrice = getCollateralPrice(); uint256 sysCoinMarketPrice = getSystemCoinMarketPrice(); if (either(collateralPrice == 0, sysCoinMarketPrice == 0)) { return (0, 0); } // Calculate underlying amounts received from LP withdrawal (uint256 sysCoinsFromLP, uint256 collateralFromLP) = getLPUnderlying(safeHandler); // Check if the keeper can get system coins and if yes, compute how many uint256 keeperSysCoins; if (sysCoinsFromLP > safeDebtRepaid) { uint256 remainingSystemCoins = sub(sysCoinsFromLP, safeDebtRepaid); uint256 payoutInSystemCoins = div(mul(minKeeperPayoutValue, WAD), sysCoinMarketPrice); if (payoutInSystemCoins <= remainingSystemCoins) { return (payoutInSystemCoins, 0); } else { keeperSysCoins = remainingSystemCoins; } } // Calculate how much collateral the keeper will get if (collateralFromLP <= safeCollateralAdded) return (0, 0); uint256 remainingCollateral = sub(collateralFromLP, safeCollateralAdded); uint256 remainingKeeperPayoutValue = sub(minKeeperPayoutValue, mul(keeperSysCoins, sysCoinMarketPrice) / WAD); uint256 collateralTokenNeeded = div(mul(remainingKeeperPayoutValue, WAD), collateralPrice); // If there are enough collateral tokens retreived from LP in order to pay the keeper, return the token amounts if (collateralTokenNeeded <= remainingCollateral) { return (keeperSysCoins, collateralTokenNeeded); } else { // Otherwise, return zeroes return (0, 0); } } /* * @notify Returns whether a target debt amount is below the debt floor of a specific collateral type * @param collateralType The collateral type whose floor we compare against * @param targetDebtAmount The target debt amount for a SAFE that has collateralType collateral in it */ function debtBelowFloor(bytes32 collateralType, uint256 targetDebtAmount) public view returns (bool) { (, , , , uint256 debtFloor, ) = safeEngine.collateralTypes(collateralType); return (mul(targetDebtAmount, RAY) < debtFloor); } /* * @notify Get the accumulated interest rate for a specific collateral type * @param The collateral type for which to retrieve the rate */ function getAccumulatedRate(bytes32 collateralType) public view returns (uint256 accumulatedRate) { (, accumulatedRate, , , , ) = safeEngine.collateralTypes(collateralType); } }
--- Transferring Reserves --- @notify Get back system coins or collateral tokens that were withdrawn from Uniswap and not used to save a specific SAFE @param safeID The ID of the safe that was previously saved and has leftover funds that can be withdrawn @param dst The address that will receive/
function getReserves(uint256 safeID, address dst) external controlsSAFE(msg.sender, safeID) nonReentrant { address safeHandler = safeManager.safes(safeID); (uint256 systemCoins, uint256 collateralCoins) = (underlyingReserves[safeHandler].systemCoins, underlyingReserves[safeHandler].collateralCoins); require(either(systemCoins > 0, collateralCoins > 0), "NativeUnderlyingUniswapV2SafeSaviour/no-reserves"); delete(underlyingReserves[safeManager.safes(safeID)]); if (systemCoins > 0) { systemCoin.transfer(dst, systemCoins); } if (collateralCoins > 0) { collateralToken.transfer(dst, collateralCoins); } emit GetReserves(msg.sender, safeHandler, systemCoins, collateralCoins, dst); }
8,052
[ 1, 6062, 2604, 74, 20245, 1124, 264, 3324, 9948, 632, 12336, 968, 1473, 2619, 276, 9896, 578, 4508, 2045, 287, 2430, 716, 4591, 598, 9446, 82, 628, 1351, 291, 91, 438, 471, 486, 1399, 358, 1923, 279, 2923, 348, 6799, 41, 225, 4183, 734, 1021, 1599, 434, 326, 4183, 716, 1703, 7243, 5198, 471, 711, 29709, 284, 19156, 716, 848, 506, 598, 9446, 82, 225, 3046, 1021, 1758, 716, 903, 6798, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 31792, 264, 3324, 12, 11890, 5034, 4183, 734, 16, 1758, 3046, 13, 3903, 11022, 22219, 12, 3576, 18, 15330, 16, 4183, 734, 13, 1661, 426, 8230, 970, 288, 203, 3639, 1758, 4183, 1503, 273, 4183, 1318, 18, 87, 1727, 281, 12, 4626, 734, 1769, 203, 3639, 261, 11890, 5034, 2619, 39, 9896, 16, 2254, 5034, 4508, 2045, 287, 39, 9896, 13, 273, 203, 1850, 261, 9341, 6291, 607, 264, 3324, 63, 4626, 1503, 8009, 4299, 39, 9896, 16, 6808, 607, 264, 3324, 63, 4626, 1503, 8009, 12910, 2045, 287, 39, 9896, 1769, 203, 203, 3639, 2583, 12, 73, 2927, 12, 4299, 39, 9896, 405, 374, 16, 4508, 2045, 287, 39, 9896, 405, 374, 3631, 315, 9220, 14655, 6291, 984, 291, 91, 438, 58, 22, 9890, 55, 69, 522, 477, 19, 2135, 17, 455, 264, 3324, 8863, 203, 3639, 1430, 12, 9341, 6291, 607, 264, 3324, 63, 4626, 1318, 18, 87, 1727, 281, 12, 4626, 734, 13, 19226, 203, 203, 3639, 309, 261, 4299, 39, 9896, 405, 374, 13, 288, 203, 1850, 2619, 27055, 18, 13866, 12, 11057, 16, 2619, 39, 9896, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 12910, 2045, 287, 39, 9896, 405, 374, 13, 288, 203, 1850, 4508, 2045, 287, 1345, 18, 13866, 12, 11057, 16, 4508, 2045, 287, 39, 9896, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 968, 607, 264, 3324, 12, 3576, 18, 15330, 16, 4183, 1503, 16, 2619, 39, 9896, 16, 4508, 2045, 287, 39, 9896, 16, 3046, 1769, 203, 565, 289, 203, 203, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // interfaces, contracts, and utilities that are all related to NFTs // This is a one-third of ERC 721, the rest are IERC721Metadata, and IERC721Enumerable import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // Helps check if a third party addresses is not making an incorrect call import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; // A modifier to prevent reentrancy in functions import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; // a simple way to incremented or decremented; Also helps prevent overflow import "@openzeppelin/contracts/utils/Counters.sol"; // standardized way to retrieve royalty payment information for NFTs import "@openzeppelin/contracts/interfaces/IERC2981.sol"; // To print logging messages and contract variables calling console.log() import "hardhat/console.sol"; contract Marketplace is ReentrancyGuard { using Counters for Counters.Counter; Counters.Counter private _itemIds; Counters.Counter private _itemsSold; // this gets the properties available for a contract type e.g.(IERC721) bytes4 public constant ERC721INTERFACE = type(IERC721).interfaceId; // this is to check if it conforms to the EIP-2981 NFTs royalty standard // can also check by comparing with 0x2a55205a or bytes4(keccak256("royaltyInfo(uint256,uint256)")) bytes4 public constant ERC2981INTERFACE = type(IERC2981).interfaceId; // template for our market items struct MarketItem { uint256 itemId; address nftContractAddress; uint256 tokenId; address payable creator; address payable seller; address payable owner; uint256 price; uint256 royalty; bool isAuction; bool sold; } // template for our auction struct AuctionInfo { uint256 highestBid; address highestBidder; uint256 timeEnding; } // map data to template defined mapping(uint256 => MarketItem) private idToMarketItem; mapping(uint256 => AuctionInfo) private auctionData; // writing this rather rhan a function to check every time // All sellers address[] public allSellers; // All creators address[] public allCreators; // All creators earnings uint public totalEarnings; // define events event MarketItemCreatedEvent( uint256 indexed itemId, address indexed nftContractAddress, uint256 indexed tokenId, address seller, address owner, uint256 price ); event MarketAuctionItemCreatedEvent( uint256 indexed itemId, address indexed nftContractAddress, uint256 indexed tokenId, address seller, address owner, uint256 price ); event MarketItemSoldEvent( uint256 itemId, address indexed nftContractAddress, address indexed seller, address indexed newOwner ); event MarketItemUnlistedEvent(uint256 itemId); event MarketItemBidEvent( uint256 indexed itemId, address indexed bidder, uint256 amount ); // Functions // create item, check for royalty request, transfer item function createMarketItem( address nftContractAddress, uint256 tokenId, uint256 price ) public payable nonReentrant { require( ERC165Checker.supportsInterface( nftContractAddress, ERC721INTERFACE ), "ERC721 CONTRACT IS REQUIRED" ); require( IERC721(nftContractAddress).ownerOf(tokenId) == msg.sender, "MSG.SENDER MUST BE THE OWNER OF ITEM" ); require(price > 0, "PRICE CANNOT BE ZERO"); // Increase item count _itemIds.increment(); uint256 itemId = _itemIds.current(); if ( ERC165Checker.supportsInterface( nftContractAddress, ERC2981INTERFACE ) ) { (address creator, uint256 royaltyAmount) = IERC2981( nftContractAddress ).royaltyInfo(tokenId, price); idToMarketItem[itemId] = MarketItem( itemId, nftContractAddress, tokenId, payable(creator), payable(msg.sender), payable(address(0)), price, royaltyAmount, false, false ); } else { address creator = msg.sender; uint256 royaltyAmount = 0; idToMarketItem[itemId] = MarketItem( itemId, nftContractAddress, tokenId, payable(creator), payable(msg.sender), payable(address(0)), price, royaltyAmount, false, false ); } IERC721(nftContractAddress).transferFrom( msg.sender, address(this), tokenId ); allCreators.push(msg.sender); emit MarketItemCreatedEvent( itemId, nftContractAddress, tokenId, msg.sender, address(0), price ); } // creates an auction item instead of a fixed price item // create auction item, check for royalty request, transfer item, enter auction data function createMarketAuction( address nftContractAddress, uint256 tokenId, uint256 floorPrice, uint256 auctionTime ) external payable nonReentrant { require(floorPrice > 0, "PRICE CANNOT BE ZERO"); require(auctionTime > 0, "O HOURS IS AN INVALID AUCTION TIME"); require( ERC165Checker.supportsInterface( nftContractAddress, ERC721INTERFACE ), "CONTRACT SHOULD TO BE ERC721 ENUM" ); require( IERC721(nftContractAddress).ownerOf(tokenId) == msg.sender, "MSG.SENDER MUST BE THE OWNER OF ITEM" ); _itemIds.increment(); uint256 itemId = _itemIds.current(); if ( ERC165Checker.supportsInterface( nftContractAddress, ERC2981INTERFACE ) ) { (address creator, uint256 royaltyAmount) = IERC2981( nftContractAddress ).royaltyInfo(tokenId, floorPrice); idToMarketItem[itemId] = MarketItem( itemId, nftContractAddress, tokenId, payable(creator), payable(msg.sender), payable(address(0)), floorPrice, royaltyAmount, true, false ); } else { address creator = msg.sender; uint256 royaltyAmount = 0; idToMarketItem[itemId] = MarketItem( itemId, nftContractAddress, tokenId, payable(creator), payable(msg.sender), payable(address(0)), floorPrice, royaltyAmount, true, false ); } IERC721(nftContractAddress).transferFrom( msg.sender, address(this), tokenId ); auctionData[itemId] = AuctionInfo( 0, address(0), (block.timestamp + auctionTime * 1 hours) ); allCreators.push(msg.sender); emit MarketAuctionItemCreatedEvent( itemId, nftContractAddress, tokenId, msg.sender, address(0), floorPrice ); } // get item and info, function createAuctionBid(uint256 itemId) external payable nonReentrant { MarketItem storage currentItem = idToMarketItem[itemId]; AuctionInfo storage currentInfo = auctionData[itemId]; require(!currentItem.sold, "ITEM HAS ALREADY BEEN SOLD"); require(currentItem.isAuction, "NOT FOR AUCTION!"); require( currentInfo.timeEnding > block.timestamp, "AUCTION HAS ENDED!" ); require( msg.value > currentItem.price, "MSG.VALUE IS BELOW THE MINIMUM PRICE" ); require( msg.value > currentInfo.highestBid, "MSG.VALUE HAS TO BE MORE THAN THE HIGHEST BID" ); payable(currentInfo.highestBidder).transfer(currentInfo.highestBid); currentInfo.highestBidder = msg.sender; currentInfo.highestBid = msg.value; emit MarketItemBidEvent(itemId, msg.sender, msg.value); } // Sell the NFT item in an auction function createAuctionSale(address nftContractAddress, uint256 itemId) external payable nonReentrant { MarketItem storage currentItem = idToMarketItem[itemId]; AuctionInfo storage currentInfo = auctionData[itemId]; require(!currentItem.sold, "ITEM HAS ALREADY BEEN SOLD"); require(currentItem.isAuction, "ITEM IS NOT FOR AUCTION"); require( currentInfo.timeEnding < block.timestamp, "AUCTION HAS NOT YET ENDED" ); require( msg.sender == currentInfo.highestBidder, "MSG.SENDER IS NOT THE HIGHEST BIDDER" ); if (currentItem.creator == currentItem.seller) { payable(currentItem.nftContractAddress).transfer(msg.value); } else { payable(currentItem.seller).transfer(currentItem.royalty); currentItem.seller.transfer(msg.value - currentItem.royalty); } IERC721(nftContractAddress).transferFrom( address(this), msg.sender, currentItem.tokenId ); currentItem.owner = payable(msg.sender); currentItem.sold = true; _itemsSold.increment(); allSellers.push(currentItem.seller); totalEarnings += msg.value; emit MarketItemSoldEvent( itemId, nftContractAddress, currentItem.seller, currentItem.owner ); } // Let user buy NFT and exchange fund between the interested parties function createMarketSale(address nftContractAddress, uint256 itemId) public payable nonReentrant { MarketItem storage currentItem = idToMarketItem[itemId]; require(!currentItem.isAuction, "THIS ITEM IS ON AUCTION"); require( msg.value == currentItem.price, "SUBMIT ASKING PRICE TO COMPLETE PURCHASE" ); require(!currentItem.sold, "ITEM ALREADY SOLD"); if (currentItem.creator == currentItem.seller) { payable(currentItem.nftContractAddress).transfer(msg.value); } else { payable(currentItem.seller).transfer(currentItem.royalty); currentItem.seller.transfer(msg.value - currentItem.royalty); } IERC721(nftContractAddress).transferFrom( address(this), msg.sender, currentItem.tokenId ); allSellers.push(currentItem.seller); totalEarnings += msg.value; currentItem.owner = payable(msg.sender); currentItem.sold = true; _itemsSold.increment(); emit MarketItemSoldEvent( itemId, nftContractAddress, currentItem.seller, currentItem.owner ); } // Get user bids function fetchUserBids() external view returns (MarketItem[] memory, AuctionInfo[] memory) { uint256 totalItemCount = _itemIds.current(); uint256 itemCount = 0; uint256 currentIndex = 0; for (uint256 i = 0; i < totalItemCount; i++) { if (auctionData[i + 1].highestBidder == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); AuctionInfo[] memory info = new AuctionInfo[](itemCount); for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].owner == msg.sender) { uint256 currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; AuctionInfo storage currentInfo = auctionData[currentId]; items[currentIndex] = currentItem; info[currentIndex] = currentInfo; currentIndex += 1; } } return (items, info); } // Returns all unsold market items function fetchMarketItems() public view returns (MarketItem[] memory, AuctionInfo[] memory) { uint256 itemCount = _itemIds.current(); uint256 unsoldItemCount = _itemIds.current() - _itemsSold.current(); uint256 currentIndex = 0; MarketItem[] memory items = new MarketItem[](unsoldItemCount); AuctionInfo[] memory info = new AuctionInfo[](unsoldItemCount); for (uint256 i = 0; i < itemCount; i++) { if (!idToMarketItem[i + 1].sold) { uint256 currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; AuctionInfo storage currentInfo = auctionData[currentId]; items[currentIndex] = currentItem; info[currentIndex] = currentInfo; currentIndex += 1; } } return (items, info); } // Returns only items that msg.sender has purchased function fetchMyNFTs() public view returns (MarketItem[] memory) { uint256 totalItemCount = _itemIds.current(); uint256 itemCount = 0; uint256 currentIndex = 0; for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].owner == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].owner == msg.sender) { uint256 currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } /* Returns only items msg.sender has created */ function fetchItemsCreated() public view returns (MarketItem[] memory) { uint256 totalItemCount = _itemIds.current(); uint256 itemCount = 0; uint256 currentIndex = 0; for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { itemCount += 1; } } MarketItem[] memory items = new MarketItem[](itemCount); for (uint256 i = 0; i < totalItemCount; i++) { if (idToMarketItem[i + 1].seller == msg.sender) { uint256 currentId = i + 1; MarketItem storage currentItem = idToMarketItem[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } function unlistItem(uint256 itemId) external nonReentrant { require(!idToMarketItem[itemId].sold, "SOLD ITEMS CAN'T BE UNLISTED"); require( idToMarketItem[itemId].seller == msg.sender, "MSG.SENDER IS NOT THE LISTER" ); if (idToMarketItem[itemId].isAuction) { AuctionInfo storage info = auctionData[itemId]; if (info.highestBid > 0) { payable(info.highestBidder).transfer(info.highestBid); } delete auctionData[itemId]; } IERC721(idToMarketItem[itemId].nftContractAddress).transferFrom( address(this), msg.sender, idToMarketItem[itemId].tokenId ); delete idToMarketItem[itemId]; idToMarketItem[itemId].sold = true; _itemsSold.increment(); emit MarketItemUnlistedEvent(itemId); } }
writing this rather rhan a function to check every time All sellers
address[] public allSellers;
12,913,017
[ 1, 14345, 333, 9178, 6259, 304, 279, 445, 358, 866, 3614, 813, 4826, 357, 3135, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 8526, 1071, 777, 55, 1165, 414, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xaCCe8E31616e608d001AFdd63aA764F589666879 //Contract name: FundariaTokenBuy //Balance: 0 Ether //Verification Date: 5/31/2017 //Transacion Count: 4 // CODE STARTS HERE pragma solidity ^0.4.11; contract FundariaToken { uint public totalSupply; uint public supplyLimit; address public fundariaPoolAddress; function supplyTo(address, uint); function tokenForWei(uint) returns(uint); function weiForToken(uint) returns(uint); } contract FundariaBonusFund { function setOwnedBonus() payable {} } contract FundariaTokenBuy { address public fundariaBonusFundAddress; // address of Fundaria 'bonus fund' contract address public fundariaTokenAddress; // address of Fundaria token contract uint public bonusPeriod = 64 weeks; // bonus period from moment of this contract creating uint constant bonusIntervalsCount = 9; // decreasing of bonus share with time uint public startTimestampOfBonusPeriod; // when the bonus period starts uint public finalTimestampOfBonusPeriod; // when the bonus period ends // for keeping of data to define bonus share at the moment of calling buy() struct bonusData { uint timestamp; uint shareKoef; } // array to keep bonus related data bonusData[9] bonusShedule; address creator; // creator address of this contract // condition to be creator address to run some functions modifier onlyCreator { if(msg.sender == creator) _; } function FundariaTokenBuy(address _fundariaTokenAddress) { fundariaTokenAddress = _fundariaTokenAddress; startTimestampOfBonusPeriod = now; finalTimestampOfBonusPeriod = now+bonusPeriod; for(uint8 i=0; i<bonusIntervalsCount; i++) { // define timestamps of bonus period intervals bonusShedule[i].timestamp = finalTimestampOfBonusPeriod-(bonusPeriod*(bonusIntervalsCount-i-1)/bonusIntervalsCount); // koef for decreasing bonus share bonusShedule[i].shareKoef = bonusIntervalsCount-i; } creator = msg.sender; } function setFundariaBonusFundAddress(address _fundariaBonusFundAddress) onlyCreator { fundariaBonusFundAddress = _fundariaBonusFundAddress; } // finish bonus if needed (if bonus system not efficient) function finishBonusPeriod() onlyCreator { finalTimestampOfBonusPeriod = now; } // if token bought successfuly event TokenBought(address buyer, uint tokenToBuyer, uint weiForFundariaPool, uint weiForBonusFund, uint remnantWei); function buy() payable { require(msg.value>0); // use Fundaria token contract functions FundariaToken ft = FundariaToken(fundariaTokenAddress); // should be enough tokens before supply reached limit require(ft.supplyLimit()-1>ft.totalSupply()); // tokens to buyer according to course var tokenToBuyer = ft.tokenForWei(msg.value); // should be enogh ether for at least 1 token require(tokenToBuyer>=1); // every second token goes to creator address var tokenToCreator = tokenToBuyer; uint weiForFundariaPool; // wei distributed to Fundaria pool uint weiForBonusFund; // wei distributed to Fundaria bonus fund uint returnedWei; // remnant // if trying to buy more tokens then supply limit if(ft.totalSupply()+tokenToBuyer+tokenToCreator > ft.supplyLimit()) { // how many tokens are supposed to buy? var supposedTokenToBuyer = tokenToBuyer; // get all remaining tokens and devide them between reciepents tokenToBuyer = (ft.supplyLimit()-ft.totalSupply())/2; // every second token goes to creator address tokenToCreator = tokenToBuyer; // tokens over limit var excessToken = supposedTokenToBuyer-tokenToBuyer; // wei to return to buyer returnedWei = ft.weiForToken(excessToken); } // remaining wei for tokens var remnantValue = msg.value-returnedWei; // if bonus period is over if(now>finalTimestampOfBonusPeriod) { weiForFundariaPool = remnantValue; } else { uint prevTimestamp; for(uint8 i=0; i<bonusIntervalsCount; i++) { // find interval to get needed bonus share if(bonusShedule[i].timestamp>=now && now>prevTimestamp) { // wei to be distributed into the Fundaria bonus fund weiForBonusFund = remnantValue*bonusShedule[i].shareKoef/(bonusIntervalsCount+1); } prevTimestamp = bonusShedule[i].timestamp; } // wei for Fundaria pool weiForFundariaPool = remnantValue-weiForBonusFund; } // use Fundaria token contract function to distribute tokens to creator address ft.supplyTo(creator, tokenToCreator); // transfer wei for bought tokens to Fundaria pool (ft.fundariaPoolAddress()).transfer(weiForFundariaPool); // if we have wei for buyer to be saved in bonus fund if(weiForBonusFund>0) { FundariaBonusFund fbf = FundariaBonusFund(fundariaBonusFundAddress); // distribute bonus wei to bonus fund fbf.setOwnedBonus.value(weiForBonusFund)(); } // if have remnant, return it to buyer if(returnedWei>0) msg.sender.transfer(returnedWei); // use Fundaria token contract function to distribute tokens to buyer ft.supplyTo(msg.sender, tokenToBuyer); // inform about 'token bought' event TokenBought(msg.sender, tokenToBuyer, weiForFundariaPool, weiForBonusFund, returnedWei); } // Prevents accidental sending of ether function () { throw; } }
use Fundaria token contract function to distribute tokens to buyer
ft.supplyTo(msg.sender, tokenToBuyer);
5,388,585
[ 1, 1202, 478, 1074, 15240, 1147, 6835, 445, 358, 25722, 2430, 358, 27037, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 11038, 18, 2859, 1283, 774, 12, 3576, 18, 15330, 16, 1147, 774, 38, 16213, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x380e98fdB1241C178686E124265e14B481eB2c9E/sources/contracts/Assignement.sol
TODO: transfer mintership to newminter NOTE: only incumbent minter can transfer mintership NOTE: should emit `MintershipTransfer` event
function transferMintership(address newMinter) public returns (bool) { require(msg.sender==minter); minter=newMinter; emit MintershipTransfer(msg.sender, newMinter); }
16,285,001
[ 1, 6241, 30, 7412, 1131, 387, 3261, 358, 394, 1154, 387, 5219, 30, 1338, 7290, 3592, 319, 1131, 387, 848, 7412, 1131, 387, 3261, 5219, 30, 1410, 3626, 1375, 49, 2761, 3261, 5912, 68, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 49, 2761, 3261, 12, 2867, 394, 49, 2761, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 631, 1154, 387, 1769, 203, 3639, 1131, 387, 33, 2704, 49, 2761, 31, 203, 3639, 3626, 490, 2761, 3261, 5912, 12, 3576, 18, 15330, 16, 394, 49, 2761, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-16 */ pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view 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); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- 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 TheShibaFather is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "TheShibaFather"; symbol = "TSHIBA"; decimals = 18; _totalSupply = 1000000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } 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 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; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "TheShibaFather"; symbol = "TSHIBA"; decimals = 18; _totalSupply = 1000000000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
10,782,059
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 1986, 1555, 495, 69, 42, 4806, 14432, 203, 3639, 3273, 273, 315, 56, 2664, 45, 12536, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 12648, 2787, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]