Unnamed: 0 int64 0 7.36k | comments stringlengths 3 35.2k | code_string stringlengths 1 527k | code stringlengths 1 527k | __index_level_0__ int64 0 88.6k |
|---|---|---|---|---|
177 | // Bonus muliplier for early ymi makers. | uint256 public constant BONUS_MULTIPLIER = 1;
| uint256 public constant BONUS_MULTIPLIER = 1;
| 16,774 |
866 | // This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding({_hashTypedDataV4})./ solhint-disable var-name-mixedcase // solhint-enable var-name-mixedcase // Initializes the domain separator and parameter caches. The meaning of `name` and `version` is specified in - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.- `version`: the current major version of the signing domain. NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smartcontract upgrade]. / | constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
| constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
_TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
}
| 7,054 |
26 | // Retrieves all tasks of a proposer. Most recent ones first./_proposer The proposer to fetch tasks of./_fromTaskId What taskId to start from./_max The maximum amount of tasks to return. 0 for no max. | function getProposingTasks(
address _proposer,
uint256 _fromTaskId,
uint256 _max
) external view returns (OffChainTask[] memory);
| function getProposingTasks(
address _proposer,
uint256 _fromTaskId,
uint256 _max
) external view returns (OffChainTask[] memory);
| 23,707 |
244 | // Method to view the current price for buying / | function blockBuyPrice(uint256 blockID_)
public
view
returns(uint256)
| function blockBuyPrice(uint256 blockID_)
public
view
returns(uint256)
| 36,975 |
267 | // Just update reserves if _only_deposit is true - no HADES minting. This is for sending the OHM from the aHades contract. Otherwise, treat it like a normal deposit. | if (_only_deposit) {
totalReserves = totalReserves.add(value);
emit ReservesUpdated(totalReserves);
} else {
| if (_only_deposit) {
totalReserves = totalReserves.add(value);
emit ReservesUpdated(totalReserves);
} else {
| 41,066 |
75 | // called when the contract receives an ERC721 token, will revert if project is not whitelistedin exchange for nfts, depositers will receive $LIT / | function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata _data
| function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata _data
| 28,257 |
30 | // Token Issuance | function isIssuable() external view returns (bool);
function issue(address _tokenHolder, uint256 _value, bytes calldata _data) external;
function issueByPartition(bytes32 _partition, address _tokenHolder, uint256 _value, bytes calldata _data) external;
| function isIssuable() external view returns (bool);
function issue(address _tokenHolder, uint256 _value, bytes calldata _data) external;
function issueByPartition(bytes32 _partition, address _tokenHolder, uint256 _value, bytes calldata _data) external;
| 21,412 |
24 | // Record deposit data for `msg.sender` | sponsorDeposits[msg.sender].push(
Deposit({
amount: amount,
maturationTimestamp: maturationTimestamp,
active: true
})
| sponsorDeposits[msg.sender].push(
Deposit({
amount: amount,
maturationTimestamp: maturationTimestamp,
active: true
})
| 30,774 |
434 | // Trigger the underlying Reward Control contract to accrue ALK supply rewards for the supplier on the specified market market The address of the market to accrue rewards supplier The address of the supplier to accrue rewards isVerified Verified / Public protocol / | function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
| function refreshAlkSupplyIndex(
address market,
address supplier,
bool isVerified
| 74,194 |
59 | // Function to close an election, add up votes, and pay winners. | function closeElection(uint64 electionId) public {
//first make sure the election is open and valid.
checkElection(electionId);
//Next, make sure that the election has been open long enough
require((Elections[electionId].startTime + electionDuration <= uint64(now)), "Hold on - the election still needs more time to resolve");
ICoopData CoopData = ICoopData(coopDataContract);
ITACLockup TACLockup = ITACLockup(TACLockupContract);
Elections[electionId].isLive = false;
//map the total score for each match Id
for (uint i = 0;i < votesPerElection[electionId].length; i++) {
voteTotals[votesPerElection[electionId][i].choice] = voteTotals[votesPerElection[electionId][i].choice] + SafeMath.mul(CoopData.getUserMatchNumber(votesPerElection[electionId][i].voter) + defaultVotes, TACLockup.getTACLocked(votesPerElection[electionId][i].voter ));
}
//Assume the first option is the winner, and then change if another match has more votes
uint64 winner = optionsPerElection[electionId][0].matchId;
uint256 mostVotes = 0;
for (uint j = 0; j < optionsPerElection[electionId].length; j++) {
if (voteTotals[optionsPerElection[electionId][j].matchId] > mostVotes) {
winner = optionsPerElection[electionId][j].matchId;
mostVotes = voteTotals[winner];
}
//Reset voteTotals back to 0 for next election
voteTotals[optionsPerElection[electionId][j].matchId] = 0;
}
allWinners[winner] = true; //mark that the match has won and can't be entered into another election.
Elections[electionId].winningMatch = winner;
//Winner is the id of the winning match
payWinners(winner);
}
| function closeElection(uint64 electionId) public {
//first make sure the election is open and valid.
checkElection(electionId);
//Next, make sure that the election has been open long enough
require((Elections[electionId].startTime + electionDuration <= uint64(now)), "Hold on - the election still needs more time to resolve");
ICoopData CoopData = ICoopData(coopDataContract);
ITACLockup TACLockup = ITACLockup(TACLockupContract);
Elections[electionId].isLive = false;
//map the total score for each match Id
for (uint i = 0;i < votesPerElection[electionId].length; i++) {
voteTotals[votesPerElection[electionId][i].choice] = voteTotals[votesPerElection[electionId][i].choice] + SafeMath.mul(CoopData.getUserMatchNumber(votesPerElection[electionId][i].voter) + defaultVotes, TACLockup.getTACLocked(votesPerElection[electionId][i].voter ));
}
//Assume the first option is the winner, and then change if another match has more votes
uint64 winner = optionsPerElection[electionId][0].matchId;
uint256 mostVotes = 0;
for (uint j = 0; j < optionsPerElection[electionId].length; j++) {
if (voteTotals[optionsPerElection[electionId][j].matchId] > mostVotes) {
winner = optionsPerElection[electionId][j].matchId;
mostVotes = voteTotals[winner];
}
//Reset voteTotals back to 0 for next election
voteTotals[optionsPerElection[electionId][j].matchId] = 0;
}
allWinners[winner] = true; //mark that the match has won and can't be entered into another election.
Elections[electionId].winningMatch = winner;
//Winner is the id of the winning match
payWinners(winner);
}
| 17,780 |
6 | // Fianl Tuesday fin | uint public deadline = 1518566340;
| uint public deadline = 1518566340;
| 26,561 |
148 | // calculate current bond price and remove floor if above return price_ uint / | function _bondPrice() internal returns (uint256 price_) {
price_ = terms.controlVariable.mul(debtRatio()).div(1e5);
if (price_ < terms.minimumPrice) {
price_ = terms.minimumPrice;
} else if (terms.minimumPrice != 0) {
terms.minimumPrice = 0;
}
}
| function _bondPrice() internal returns (uint256 price_) {
price_ = terms.controlVariable.mul(debtRatio()).div(1e5);
if (price_ < terms.minimumPrice) {
price_ = terms.minimumPrice;
} else if (terms.minimumPrice != 0) {
terms.minimumPrice = 0;
}
}
| 33,653 |
75 | // Set to pairData.updatePeriod. maxUpdateWindow is called by other contracts. | uint public maxUpdateWindow;
ExchangePair public pairData;
IAggregatorV3 public oracle;
| uint public maxUpdateWindow;
ExchangePair public pairData;
IAggregatorV3 public oracle;
| 16,830 |
12 | // price = 0.005 + 0.06(wh)/10000; | uint256 price = (5000+6*uint256(w)*uint256(h)) * 0.000001 ether;
require(
msg.value >= price,
"errorEth"
);
uint256 tokenId = _mintToken(msg.sender);
creators[tokenId] = msg.sender;
setTokenData(tokenId, x, y, w, h, c, b);
emit MintEvent(msg.sender);
| uint256 price = (5000+6*uint256(w)*uint256(h)) * 0.000001 ether;
require(
msg.value >= price,
"errorEth"
);
uint256 tokenId = _mintToken(msg.sender);
creators[tokenId] = msg.sender;
setTokenData(tokenId, x, y, w, h, c, b);
emit MintEvent(msg.sender);
| 36,403 |
2 | // mock class using ERC1155 | contract ERC1155Mock is ERC1155 {
constructor() ERC1155("") {}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts
) external {
_mintBatch(to, ids, amounts, "");
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) external {
_mintBatch(to, ids, amounts, data);
}
}
| contract ERC1155Mock is ERC1155 {
constructor() ERC1155("") {}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts
) external {
_mintBatch(to, ids, amounts, "");
}
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) external {
_mintBatch(to, ids, amounts, data);
}
}
| 23,953 |
7 | // Emitted when `owner` pays to purchase a specific image id. / | event Purchase(address indexed owner, string imageId, string name);
| event Purchase(address indexed owner, string imageId, string name);
| 33,392 |
5 | // Position of the entry defined by a key in the `entries` array, plus 1 because index 0 means a key is not in the map. | mapping(bytes32 => uint256) indexes;
| mapping(bytes32 => uint256) indexes;
| 5,156 |
32 | // Check if we need to withdraw yield token | if (_amountYT != 0) {
| if (_amountYT != 0) {
| 82,217 |
22 | // Remove approval for address _to to transfer the NFT with ID _tokenId. | function removeApproval (uint _tokenId) public onlyExtantToken (_tokenId) onlyOwnerOfToken (_tokenId) {
require(approvedAddressToTransferTokenId[_tokenId] != address(0));
_clearTokenApproval(_tokenId);
Approval(msg.sender, address(0), _tokenId);
}
| function removeApproval (uint _tokenId) public onlyExtantToken (_tokenId) onlyOwnerOfToken (_tokenId) {
require(approvedAddressToTransferTokenId[_tokenId] != address(0));
_clearTokenApproval(_tokenId);
Approval(msg.sender, address(0), _tokenId);
}
| 20,477 |
26 | // overwrite value | writeValue(root, value(n));
| writeValue(root, value(n));
| 21,243 |
111 | // Denominator used to when distributing tokens 1000 == 100% | uint128 public constant DENOMINATOR = 1000;
| uint128 public constant DENOMINATOR = 1000;
| 31,353 |
32 | // Sell NXM tokens and receive ETH.//tokenAmountAmount of tokens to sell./minEthOutMinimum amount of ETH to be received. Revert if ethOut falls below this number./ | function sellNXM(
uint tokenAmount,
uint minEthOut
| function sellNXM(
uint tokenAmount,
uint minEthOut
| 12,191 |
11 | // CRITERIA: function exchangeStars/ | function offerExchange(uint256 _offeredTokenID,
uint256 _requestedTokenID,
uint256 _timeOut,
uint256 _exchangePriceOffer,
uint256 _exchangePriceRequest
| function offerExchange(uint256 _offeredTokenID,
uint256 _requestedTokenID,
uint256 _timeOut,
uint256 _exchangePriceOffer,
uint256 _exchangePriceRequest
| 7,643 |
5 | // Returns the smallest of two signed numbers. / | function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
| function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
| 15,378 |
165 | // determine the length of the input by finding the location of the last non-zero byte | for (uint256 i = 32; i > 0; ) {
| for (uint256 i = 32; i > 0; ) {
| 14,646 |
5 | // 50% of tokens reserved for presale | uint256 public constant PRESALE_SUPPLY = 210210210210210 * 10 ** 18;
| uint256 public constant PRESALE_SUPPLY = 210210210210210 * 10 ** 18;
| 6,736 |
38 | // setting up all required token approvals / | constructor() public {
ERC20Interface(daiAddr).approve(cDai, uint(-1));
ERC20Interface(usdcAddr).approve(cUsdc, uint(-1));
ERC20Interface(cDai).approve(cDai, uint(-1));
ERC20Interface(cUsdc).approve(cUsdc, uint(-1));
ERC20Interface(cEth).approve(cEth, uint(-1));
}
| constructor() public {
ERC20Interface(daiAddr).approve(cDai, uint(-1));
ERC20Interface(usdcAddr).approve(cUsdc, uint(-1));
ERC20Interface(cDai).approve(cDai, uint(-1));
ERC20Interface(cUsdc).approve(cUsdc, uint(-1));
ERC20Interface(cEth).approve(cEth, uint(-1));
}
| 48,089 |
390 | // true up earned amount to vBZRX vesting schedule | lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
value = value
.mul(multiplier);
value /= 1e36;
bzrxRewardsEarned = bzrxRewardsEarned
| lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
value = value
.mul(multiplier);
value /= 1e36;
bzrxRewardsEarned = bzrxRewardsEarned
| 43,085 |
31 | // Calculate | uint256 fee = _marketFee(payAmount);
uint256 paySeller = SafeMath.sub(payAmount, fee);
| uint256 fee = _marketFee(payAmount);
uint256 paySeller = SafeMath.sub(payAmount, fee);
| 15,147 |
24 | // Mapping from: user -> total balance accross all entered swaps | mapping(address => uint) user_total_balances;
| mapping(address => uint) user_total_balances;
| 17,990 |
51 | // Internal function that is used to determine the current rate for token / ETH conversionreturn The current token rate / | function getRate() internal view returns (uint256) {
if(now < (startTime + 5 weeks)) {
return 7000;
}
if(now < (startTime + 9 weeks)) {
return 6500;
}
if(now < (startTime + 13 weeks)) {
return 6000;
}
if(now < (startTime + 15 weeks)) {
return 5500;
}
return 5000;
}
| function getRate() internal view returns (uint256) {
if(now < (startTime + 5 weeks)) {
return 7000;
}
if(now < (startTime + 9 weeks)) {
return 6500;
}
if(now < (startTime + 13 weeks)) {
return 6000;
}
if(now < (startTime + 15 weeks)) {
return 5500;
}
return 5000;
}
| 43,313 |
151 | // Override this to add all tokens/tokenized positions this contractmanages on a persistent basis (e.g. not just for swapping back towant ephemerally). NOTE: Do not include `want`, already included in `sweep` below. Example:``` | * function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
| * function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
| 872 |
43 | // If Sale didn't start yet | require(sellingStep == Steps.Sale, "Sorry, sale has not started yet.");
| require(sellingStep == Steps.Sale, "Sorry, sale has not started yet.");
| 10,916 |
69 | // verify typed signature | _verifyTradeOfferSignature(_offer, _signature);
_verifyForwardingGasSignature(_forwardingGas, _gasSignature);
| _verifyTradeOfferSignature(_offer, _signature);
_verifyForwardingGasSignature(_forwardingGas, _gasSignature);
| 15,532 |
54 | // assuming token transfer is approved | IERC721(tokenAddress).transferFrom(msg.sender, address(this), tokenId);
uint256 _initialWorth = lentERC721List[tokenAddress][tokenId].initialWorth;
IERC20(acceptedPayTokenAddress).transfer(_borrower, _initialWorth);
lentERC721List[tokenAddress][tokenId].borrower = address(0);
lentERC721List[tokenAddress][tokenId].borrowedAtTimestamp = 0;
address lenderAddress = lentERC721List[tokenAddress][tokenId].lender;
| IERC721(tokenAddress).transferFrom(msg.sender, address(this), tokenId);
uint256 _initialWorth = lentERC721List[tokenAddress][tokenId].initialWorth;
IERC20(acceptedPayTokenAddress).transfer(_borrower, _initialWorth);
lentERC721List[tokenAddress][tokenId].borrower = address(0);
lentERC721List[tokenAddress][tokenId].borrowedAtTimestamp = 0;
address lenderAddress = lentERC721List[tokenAddress][tokenId].lender;
| 4,589 |
6 | // Updates an element in the list. list A storage pointer to the underlying list. key The element key. previousKey The key of the element that comes before the updated element. nextKey The key of the element that comes after the updated element. / | function update(
LinkedList.List storage list,
address key,
address previousKey,
address nextKey
| function update(
LinkedList.List storage list,
address key,
address previousKey,
address nextKey
| 25,929 |
281 | // CreatureCreature - a contract for my non-fungible creatures. / | contract FadeAwayBunnyNFT is ERC721Tradable {
event Birth(address owner, uint256 fadeAwayBunnyId, uint256 matronId, uint256 sireId, bytes32 genes);
struct FadeAwayBunny {
bytes32 genes;
uint64 birthTime;
uint32 matronId;
uint32 sireId;
uint16 generation;
}
string baseURI;
mapping(uint256 => FadeAwayBunny) public bunnies;
constructor(address _proxyRegistryAddress)
ERC721Tradable("Fade Away Bunny Collection", "FAB", _proxyRegistryAddress)
{}
/// @dev Assigns a new address to act as the base URI. Only available to the current Owner.
/// @param _baseURI The address of the new base URI
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
function _createFadeAwayBunny(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
bytes32 _genes,
address _owner
)
internal
returns (uint256)
{
uint256 nextTokenId = delegatedMintTo(_owner);
bunnies[nextTokenId] = FadeAwayBunny({
genes: _genes,
birthTime: uint64(block.timestamp),
matronId: uint32(_matronId),
sireId: uint32(_sireId),
generation: uint16(_generation)
});
emit Birth(_owner, nextTokenId, _matronId, _sireId, _genes);
return nextTokenId;
}
function createFadeAwayBunny(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
bytes32 _genes,
address _owner
)
public onlyRouter returns (uint)
{
return _createFadeAwayBunny(_matronId, _sireId, _generation, _genes, _owner);
}
function baseTokenURI() override public view returns (string memory) {
return baseURI;
}
function contractURI() public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), "api/contract"));
}
} | contract FadeAwayBunnyNFT is ERC721Tradable {
event Birth(address owner, uint256 fadeAwayBunnyId, uint256 matronId, uint256 sireId, bytes32 genes);
struct FadeAwayBunny {
bytes32 genes;
uint64 birthTime;
uint32 matronId;
uint32 sireId;
uint16 generation;
}
string baseURI;
mapping(uint256 => FadeAwayBunny) public bunnies;
constructor(address _proxyRegistryAddress)
ERC721Tradable("Fade Away Bunny Collection", "FAB", _proxyRegistryAddress)
{}
/// @dev Assigns a new address to act as the base URI. Only available to the current Owner.
/// @param _baseURI The address of the new base URI
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
function _createFadeAwayBunny(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
bytes32 _genes,
address _owner
)
internal
returns (uint256)
{
uint256 nextTokenId = delegatedMintTo(_owner);
bunnies[nextTokenId] = FadeAwayBunny({
genes: _genes,
birthTime: uint64(block.timestamp),
matronId: uint32(_matronId),
sireId: uint32(_sireId),
generation: uint16(_generation)
});
emit Birth(_owner, nextTokenId, _matronId, _sireId, _genes);
return nextTokenId;
}
function createFadeAwayBunny(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
bytes32 _genes,
address _owner
)
public onlyRouter returns (uint)
{
return _createFadeAwayBunny(_matronId, _sireId, _generation, _genes, _owner);
}
function baseTokenURI() override public view returns (string memory) {
return baseURI;
}
function contractURI() public view returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), "api/contract"));
}
} | 8,549 |
133 | // Transfer base_asset tokens from LP to pool | IERC20(base_asset_address).safeTransferFrom(msg.sender, address(this), amount);
| IERC20(base_asset_address).safeTransferFrom(msg.sender, address(this), amount);
| 17,116 |
226 | // It allows the admin to recover wrong tokens sent to the contract _tokenAddress: the address of the token to withdraw (18 decimals) _tokenAmount: the number of token amount to withdraw This function is only callable by admin. / | function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyAdmin {
require(_tokenAddress != address(lpToken), "Cannot be LP token");
require(_tokenAddress != address(offeringToken), "Cannot be offering token");
IBEP20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
| function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyAdmin {
require(_tokenAddress != address(lpToken), "Cannot be LP token");
require(_tokenAddress != address(offeringToken), "Cannot be offering token");
IBEP20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
| 5,229 |
133 | // decode evert string: assume it has a standard Error(string) signature: simply skip the (selector,offset,length) fields | if ( ret.length>4+32+32 ) {
return abi.decode(ret[4:], (string));
}
| if ( ret.length>4+32+32 ) {
return abi.decode(ret[4:], (string));
}
| 73,551 |
112 | // 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);
}
| function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
| 47,924 |
167 | // add eth to our players & rounds ICO phase investment. this will be usedto determine total keys and each players share | plyrRnds_[_pID][_rID].ico = _eth.add(plyrRnds_[_pID][_rID].ico);
round_[_rID].ico = _eth.add(round_[_rID].ico);
| plyrRnds_[_pID][_rID].ico = _eth.add(plyrRnds_[_pID][_rID].ico);
round_[_rID].ico = _eth.add(round_[_rID].ico);
| 76,521 |
12 | // make sure contract is registered | require(contract_info.contract_id != 0, 'Contract not found');
| require(contract_info.contract_id != 0, 'Contract not found');
| 55,093 |
34 | // Checks: the current milestone is strictly greater than the previous milestone. | currentMilestone = segments[index].milestone;
if (currentMilestone <= previousMilestone) {
revert Errors.SablierV2LockupDynamic_SegmentMilestonesNotOrdered(
index, previousMilestone, currentMilestone
);
}
| currentMilestone = segments[index].milestone;
if (currentMilestone <= previousMilestone) {
revert Errors.SablierV2LockupDynamic_SegmentMilestonesNotOrdered(
index, previousMilestone, currentMilestone
);
}
| 31,330 |
7 | // Emitted when a caller places a bid | event BidMade(address caller, uint256 tokenId, uint256 amount);
| event BidMade(address caller, uint256 tokenId, uint256 amount);
| 14,650 |
18 | // Since the cipher part of the batch has already been executed or skipped and the config cannot be changed anymore (since the batching period is over), the following checks remain true. | assert(configContract.batchingActive(configIndex));
(, uint64 end, ) =
configContract.batchBoundaryBlocks(configIndex, batchIndex);
assert(block.number >= end);
bytes32 batchHash =
executeTransactions(
targetAddress,
targetFunctionSelector,
transactionGasLimit,
| assert(configContract.batchingActive(configIndex));
(, uint64 end, ) =
configContract.batchBoundaryBlocks(configIndex, batchIndex);
assert(block.number >= end);
bytes32 batchHash =
executeTransactions(
targetAddress,
targetFunctionSelector,
transactionGasLimit,
| 43,007 |
322 | // Update a transcoder with rewards and update the transcoder pool with an optional list hint if needed.See SortedDoublyLL.sol for details on list hints _transcoder Address of transcoder _rewards Amount of rewards _round Round that transcoder is updated _newPosPrev Address of previous transcoder in pool if the transcoder is in the pool _newPosNext Address of next transcoder in pool if the transcoder is in the pool / | function updateTranscoderWithRewards(
address _transcoder,
uint256 _rewards,
uint256 _round,
address _newPosPrev,
address _newPosNext
)
internal
| function updateTranscoderWithRewards(
address _transcoder,
uint256 _rewards,
uint256 _round,
address _newPosPrev,
address _newPosNext
)
internal
| 6,105 |
103 | // Dividend tracker | if (!isDividendExempt[sender]) {
try distributor.setShare(sender, balanceOf(sender)) {} catch {}
| if (!isDividendExempt[sender]) {
try distributor.setShare(sender, balanceOf(sender)) {} catch {}
| 28,210 |
0 | // Executes a percentage multiplication value The value of which the percentage needs to be calculated percentage The percentage of the value to be calculatedreturn The percentage of value / | function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
"PercentMathMul overflow"
);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
| function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) {
if (value == 0 || percentage == 0) {
return 0;
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
"PercentMathMul overflow"
);
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR;
}
| 8,621 |
1 | // Connection to other ERC20 smart contracts | function transferFrom(address _from, address _to, uint256 _value) external returns (bool success){}
}
| function transferFrom(address _from, address _to, uint256 _value) external returns (bool success){}
}
| 35,495 |
153 | // Mint new tokens. Only callable by owner after the required time period has elapsed. recipientThe address to receive minted tokens.amount The number of tokens to mint. / | function mint(
address recipient,
uint256 amount
)
external
onlyOwner
| function mint(
address recipient,
uint256 amount
)
external
onlyOwner
| 66,006 |
24 | // ERC777 Standards followed by OpenZeppelin Group libraries on Github // Interface of the ERC777Token standard as defined in the EIP. This contract uses thetoken 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 Revoke an account's operator status for 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 Destroys `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);
}
| * 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 Revoke an account's operator status for 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 Destroys `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);
}
| 26,389 |
208 | // BballPandas contract Extends ERC721 Non-Fungible Token Standard basic implementation / | contract BballPandas is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable {
using SafeMath for uint256;
uint256 public constant pandaPrice = 80000000000000000; //0.08 ETH
uint256 public constant maxPandaPurchase = 20;
uint256 public constant MAX_PANDAS = 10000;
bool public saleIsActive = false;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function _baseURI() internal pure override returns (string memory) {
return "ipfs://QmfTEXFZJa19J1hWjytpeq7NUvB1xWd9ZG3H46tfxa6VNq/";
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function toggleSale() public onlyOwner {
saleIsActive = !saleIsActive;
}
function reservePandas() public onlyOwner {
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < 25; i++) {
_safeMint(msg.sender, supply + i);
}
}
function mintPanda(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Panda");
require(numberOfTokens <= maxPandaPurchase, "Can only mint a maximum of 20 tokens in a single transaction");
require(totalSupply().add(numberOfTokens) <= MAX_PANDAS, "Purchase would exceed max supply of Pandas");
require(pandaPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_PANDAS) {
_safeMint(msg.sender, mintIndex);
}
}
}
} | contract BballPandas is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable {
using SafeMath for uint256;
uint256 public constant pandaPrice = 80000000000000000; //0.08 ETH
uint256 public constant maxPandaPurchase = 20;
uint256 public constant MAX_PANDAS = 10000;
bool public saleIsActive = false;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function _baseURI() internal pure override returns (string memory) {
return "ipfs://QmfTEXFZJa19J1hWjytpeq7NUvB1xWd9ZG3H46tfxa6VNq/";
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function toggleSale() public onlyOwner {
saleIsActive = !saleIsActive;
}
function reservePandas() public onlyOwner {
uint256 supply = totalSupply();
uint256 i;
for (i = 0; i < 25; i++) {
_safeMint(msg.sender, supply + i);
}
}
function mintPanda(uint numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Panda");
require(numberOfTokens <= maxPandaPurchase, "Can only mint a maximum of 20 tokens in a single transaction");
require(totalSupply().add(numberOfTokens) <= MAX_PANDAS, "Purchase would exceed max supply of Pandas");
require(pandaPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = totalSupply();
if (totalSupply() < MAX_PANDAS) {
_safeMint(msg.sender, mintIndex);
}
}
}
} | 55,775 |
15 | // Otherwise we have an unsupported message type and we skip the message | if (data[0] == MSG_ROOT) {
require(data.length == 97, "BAD_LENGTH");
uint256 batchNum = data.toUint(1);
| if (data[0] == MSG_ROOT) {
require(data.length == 97, "BAD_LENGTH");
uint256 batchNum = data.toUint(1);
| 25,331 |
28 | // Burn liquidity from the sender and account tokens owed for the liquidity to the position/Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0/Fees must be collected separately via a call to collect/tickLower The lower tick of the position for which to burn liquidity/tickUpper The upper tick of the position for which to burn liquidity/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);
| function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
| 50,801 |
53 | // If the tokenAddress is WETH, always return 0 (there is a separate set of functions for WETH) | if (tokenAddress == WETH) return 0;
else {
| if (tokenAddress == WETH) return 0;
else {
| 28,359 |
224 | // Gets a Fl from Spark and returns back the execution to the action address/_flData All the amounts/tokens and related spark fl data/_params Rest of the data we have in the recipe | function _flSpark(FlashLoanParams memory _flData, bytes memory _params) internal returns (uint) {
ILendingPoolV2(SPARK_LENDING_POOL).flashLoan(
address(this),
_flData.tokens,
_flData.amounts,
_flData.modes,
_flData.onBehalfOf,
_params,
SPARK_REFERRAL_CODE
);
emit ActionEvent(
"FLSpark",
abi.encode(_flData.tokens, _flData.amounts, _flData.modes, _flData.onBehalfOf)
);
return _flData.amounts[0];
}
| function _flSpark(FlashLoanParams memory _flData, bytes memory _params) internal returns (uint) {
ILendingPoolV2(SPARK_LENDING_POOL).flashLoan(
address(this),
_flData.tokens,
_flData.amounts,
_flData.modes,
_flData.onBehalfOf,
_params,
SPARK_REFERRAL_CODE
);
emit ActionEvent(
"FLSpark",
abi.encode(_flData.tokens, _flData.amounts, _flData.modes, _flData.onBehalfOf)
);
return _flData.amounts[0];
}
| 40,364 |
12 | // Returns true if address is a registered price provider/_provider address of price provider to be removed/ return true if address is a registered price provider, otherwise false | function isPriceProvider(IPriceProvider _provider) external view returns (bool);
| function isPriceProvider(IPriceProvider _provider) external view returns (bool);
| 24,623 |
88 | // Pull the creator address before removing the auction. | address Creator = auctions[tokenId].Creator;
| address Creator = auctions[tokenId].Creator;
| 7,263 |
23 | // Allows to update the number of required confirmations by Safe owners./This can only be done via a Safe transaction./Changes the threshold of the Safe to `_threshold`./_threshold New threshold. | function changeThreshold(uint256 _threshold)
public
authorized
| function changeThreshold(uint256 _threshold)
public
authorized
| 29,097 |
26 | // Allows for the bonus credit of an address to be queried. This is a constant function which does not alter the state of the contract and therefore does not require any gas or a signature to be executed._addr The address of which to query the bonus credits. return The total amount of bonus credit the address has (minus non-bonus credit)./ | function getBonusDropsOf(address _addr) public view returns(uint256) {
return bonusDropsOf[_addr];
}
| function getBonusDropsOf(address _addr) public view returns(uint256) {
return bonusDropsOf[_addr];
}
| 21,973 |
10 | // Log the transfer request | emit Transfer(msg.sender, _doctor);
| emit Transfer(msg.sender, _doctor);
| 15,091 |
49 | // contractInfo: Returns total users, totalDeposited, totalWithdraw / | function contractInfo() external view returns(uint256 _total_users, uint256 _total_deposited,
| function contractInfo() external view returns(uint256 _total_users, uint256 _total_deposited,
| 28,459 |
1 | // Called to `msg.sender` after flash loaning to the recipient from IPoolflash./This function's implementation must send the loaned amounts with computed fee amounts/ The caller of this method must be checked to be a Pool deployed by the canonical Factory./feeQty0 The token0 fee to be sent to the pool./feeQty1 The token1 fee to be sent to the pool./data Data passed through by the caller via the IPoolflash call | function flashCallback(
uint256 feeQty0,
uint256 feeQty1,
bytes calldata data
) external;
| function flashCallback(
uint256 feeQty0,
uint256 feeQty1,
bytes calldata data
) external;
| 27,278 |
246 | // A lender optimisation strategy for any erc20 assetUsing iron bank to leverage upv0.3.0 This strategy works by taking plugins designed for standard lending platformsIt automatically chooses the best yield generating platform and adjusts accordinglyThe adjustment is sub optimal so there is an additional option to manually set position / | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
uint256 public constant BLOCKSPERYEAR = 2102400; // 12 seconds per block
//IRON BANK
ComptrollerI private ironBank = ComptrollerI(address(0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB));
CErc20I private ironBankToken;
uint256 public maxIronBankLeverage = 4; //max leverage we will take from iron bank
uint256 public step = 10;
IGenericLender[] public lenders;
bool public externalOracle = false;
address public wantToEthOracle;
constructor(address _vault, address _ironBankToken) public BaseStrategy(_vault) {
ironBankToken = CErc20I(_ironBankToken);
debtThreshold = 1e15;
want.safeApprove(address(ironBankToken), uint256(-1));
//we do this horrible thing because you can't compare strings in solidity
require(keccak256(bytes(apiVersion())) == keccak256(bytes(VaultAPI(_vault).apiVersion())), "WRONG VERSION");
}
/*****************
* Iron Bank
******************/
//simple logic. do we get more apr than iron bank charges?
//if so, is that still true with increased pos?
//if not, should be reduce?
//made harder because we can't assume iron bank debt curve. So need to increment
function internalCreditOfficer() public view returns (bool borrowMore, uint256 amount) {
if(emergencyExit){
return(false, ironBankOutstandingDebtStored());
}
//how much credit we have
(, uint256 liquidity, uint256 shortfall) = ironBank.getAccountLiquidity(address(this));
uint256 underlyingPrice = ironBank.oracle().getUnderlyingPrice(address(ironBankToken));
if(underlyingPrice == 0){
return (false, 0);
}
liquidity = liquidity.mul(1e18).div(underlyingPrice);
shortfall = shortfall.mul(1e18).div(underlyingPrice);
//repay debt if iron bank wants its money back
if(shortfall > 0){
//note we only borrow 1 asset so can assume all our shortfall is from it
return(false, shortfall-1); //remove 1 incase of rounding errors
}
uint256 liquidityAvailable = want.balanceOf(address(ironBankToken));
uint256 remainingCredit = Math.min(liquidity, liquidityAvailable);
//our current supply rate.
//we only calculate once because it is expensive
uint256 currentSR = currentSupplyRate();
//iron bank borrow rate
uint256 ironBankBR = ironBankBorrowRate(0, true);
uint256 outstandingDebt = ironBankOutstandingDebtStored();
//we have internal credit limit. it is function on our own assets invested
//this means we can always repay our debt from our capital
uint256 maxCreditDesired = vault.strategies(address(this)).totalDebt.mul(maxIronBankLeverage);
//minIncrement must be > 0
if(maxCreditDesired <= step){
return (false, 0);
}
//we move in 10% increments
uint256 minIncrement = maxCreditDesired.div(step);
//we start at 1 to save some gas
uint256 increment = 1;
// if we have too much debt we return
//overshoot incase of dust
if(maxCreditDesired.mul(11).div(10) < outstandingDebt){
borrowMore = false;
amount = outstandingDebt - maxCreditDesired;
}
//if sr is > iron bank we borrow more. else return
else if(currentSR > ironBankBR){
remainingCredit = Math.min(maxCreditDesired - outstandingDebt, remainingCredit);
while(minIncrement.mul(increment) <= remainingCredit){
ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), false);
if(currentSR <= ironBankBR){
break;
}
increment++;
}
borrowMore = true;
amount = minIncrement.mul(increment-1);
}else{
while(minIncrement.mul(increment) <= outstandingDebt){
ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), true);
//we do increment before the if statement here
increment++;
if(currentSR > ironBankBR){
break;
}
}
borrowMore = false;
//special case to repay all
if(increment == 1){
amount = outstandingDebt;
}else{
amount = minIncrement.mul(increment - 1);
}
}
//we dont play with dust:
if (amount < debtThreshold) {
amount = 0;
}
}
function ironBankOutstandingDebtStored() public view returns (uint256 available) {
return ironBankToken.borrowBalanceStored(address(this));
}
function ironBankBorrowRate(uint256 amount, bool repay) public view returns (uint256) {
uint256 cashPrior = want.balanceOf(address(ironBankToken));
uint256 borrows = ironBankToken.totalBorrows();
uint256 reserves = ironBankToken.totalReserves();
InterestRateModel model = ironBankToken.interestRateModel();
uint256 cashChange;
uint256 borrowChange;
if(repay){
cashChange = cashPrior.add(amount);
borrowChange = borrows.sub(amount);
}else{
cashChange = cashPrior.sub(amount);
borrowChange = borrows.add(amount);
}
uint256 borrowRate = model.getBorrowRate(cashChange, borrowChange, reserves);
return borrowRate;
}
function setPriceOracle(address _oracle) external onlyAuthorized{
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiserIB";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length-1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr().mul(BLOCKSPERYEAR);
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav += want.balanceOf(address(this));
uint256 ironBankDebt = ironBankOutstandingDebtStored();
if(ironBankDebt > nav) return 0;
return nav.sub(ironBankDebt);
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function currentSupplyRate() public view returns (uint256) {
uint256 bal = lentTotalAssets();
bal += want.balanceOf(address(this));
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR += lenders[i].weightedApr();
}
return weightedAPR.div(bal);
}
function estimatedAPR() public view returns (uint256){
uint256 outstandingDebt = ironBankOutstandingDebtStored();
uint256 ironBankBR = ironBankBorrowRate(0, true);
uint256 id = outstandingDebt.mul(ironBankBR);
uint256 currentSR = currentSupplyRate();
uint256 assets = lentTotalAssets().add(want.balanceOf(address(this)));
uint256 ti = assets.mul(currentSR);
if(ti > id && assets > outstandingDebt){
return ti.sub(id).div(assets.sub(outstandingDebt)).mul(BLOCKSPERYEAR);
}else{
return 0;
}
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR += lenders[i].weightedApr();
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR += lenders[i].weightedApr();
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR += lowestApr.mul(change);
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav += lenders[i].nav();
}
return nav;
}
//we need to free up profit plus _debtOutstanding.
//If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 ironBankDebt = ironBankOutstandingDebtStored();
uint256 total = looseAssets.add(lentAssets);
if(ironBankDebt < total){
total = total.sub(ironBankDebt);
}else{
total = 0;
}
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
//start off by borrowing or returning:
(bool borrowMore, uint256 amount) = internalCreditOfficer();
//do iron bank stuff first
if(!borrowMore){
(uint256 _amountFreed,) = liquidatePosition(amount);
//withdraw and repay
ironBankToken.repayBorrow(_amountFreed);
}else if(amount > 0){
//borrow the amount we want
ironBankToken.borrow(amount);
}
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if(lenders.length == 0){
return;
}
_debtOutstanding; //ignored. we handle it in prepare return
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000.
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[j].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share += _newPositions[i].share;
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
//dont withdraw dust
if (_amount < debtThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn += lenders[lowest].withdraw(_amount - amountWithdrawn);
j++;
//dont want infinite loop
if(j >= 6){
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded,0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded,0);
} else {
return (received,0);
}
}
}
function harvestTrigger(uint256 callCost) public override view returns (bool) {
uint256 wantCallCost = _callCostToWant(callCost);
return super.harvestTrigger(wantCallCost);
}
function ethToWant(uint256 _amount) internal view returns (uint256){
address[] memory path = new address[](2);
path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256){
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if(address(want) == weth){
wantCallCost = callCost;
}else if(wantToEthOracle == address(0)){
wantCallCost = ethToWant(callCost);
}else{
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
uint256 wantCallCost = _callCostToWant(callCost);
//test if we want to change iron bank position
(,uint256 _amount)= internalCreditOfficer();
if(profitFactor.mul(wantCallCost) < _amount){
return true;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//profit increase is 1 days profit with new apr
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).div(365);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
uint256 ibBorrows = ironBankToken.borrowBalanceCurrent(address(this));
(,, uint wantBalance) = prepareReturn(outstanding.add(ibBorrows));
ironBankToken.repayBorrow(Math.min(ibBorrows, wantBalance));
wantBalance = want.balanceOf(address(this));
// require(wantBalance.add(loss) >= outstanding, "LIQUIDITY LOCKED");
//require removed because in 0.3.0 we can still harvest after migrate
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
uint256 public constant BLOCKSPERYEAR = 2102400; // 12 seconds per block
//IRON BANK
ComptrollerI private ironBank = ComptrollerI(address(0xAB1c342C7bf5Ec5F02ADEA1c2270670bCa144CbB));
CErc20I private ironBankToken;
uint256 public maxIronBankLeverage = 4; //max leverage we will take from iron bank
uint256 public step = 10;
IGenericLender[] public lenders;
bool public externalOracle = false;
address public wantToEthOracle;
constructor(address _vault, address _ironBankToken) public BaseStrategy(_vault) {
ironBankToken = CErc20I(_ironBankToken);
debtThreshold = 1e15;
want.safeApprove(address(ironBankToken), uint256(-1));
//we do this horrible thing because you can't compare strings in solidity
require(keccak256(bytes(apiVersion())) == keccak256(bytes(VaultAPI(_vault).apiVersion())), "WRONG VERSION");
}
/*****************
* Iron Bank
******************/
//simple logic. do we get more apr than iron bank charges?
//if so, is that still true with increased pos?
//if not, should be reduce?
//made harder because we can't assume iron bank debt curve. So need to increment
function internalCreditOfficer() public view returns (bool borrowMore, uint256 amount) {
if(emergencyExit){
return(false, ironBankOutstandingDebtStored());
}
//how much credit we have
(, uint256 liquidity, uint256 shortfall) = ironBank.getAccountLiquidity(address(this));
uint256 underlyingPrice = ironBank.oracle().getUnderlyingPrice(address(ironBankToken));
if(underlyingPrice == 0){
return (false, 0);
}
liquidity = liquidity.mul(1e18).div(underlyingPrice);
shortfall = shortfall.mul(1e18).div(underlyingPrice);
//repay debt if iron bank wants its money back
if(shortfall > 0){
//note we only borrow 1 asset so can assume all our shortfall is from it
return(false, shortfall-1); //remove 1 incase of rounding errors
}
uint256 liquidityAvailable = want.balanceOf(address(ironBankToken));
uint256 remainingCredit = Math.min(liquidity, liquidityAvailable);
//our current supply rate.
//we only calculate once because it is expensive
uint256 currentSR = currentSupplyRate();
//iron bank borrow rate
uint256 ironBankBR = ironBankBorrowRate(0, true);
uint256 outstandingDebt = ironBankOutstandingDebtStored();
//we have internal credit limit. it is function on our own assets invested
//this means we can always repay our debt from our capital
uint256 maxCreditDesired = vault.strategies(address(this)).totalDebt.mul(maxIronBankLeverage);
//minIncrement must be > 0
if(maxCreditDesired <= step){
return (false, 0);
}
//we move in 10% increments
uint256 minIncrement = maxCreditDesired.div(step);
//we start at 1 to save some gas
uint256 increment = 1;
// if we have too much debt we return
//overshoot incase of dust
if(maxCreditDesired.mul(11).div(10) < outstandingDebt){
borrowMore = false;
amount = outstandingDebt - maxCreditDesired;
}
//if sr is > iron bank we borrow more. else return
else if(currentSR > ironBankBR){
remainingCredit = Math.min(maxCreditDesired - outstandingDebt, remainingCredit);
while(minIncrement.mul(increment) <= remainingCredit){
ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), false);
if(currentSR <= ironBankBR){
break;
}
increment++;
}
borrowMore = true;
amount = minIncrement.mul(increment-1);
}else{
while(minIncrement.mul(increment) <= outstandingDebt){
ironBankBR = ironBankBorrowRate(minIncrement.mul(increment), true);
//we do increment before the if statement here
increment++;
if(currentSR > ironBankBR){
break;
}
}
borrowMore = false;
//special case to repay all
if(increment == 1){
amount = outstandingDebt;
}else{
amount = minIncrement.mul(increment - 1);
}
}
//we dont play with dust:
if (amount < debtThreshold) {
amount = 0;
}
}
function ironBankOutstandingDebtStored() public view returns (uint256 available) {
return ironBankToken.borrowBalanceStored(address(this));
}
function ironBankBorrowRate(uint256 amount, bool repay) public view returns (uint256) {
uint256 cashPrior = want.balanceOf(address(ironBankToken));
uint256 borrows = ironBankToken.totalBorrows();
uint256 reserves = ironBankToken.totalReserves();
InterestRateModel model = ironBankToken.interestRateModel();
uint256 cashChange;
uint256 borrowChange;
if(repay){
cashChange = cashPrior.add(amount);
borrowChange = borrows.sub(amount);
}else{
cashChange = cashPrior.sub(amount);
borrowChange = borrows.add(amount);
}
uint256 borrowRate = model.getBorrowRate(cashChange, borrowChange, reserves);
return borrowRate;
}
function setPriceOracle(address _oracle) external onlyAuthorized{
wantToEthOracle = _oracle;
}
function name() external view override returns (string memory) {
return "StrategyLenderYieldOptimiserIB";
}
//management functions
//add lenders for the strategy to choose between
// only governance to stop strategist adding dodgy lender
function addLender(address a) public onlyGovernance {
IGenericLender n = IGenericLender(a);
require(n.strategy() == address(this), "Undocked Lender");
for (uint256 i = 0; i < lenders.length; i++) {
require(a != address(lenders[i]), "Already Added");
}
lenders.push(n);
}
//but strategist can remove for safety
function safeRemoveLender(address a) public onlyAuthorized {
_removeLender(a, false);
}
function forceRemoveLender(address a) public onlyAuthorized {
_removeLender(a, true);
}
//force removes the lender even if it still has a balance
function _removeLender(address a, bool force) internal {
for (uint256 i = 0; i < lenders.length; i++) {
if (a == address(lenders[i])) {
bool allWithdrawn = lenders[i].withdrawAll();
if (!force) {
require(allWithdrawn, "WITHDRAW FAILED");
}
//put the last index here
//remove last index
if (i != lenders.length-1) {
lenders[i] = lenders[lenders.length - 1];
}
//pop shortens array by 1 thereby deleting the last index
lenders.pop();
//if balance to spend we might as well put it into the best lender
if (want.balanceOf(address(this)) > 0) {
adjustPosition(0);
}
return;
}
}
require(false, "NOT LENDER");
}
//we could make this more gas efficient but it is only used by a view function
struct lendStatus {
string name;
uint256 assets;
uint256 rate;
address add;
}
//Returns the status of all lenders attached the strategy
function lendStatuses() public view returns (lendStatus[] memory) {
lendStatus[] memory statuses = new lendStatus[](lenders.length);
for (uint256 i = 0; i < lenders.length; i++) {
lendStatus memory s;
s.name = lenders[i].lenderName();
s.add = address(lenders[i]);
s.assets = lenders[i].nav();
s.rate = lenders[i].apr().mul(BLOCKSPERYEAR);
statuses[i] = s;
}
return statuses;
}
// lent assets plus loose assets
function estimatedTotalAssets() public view override returns (uint256) {
uint256 nav = lentTotalAssets();
nav += want.balanceOf(address(this));
uint256 ironBankDebt = ironBankOutstandingDebtStored();
if(ironBankDebt > nav) return 0;
return nav.sub(ironBankDebt);
}
function numLenders() public view returns (uint256) {
return lenders.length;
}
//the weighted apr of all lenders. sum(nav * apr)/totalNav
function currentSupplyRate() public view returns (uint256) {
uint256 bal = lentTotalAssets();
bal += want.balanceOf(address(this));
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
weightedAPR += lenders[i].weightedApr();
}
return weightedAPR.div(bal);
}
function estimatedAPR() public view returns (uint256){
uint256 outstandingDebt = ironBankOutstandingDebtStored();
uint256 ironBankBR = ironBankBorrowRate(0, true);
uint256 id = outstandingDebt.mul(ironBankBR);
uint256 currentSR = currentSupplyRate();
uint256 assets = lentTotalAssets().add(want.balanceOf(address(this)));
uint256 ti = assets.mul(currentSR);
if(ti > id && assets > outstandingDebt){
return ti.sub(id).div(assets.sub(outstandingDebt)).mul(BLOCKSPERYEAR);
}else{
return 0;
}
}
//Estimates the impact on APR if we add more money. It does not take into account adjusting position
function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) {
uint256 highestAPR = 0;
uint256 aprChoice = 0;
uint256 assets = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr > highestAPR) {
aprChoice = i;
highestAPR = apr;
assets = lenders[i].nav();
}
}
uint256 weightedAPR = highestAPR.mul(assets.add(change));
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR += lenders[i].weightedApr();
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//Estimates debt limit decrease. It is not accurate and should only be used for very broad decision making
function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) {
uint256 lowestApr = uint256(-1);
uint256 aprChoice = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr = lenders[i].aprAfterDeposit(change);
if (apr < lowestApr) {
aprChoice = i;
lowestApr = apr;
}
}
uint256 weightedAPR = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (i != aprChoice) {
weightedAPR += lenders[i].weightedApr();
} else {
uint256 asset = lenders[i].nav();
if (asset < change) {
//simplistic. not accurate
change = asset;
}
weightedAPR += lowestApr.mul(change);
}
}
uint256 bal = estimatedTotalAssets().add(change);
return weightedAPR.div(bal);
}
//estimates highest and lowest apr lenders. Public for debugging purposes but not much use to general public
function estimateAdjustPosition()
public
view
returns (
uint256 _lowest,
uint256 _lowestApr,
uint256 _highest,
uint256 _potential
)
{
//all loose assets are to be invested
uint256 looseAssets = want.balanceOf(address(this));
// our simple algo
// get the lowest apr strat
// cycle through and see who could take its funds plus want for the highest apr
_lowestApr = uint256(-1);
_lowest = 0;
uint256 lowestNav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < _lowestApr) {
_lowestApr = apr;
_lowest = i;
lowestNav = lenders[i].nav();
}
}
}
uint256 toAdd = lowestNav.add(looseAssets);
uint256 highestApr = 0;
_highest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
uint256 apr;
apr = lenders[i].aprAfterDeposit(looseAssets);
if (apr > highestApr) {
highestApr = apr;
_highest = i;
}
}
//if we can improve apr by withdrawing we do so
_potential = lenders[_highest].aprAfterDeposit(toAdd);
}
//gives estiomate of future APR with a change of debt limit. Useful for governance to decide debt limits
function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) {
uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt;
uint256 change;
if (oldDebtLimit < newDebtLimit) {
change = newDebtLimit - oldDebtLimit;
return _estimateDebtLimitIncrease(change);
} else {
change = oldDebtLimit - newDebtLimit;
return _estimateDebtLimitDecrease(change);
}
}
//cycle all lenders and collect balances
function lentTotalAssets() public view returns (uint256) {
uint256 nav = 0;
for (uint256 i = 0; i < lenders.length; i++) {
nav += lenders[i].nav();
}
return nav;
}
//we need to free up profit plus _debtOutstanding.
//If _debtOutstanding is more than we can free we get as much as possible
// should be no way for there to be a loss. we hope...
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
_profit = 0;
_loss = 0; //for clarity
_debtPayment = _debtOutstanding;
uint256 lentAssets = lentTotalAssets();
uint256 looseAssets = want.balanceOf(address(this));
uint256 ironBankDebt = ironBankOutstandingDebtStored();
uint256 total = looseAssets.add(lentAssets);
if(ironBankDebt < total){
total = total.sub(ironBankDebt);
}else{
total = 0;
}
if (lentAssets == 0) {
//no position to harvest or profit to report
if (_debtPayment > looseAssets) {
//we can only return looseAssets
_debtPayment = looseAssets;
}
return (_profit, _loss, _debtPayment);
}
uint256 debt = vault.strategies(address(this)).totalDebt;
if (total > debt) {
_profit = total - debt;
uint256 amountToFree = _profit.add(_debtPayment);
//we need to add outstanding to our profit
//dont need to do logic if there is nothiing to free
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _profit, _debtPayment);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - total;
uint256 amountToFree = _loss.add(_debtPayment);
if (amountToFree > 0 && looseAssets < amountToFree) {
//withdraw what we can withdraw
_withdrawSome(amountToFree.sub(looseAssets));
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_loss > newLoose) {
_loss = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(newLoose - _loss, _debtPayment);
}
}
}
}
}
/*
* Key logic.
* The algorithm moves assets from lowest return to highest
* like a very slow idiots bubble sort
* we ignore debt outstanding for an easy life
*/
function adjustPosition(uint256 _debtOutstanding) internal override {
//start off by borrowing or returning:
(bool borrowMore, uint256 amount) = internalCreditOfficer();
//do iron bank stuff first
if(!borrowMore){
(uint256 _amountFreed,) = liquidatePosition(amount);
//withdraw and repay
ironBankToken.repayBorrow(_amountFreed);
}else if(amount > 0){
//borrow the amount we want
ironBankToken.borrow(amount);
}
//emergency exit is dealt with at beginning of harvest
if (emergencyExit) {
return;
}
//we just keep all money in want if we dont have any lenders
if(lenders.length == 0){
return;
}
_debtOutstanding; //ignored. we handle it in prepare return
(uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition();
if (potential > lowestApr) {
//apr should go down after deposit so wont be withdrawing from self
lenders[lowest].withdrawAll();
}
uint256 bal = want.balanceOf(address(this));
if (bal > 0) {
want.safeTransfer(address(lenders[highest]), bal);
lenders[highest].deposit();
}
}
struct lenderRatio {
address lender;
//share x 1000
uint16 share;
}
//share must add up to 1000.
function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized {
uint256 share = 0;
for (uint256 i = 0; i < lenders.length; i++) {
lenders[i].withdrawAll();
}
uint256 assets = want.balanceOf(address(this));
for (uint256 i = 0; i < _newPositions.length; i++) {
bool found = false;
//might be annoying and expensive to do this second loop but worth it for safety
for (uint256 j = 0; j < lenders.length; j++) {
if (address(lenders[j]) == _newPositions[j].lender) {
found = true;
}
}
require(found, "NOT LENDER");
share += _newPositions[i].share;
uint256 toSend = assets.mul(_newPositions[i].share).div(1000);
want.safeTransfer(_newPositions[i].lender, toSend);
IGenericLender(_newPositions[i].lender).deposit();
}
require(share == 1000, "SHARE!=1000");
}
//cycle through withdrawing from worst rate first
function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) {
//dont withdraw dust
if (_amount < debtThreshold) {
return 0;
}
amountWithdrawn = 0;
//most situations this will only run once. Only big withdrawals will be a gas guzzler
uint256 j = 0;
while (amountWithdrawn < _amount) {
uint256 lowestApr = uint256(-1);
uint256 lowest = 0;
for (uint256 i = 0; i < lenders.length; i++) {
if (lenders[i].hasAssets()) {
uint256 apr = lenders[i].apr();
if (apr < lowestApr) {
lowestApr = apr;
lowest = i;
}
}
}
if (!lenders[lowest].hasAssets()) {
return amountWithdrawn;
}
amountWithdrawn += lenders[lowest].withdraw(_amount - amountWithdrawn);
j++;
//dont want infinite loop
if(j >= 6){
return amountWithdrawn;
}
}
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) {
uint256 _balance = want.balanceOf(address(this));
if (_balance >= _amountNeeded) {
//if we don't set reserve here withdrawer will be sent our full balance
return (_amountNeeded,0);
} else {
uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance);
if (received >= _amountNeeded) {
return (_amountNeeded,0);
} else {
return (received,0);
}
}
}
function harvestTrigger(uint256 callCost) public override view returns (bool) {
uint256 wantCallCost = _callCostToWant(callCost);
return super.harvestTrigger(wantCallCost);
}
function ethToWant(uint256 _amount) internal view returns (uint256){
address[] memory path = new address[](2);
path = new address[](2);
path[0] = weth;
path[1] = address(want);
uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path);
return amounts[amounts.length - 1];
}
function _callCostToWant(uint256 callCost) internal view returns (uint256){
uint256 wantCallCost;
//three situations
//1 currency is eth so no change.
//2 we use uniswap swap price
//3 we use external oracle
if(address(want) == weth){
wantCallCost = callCost;
}else if(wantToEthOracle == address(0)){
wantCallCost = ethToWant(callCost);
}else{
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// make sure to call tendtrigger with same callcost as harvestTrigger
if (harvestTrigger(callCost)) {
return false;
}
uint256 wantCallCost = _callCostToWant(callCost);
//test if we want to change iron bank position
(,uint256 _amount)= internalCreditOfficer();
if(profitFactor.mul(wantCallCost) < _amount){
return true;
}
//now let's check if there is better apr somewhere else.
//If there is and profit potential is worth changing then lets do it
(uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition();
//if protential > lowestApr it means we are changing horses
if (potential > lowestApr) {
uint256 nav = lenders[lowest].nav();
//profit increase is 1 days profit with new apr
uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).div(365);
return (wantCallCost.mul(profitFactor) < profitIncrease);
}
}
/*
* revert if we can't withdraw full balance
*/
function prepareMigration(address _newStrategy) internal override {
uint256 outstanding = vault.strategies(address(this)).totalDebt;
uint256 ibBorrows = ironBankToken.borrowBalanceCurrent(address(this));
(,, uint wantBalance) = prepareReturn(outstanding.add(ibBorrows));
ironBankToken.repayBorrow(Math.min(ibBorrows, wantBalance));
wantBalance = want.balanceOf(address(this));
// require(wantBalance.add(loss) >= outstanding, "LIQUIDITY LOCKED");
//require removed because in 0.3.0 we can still harvest after migrate
}
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(want);
return protected;
}
} | 61,499 |
50 | // ADMIN //called after deployment so that the contract can get random wolf thieves _barn the address of the Barn / | function setBarn(address _barn) external onlyOwner {
barn = IBarn(_barn);
}
| function setBarn(address _barn) external onlyOwner {
barn = IBarn(_barn);
}
| 14,856 |
169 | // Trying to be highly efficient, but no yul/assembly because it's harder to read | function airdrop(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner {
uint256 totalRecipients = recipients.length; // Number of recipients passed
require(totalRecipients == amounts.length, "Number of recipients and amounts don't match!");
unchecked { // As long as we don't pass more that 2**256-1 recipients in this won't overflow...
for (uint256 i = 0; i < totalRecipients;) {
// Uses raw transfer from the owner to the recipient. No tax/bot/logic involved
super._transfer(msg.sender, recipients[i], amounts[i]);
++i;
}
}
}
| function airdrop(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner {
uint256 totalRecipients = recipients.length; // Number of recipients passed
require(totalRecipients == amounts.length, "Number of recipients and amounts don't match!");
unchecked { // As long as we don't pass more that 2**256-1 recipients in this won't overflow...
for (uint256 i = 0; i < totalRecipients;) {
// Uses raw transfer from the owner to the recipient. No tax/bot/logic involved
super._transfer(msg.sender, recipients[i], amounts[i]);
++i;
}
}
}
| 14,342 |
17 | // Adds a new account owner account account address owner owner address / | function addAccountOwner(
address account,
address owner
)
external
| function addAccountOwner(
address account,
address owner
)
external
| 9,668 |
77 | // Returns the balance that is available to award./captureAwardBalance() should be called first/ return The total amount of assets to be awarded for the current prize | function awardBalance() external override view returns (uint256) {
return _currentAwardBalance;
}
| function awardBalance() external override view returns (uint256) {
return _currentAwardBalance;
}
| 14,369 |
47 | // Transfer 10% profit to current country owner | uint256 countryId = _tokenId % COUNTRY_IDX;
address countryOwner;
(countryOwner,,,,) = countryContract.getCountryData(countryId);
require (countryOwner != address(0));
countryOwner.transfer(poolCut.mul(COUNTRY_PAYOUT).div(100));
| uint256 countryId = _tokenId % COUNTRY_IDX;
address countryOwner;
(countryOwner,,,,) = countryContract.getCountryData(countryId);
require (countryOwner != address(0));
countryOwner.transfer(poolCut.mul(COUNTRY_PAYOUT).div(100));
| 9,414 |
42 | // v2_ohm_out = getAmountOut(amountin, reserve1, reserve0); |
v3_sohm_out = v3out(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2), address(0x04F2694C8fcee23e8Fd0dfEA1d4f5Bb8c352111F), 10000, lowerbound);
|
v3_sohm_out = v3out(address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2), address(0x04F2694C8fcee23e8Fd0dfEA1d4f5Bb8c352111F), 10000, lowerbound);
| 20,109 |
268 | // transfer LP tokens to user | pool.lpToken.safeTransfer(address(msg.sender), amount);
pool.totalDeposit = pool.totalDeposit.sub(user.amount);
| pool.lpToken.safeTransfer(address(msg.sender), amount);
pool.totalDeposit = pool.totalDeposit.sub(user.amount);
| 38,384 |
69 | // Returns asset implementation contract address assigned to sender./_sender sender address./ return asset implementation contract address. | function getVersionFor(address _sender) public view returns (address) {
return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender];
}
| function getVersionFor(address _sender) public view returns (address) {
return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender];
}
| 36,296 |
176 | // The MG TOKEN! | MGToken public mg;
| MGToken public mg;
| 8,905 |
259 | // 5. Increase xtoken | _mint(to, liquidity);
xtoken = address(this);
emit Mint(token, to, amountETH, amountToken, liquidity);
| _mint(to, liquidity);
xtoken = address(this);
emit Mint(token, to, amountETH, amountToken, liquidity);
| 86,024 |
4 | // Does the element exist ?/self the set itself/key the object's place in the set | function exists(Set storage self, bytes32 key) internal view returns(bool) {
if(self.keyList.length == 0) return false;
return self.keyList[self.keyPointers[key]] == key;
}
| function exists(Set storage self, bytes32 key) internal view returns(bool) {
if(self.keyList.length == 0) return false;
return self.keyList[self.keyPointers[key]] == key;
}
| 31,940 |
50 | // Must own one thousandth of outstanding tokens (100,000 eth) to administer oracle and receive dividends. Prevents spamming by de minimus token holders | require(amt >= 100 ether);
if (adminStruct[msg.sender].tokens > 0) {
uint userTokens = adminStruct[msg.sender].tokens;
uint ethClaim = (feePool - adminStruct[msg.sender].initFeePool ) * userTokens/ 1e18 ;
uint ethBalance = address(this).balance;
if (ethBalance <= ethClaim) ethClaim = ethBalance;
payable(msg.sender).transfer(ethClaim);
}
| require(amt >= 100 ether);
if (adminStruct[msg.sender].tokens > 0) {
uint userTokens = adminStruct[msg.sender].tokens;
uint ethClaim = (feePool - adminStruct[msg.sender].initFeePool ) * userTokens/ 1e18 ;
uint ethBalance = address(this).balance;
if (ethBalance <= ethClaim) ethClaim = ethBalance;
payable(msg.sender).transfer(ethClaim);
}
| 24,989 |
162 | // Reverses storage array in place/ | function sReverse(address[] storage A) internal {
address t;
uint256 length = A.length;
for (uint256 i = 0; i < length / 2; i++) {
t = A[i];
A[i] = A[A.length - i - 1];
A[A.length - i - 1] = t;
}
}
| function sReverse(address[] storage A) internal {
address t;
uint256 length = A.length;
for (uint256 i = 0; i < length / 2; i++) {
t = A[i];
A[i] = A[A.length - i - 1];
A[A.length - i - 1] = t;
}
}
| 27,532 |
389 | // gets the reserve total borrows variable_reserve the reserve address return the total borrows variable/ | function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.totalBorrowsVariable;
}
| function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.totalBorrowsVariable;
}
| 24,408 |
75 | // Name of token. / | string public constant name = "Hero";
| string public constant name = "Hero";
| 77,026 |
35 | // Initial token distribution | balances[_accICO] = totalSupply()/100*(100-PERCENT_BONUS);
balances[_accBonusTokens] = totalSupply()/100*PERCENT_BONUS;
emit Transfer(address(0), _accICO, totalSupply()/100*(100-PERCENT_BONUS));
emit Transfer(address(0), _accBonusTokens, totalSupply()/100*PERCENT_BONUS);
| balances[_accICO] = totalSupply()/100*(100-PERCENT_BONUS);
balances[_accBonusTokens] = totalSupply()/100*PERCENT_BONUS;
emit Transfer(address(0), _accICO, totalSupply()/100*(100-PERCENT_BONUS));
emit Transfer(address(0), _accBonusTokens, totalSupply()/100*PERCENT_BONUS);
| 74,906 |
518 | // In short, _stakeDailyUpdate needs to be called in all possible cases. | {
_stakeDailyUpdate();
return super.approve(spender, amount);
}
| {
_stakeDailyUpdate();
return super.approve(spender, amount);
}
| 36,228 |
27 | // For first deposit, just use the amounts desired | amount0 = amount0Desired;
amount1 = amount1Desired;
shares = Math.max(amount0, amount1);
| amount0 = amount0Desired;
amount1 = amount1Desired;
shares = Math.max(amount0, amount1);
| 12,992 |
65 | // Adds or removes dynamic support for an interface. Can be used in 3 ways:/ - Add a contract "delegate" that implements a single function/ - Remove delegate for a function/ - Specify that an interface ID is "supported", without adding a delegate. This is/ used for composite interfaces when the interface ID is not a single method ID./Must be called through `invoke`/_interfaceId The ID of the interface we are adding support for/_delegate Either:/- the address of a contract that implements the function specified by `_interfaceId`/for adding an implementation for a single function/- 0 for removing an existing delegate/- COMPOSITE_PLACEHOLDER for | function setDelegate(bytes4 _interfaceId, address _delegate) external onlyInvoked {
delegates[_interfaceId] = _delegate;
emit DelegateUpdated(_interfaceId, _delegate);
}
| function setDelegate(bytes4 _interfaceId, address _delegate) external onlyInvoked {
delegates[_interfaceId] = _delegate;
emit DelegateUpdated(_interfaceId, _delegate);
}
| 36,580 |
229 | // reset token emission based on APR | gloPerSec = 2 * glorycoin.balanceOf(address(pool.lpToken)) / 31536000 * ((apr+rsiBoost)/100);
uint256 gloReward = multiplier.mul(gloPerSec).mul(pool.allocPoint).div(
totalAllocPoint
);
| gloPerSec = 2 * glorycoin.balanceOf(address(pool.lpToken)) / 31536000 * ((apr+rsiBoost)/100);
uint256 gloReward = multiplier.mul(gloPerSec).mul(pool.allocPoint).div(
totalAllocPoint
);
| 4,288 |
61 | // this is a recent ethereum block hash, used to prevent pre-mining future blocks | function getChallengeNumber() public view returns (bytes32) {
return challengeNumber;
}
| function getChallengeNumber() public view returns (bytes32) {
return challengeNumber;
}
| 33,479 |
27 | // When unpaused, staking will be re-enabled | function unpause() external onlyOwner {
_unpause();
}
| function unpause() external onlyOwner {
_unpause();
}
| 5,379 |
10 | // returns the loan amount before interest/ | function getLoanAmount(bytes32 _requestId) external view returns (uint256);
| function getLoanAmount(bytes32 _requestId) external view returns (uint256);
| 25,489 |
157 | // Emitted when liquidity is minted for a given position/transfers reinvestment tokens for any collected fees earned by the position/sender address that minted the liquidity/owner address of owner of the position/tickLower position's lower tick/tickUpper position's upper tick/qty liquidity minted to the position range/qty0 token0 quantity needed to mint the liquidity/qty1 token1 quantity needed to mint the liquidity | event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 qty,
uint256 qty0,
uint256 qty1
);
| event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 qty,
uint256 qty0,
uint256 qty1
);
| 30,077 |
105 | // pause once cards become tradable | function claimPheonix(address user) public returns (bool){
require(isApproved(msg.sender));
if (claimed[user] || paused){
return false;
}
claimed[user] = true;
core.createCard(user, PHEONIX_PROTO, 0);
return true;
}
| function claimPheonix(address user) public returns (bool){
require(isApproved(msg.sender));
if (claimed[user] || paused){
return false;
}
claimed[user] = true;
core.createCard(user, PHEONIX_PROTO, 0);
return true;
}
| 44,378 |
317 | // vault => user => amountOfDebtInShares | mapping(address => mapping(address => uint256)) public vaultDebt;
event Compensate(address user, address vault, uint compensatedFeeInAsset, uint compensatedFeeInShares);
event DebtToUser(address user, address vault, uint nonCompensatedFeeInShares);
| mapping(address => mapping(address => uint256)) public vaultDebt;
event Compensate(address user, address vault, uint compensatedFeeInAsset, uint compensatedFeeInShares);
event DebtToUser(address user, address vault, uint nonCompensatedFeeInShares);
| 57,944 |
41 | // Modifiers ----------------------------------------------------------------------------------------------------------------- | modifier onlyDeployer() {
require(isDeployer());
_;
}
| modifier onlyDeployer() {
require(isDeployer());
_;
}
| 21,875 |
10 | // Called by the user to retire his worker./workerAddress address of the worker to be retired/this also removes all authorizations in place | function retire(address payable workerAddress) external;
| function retire(address payable workerAddress) external;
| 33,438 |
48 | // newBalTo = poolRatio^(1/weightTo)balTo; | uint256 tokenOutRatio = poolRatio.bpow(BONE.bdiv(normalizedWeight));
uint256 newTokenBalanceOut = tokenOutRatio.bmul(tokenBalanceOut);
uint256 tokenAmountOutBeforeSwapFee =
tokenBalanceOut.bsub(newTokenBalanceOut);
| uint256 tokenOutRatio = poolRatio.bpow(BONE.bdiv(normalizedWeight));
uint256 newTokenBalanceOut = tokenOutRatio.bmul(tokenBalanceOut);
uint256 tokenAmountOutBeforeSwapFee =
tokenBalanceOut.bsub(newTokenBalanceOut);
| 1,582 |
13 | // supply cap check | uint256 amtTillMax = maxSupply - supply;
if(_amount > amtTillMax){
_amount = amtTillMax;
}
| uint256 amtTillMax = maxSupply - supply;
if(_amount > amtTillMax){
_amount = amtTillMax;
}
| 1,535 |
181 | // Ensure the caller is the creator of the request. | require(getRequestCreator[execHash] == msg.sender, "NOT_CREATOR");
| require(getRequestCreator[execHash] == msg.sender, "NOT_CREATOR");
| 65,254 |
442 | // withdraw lp fromGauge | Gauge(gauge).withdraw(_lpAmount);
| Gauge(gauge).withdraw(_lpAmount);
| 17,482 |
138 | // The block in which the migration was initiated | InitiatedInBlock = block.number;
| InitiatedInBlock = block.number;
| 16,823 |
26 | // Internal function that burns an amount of the token of a givenaccount, deducting from the sender's allowance for said account. Uses theinternal burn function. account The account whose tokens will be burnt. amount The amount that will be burnt. / | function _burnFrom(address account, uint256 amount) internal {
require(amount <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
amount);
_burn(account, amount);
}
| function _burnFrom(address account, uint256 amount) internal {
require(amount <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
amount);
_burn(account, amount);
}
| 18,155 |
140 | // Returns the amount of votes that `account` had at the end of a past block (`blockNumber`). / | function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
| function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
| 24,511 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.