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
170
// Returns the SECP256k1 public key associated with an ENS node.Defined in EIP 619. node The ENS node to queryreturn x, y the X and Y coordinates of the curve point for the public key. /
function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) { return (pubkeys[node].x, pubkeys[node].y); }
function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) { return (pubkeys[node].x, pubkeys[node].y); }
5,050
28
// Constant to simplify conversion of token amounts into integer form
uint256 public tokenUnit = uint256(10)**decimals;
uint256 public tokenUnit = uint256(10)**decimals;
13,890
44
// Burn selled tokens.
nftRegistry.burnBondedERC20( _tokenId, msgSender(), _liquidationAmount, reserveAmount );
nftRegistry.burnBondedERC20( _tokenId, msgSender(), _liquidationAmount, reserveAmount );
49,868
45
// these arrays will have 3 uints, 0 is 3 months, 1 is 6 months, 2 is 12 months
uint256[] public stakingAllocations; uint256[] public stakingMaxs; uint256[] public stakingShares; bool public stakingActive; IAddressIndex addressIndex; UniswapInterface routerContract = UniswapInterface(uniswapRouter);
uint256[] public stakingAllocations; uint256[] public stakingMaxs; uint256[] public stakingShares; bool public stakingActive; IAddressIndex addressIndex; UniswapInterface routerContract = UniswapInterface(uniswapRouter);
31,483
37
// returns the current debt based on actual block.timestamp (now)
function debt(uint loan) external view returns (uint) { uint rate_ = loanRates[loan]; uint chi_ = rates[rate_].chi; if (block.timestamp >= rates[rate_].lastUpdated) { chi_ = chargeInterest(rates[rate_].chi, rates[rate_].ratePerSecond, rates[rate_].lastUpdated); } return toAmount(chi_, pie[loan]); }
function debt(uint loan) external view returns (uint) { uint rate_ = loanRates[loan]; uint chi_ = rates[rate_].chi; if (block.timestamp >= rates[rate_].lastUpdated) { chi_ = chargeInterest(rates[rate_].chi, rates[rate_].ratePerSecond, rates[rate_].lastUpdated); } return toAmount(chi_, pie[loan]); }
31,091
152
// The amount (priced in want) of the total assets managed by this strategy should not count towards Yearn's TVL calculations. You can override this field to set it to a non-zero value if some of the assets of this Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. Note that this value must be strictly less than or equal to the amount provided by `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.return The amount of assets this strategy manages that should not be included in Yearn's Total Value Locked (TVL)
function delegatedAssets() external override view returns (uint256) { return 0; }
function delegatedAssets() external override view returns (uint256) { return 0; }
37,577
107
// register itself in a lookup table
_registerInterface(InterfaceId_ERC165);
_registerInterface(InterfaceId_ERC165);
32,299
59
// We won't do any pre or post processing, so leave _preRelayedCall and _postRelayedCall empty
// function _preRelayedCall(bytes memory context) internal override returns (bytes32) { // }
// function _preRelayedCall(bytes memory context) internal override returns (bytes32) { // }
28,536
167
// total tokenIds
uint256 public totalTokens;
uint256 public totalTokens;
67,763
486
// Deposits waTokens into the transmuter// amount the amount of waTokens to stake
function stake(uint256 amount) public runPhasedDistribution() updateAccount(msg.sender) checkIfNewUser()
function stake(uint256 amount) public runPhasedDistribution() updateAccount(msg.sender) checkIfNewUser()
22,943
111
// max reward block
uint256 public maxRewardBlockNumber;
uint256 public maxRewardBlockNumber;
11,543
112
// Block withdrawals within 1 hour of depositing.
modifier onceAnHour { require(block.timestamp >= balances[msg.sender].lastTime.add(1 hours), "You must wait an hour after your last update to withdraw."); _; }
modifier onceAnHour { require(block.timestamp >= balances[msg.sender].lastTime.add(1 hours), "You must wait an hour after your last update to withdraw."); _; }
80,919
1
// ensure that at least one full period has passed since the last update
require(timeElapsed >= PERIOD, 'ExampleOracleSimple: PERIOD_NOT_ELAPSED');
require(timeElapsed >= PERIOD, 'ExampleOracleSimple: PERIOD_NOT_ELAPSED');
2,338
1
// The first word of a string is its length
length := mload(message)
length := mload(message)
16,979
19
// Set token URI /
function setTokenURI(uint256 tokenId, string memory newURI) external { if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert UnauthorisedUser(); if (tokenId == 0) revert InvalidTokenId(); tokenMap[tokenId].URI = newURI; }
function setTokenURI(uint256 tokenId, string memory newURI) external { if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert UnauthorisedUser(); if (tokenId == 0) revert InvalidTokenId(); tokenMap[tokenId].URI = newURI; }
11,490
7
// Return the wei owed on a payment at the current block timestamp. /
function paymentWeiOwed(uint256 index) public view returns (uint256) { requirePaymentIndexInRange(index); Payment memory payment = payments[index]; // Calculate owed wei based on current time and total wei owed/paid return max(payment.weiPaid, payment.weiValue * min(block.timestamp - payment.timestamp, payment.time) / payment.time) - payment.weiPaid; }
function paymentWeiOwed(uint256 index) public view returns (uint256) { requirePaymentIndexInRange(index); Payment memory payment = payments[index]; // Calculate owed wei based on current time and total wei owed/paid return max(payment.weiPaid, payment.weiValue * min(block.timestamp - payment.timestamp, payment.time) / payment.time) - payment.weiPaid; }
38,960
303
// require(false, "HELLO: HOW ARE YOU TODAY!");
liquidity = IUniswapV2Pair(pair).mint(to); // << PROBLEM IS HERE
liquidity = IUniswapV2Pair(pair).mint(to); // << PROBLEM IS HERE
38,450
71
// Returns the link to artificat location for a given token by 'tokenId'.Throws if the token ID does not exist. May return an empty string. tokenId uint256 ID of the token to query.return The location where the artifact assets are stored. /
function tokenURI(uint256 tokenId) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory tokenIdStr = Strings.toString(tokenId); return string(abi.encodePacked(_baseURI, tokenIdStr)); }
function tokenURI(uint256 tokenId) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory tokenIdStr = Strings.toString(tokenId); return string(abi.encodePacked(_baseURI, tokenIdStr)); }
15,966
7
// Creates an upgradeable proxy version representing the first version to be set for the proxyreturn address of the new proxy created /
function createProxy(uint256 version, address _owner) external onlyOwner returns (address)
function createProxy(uint256 version, address _owner) external onlyOwner returns (address)
13,512
103
// We need to swap the current tokens to AVAX and send to the team wallet
swapTokensForAvax(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendAVAXToTeam(address(this).balance); }
swapTokensForAvax(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendAVAXToTeam(address(this).balance); }
29,134
166
// Throws if the sender is not the SetToken methodologist /
modifier onlyMethodologist() { require(msg.sender == manager.methodologist(), "Must be methodologist"); _; }
modifier onlyMethodologist() { require(msg.sender == manager.methodologist(), "Must be methodologist"); _; }
29,387
62
// Check valid params and number of choices:
require(parameters[_paramsHash].precReq > 0); require(_numOfChoices > 0 && _numOfChoices <= MAX_NUM_OF_CHOICES);
require(parameters[_paramsHash].precReq > 0); require(_numOfChoices > 0 && _numOfChoices <= MAX_NUM_OF_CHOICES);
2,689
47
// profits - liquidationFee gets paid out
int256 reducedProfit = user.profit - liquidationFee;
int256 reducedProfit = user.profit - liquidationFee;
4,881
30
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.membersDone & memberIndexBit == 0) { Confirmation(msg.sender, _operation);
if (pending.membersDone & memberIndexBit == 0) { Confirmation(msg.sender, _operation);
20,121
114
// tokenId id of the token/indices query indices for TokenDescriptor
function setTokenIndices(uint256 tokenId, uint256[2] memory indices) public override onlyUpdateAdmin
function setTokenIndices(uint256 tokenId, uint256[2] memory indices) public override onlyUpdateAdmin
60,111
92
// User can request to convert their tokens from older AugmintToken versions in 1:1/
function transferNotification(address from, uint amount, uint /* data, not used */ ) external { AugmintTokenInterface legacyToken = AugmintTokenInterface(msg.sender); require(acceptedLegacyAugmintTokens[legacyToken], "msg.sender must be allowed in acceptedLegacyAugmintTokens"); legacyToken.burn(amount); augmintToken.issueTo(from, amount); emit LegacyTokenConverted(msg.sender, from, amount); }
function transferNotification(address from, uint amount, uint /* data, not used */ ) external { AugmintTokenInterface legacyToken = AugmintTokenInterface(msg.sender); require(acceptedLegacyAugmintTokens[legacyToken], "msg.sender must be allowed in acceptedLegacyAugmintTokens"); legacyToken.burn(amount); augmintToken.issueTo(from, amount); emit LegacyTokenConverted(msg.sender, from, amount); }
49,195
171
// Returns the number of key-value pairs in the map. O(1). /
function _length(Map storage map) private view returns (uint256) { return map._entries.length; }
function _length(Map storage map) private view returns (uint256) { return map._entries.length; }
196
80
// Redeem as much collateral as possible from _borrower's Trove in exchange for LUSD up to _maxLUSDamount
function _redeemCollateralFromTrove( ContractsCache memory _contractsCache, address _borrower, uint _maxLUSDamount, uint _price, address _upperPartialRedemptionHint, address _lowerPartialRedemptionHint, uint _partialRedemptionHintNICR ) internal returns (SingleRedemptionValues memory singleRedemption)
function _redeemCollateralFromTrove( ContractsCache memory _contractsCache, address _borrower, uint _maxLUSDamount, uint _price, address _upperPartialRedemptionHint, address _lowerPartialRedemptionHint, uint _partialRedemptionHintNICR ) internal returns (SingleRedemptionValues memory singleRedemption)
9,121
37
// function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool) { balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); emit Transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value, _data); return true; }
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool) { balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); emit Transfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value, _data); return true; }
49,344
101
// Return the optimal rate and the strategy ID.
function optimizeSwap( address _from, address _to, uint256 _amount ) external returns (address strategy, uint256 amount);
function optimizeSwap( address _from, address _to, uint256 _amount ) external returns (address strategy, uint256 amount);
48,770
5
// This function sets the lifetime maximum deposit for a given asset/asset_source Contract address for given ERC20 token/lifetime_limit Deposit limit for a given ethereum address/nonce Vega-assigned single-use number that provides replay attack protection/signatures Vega-supplied signature bundle of a validator-signed order/asset must first be listed
function set_lifetime_deposit_max(address asset_source, uint256 lifetime_limit, uint256 nonce, bytes calldata signatures) public virtual;
function set_lifetime_deposit_max(address asset_source, uint256 lifetime_limit, uint256 nonce, bytes calldata signatures) public virtual;
3,769
4,718
// 2361
entry "uninquisitively" : ENG_ADVERB
entry "uninquisitively" : ENG_ADVERB
23,197
91
// initialize variables
minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
1,426
252
// Update reward amount before addliquidity
if (addAmount != 0) { balanceData.rewardAmount = _calcNextReward(balanceData, term); balanceData.term = uint64(term); balanceData.balance = balanceData.balance = uint256(balanceData.balance) .add(uint256(addAmount)) .toUint128(); }
if (addAmount != 0) { balanceData.rewardAmount = _calcNextReward(balanceData, term); balanceData.term = uint64(term); balanceData.balance = balanceData.balance = uint256(balanceData.balance) .add(uint256(addAmount)) .toUint128(); }
10,148
51
// Return Manager Module address from the Nexusreturn Address of the Manager Module contract /
function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); }
function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); }
23,245
50
// checks if a token is a Wizards tokenId the ID of the token to checkreturn wizard - whether or not a token is a Wizards /
function isLlama(uint256 tokenId) external view override returns (bool)
function isLlama(uint256 tokenId) external view override returns (bool)
81,969
156
// Owner able to mint independent of contract state
function mintForOwner(uint256 _mintAmount) public onlyOwner { require(_mintAmount > 0,"Need to mint 1 at least"); require(_mintAmount <= maxMintAmount); require(supply.current() + _mintAmount <= maxSupply, "MaxSupply exceeded"); _mintLoop(msg.sender, _mintAmount); }
function mintForOwner(uint256 _mintAmount) public onlyOwner { require(_mintAmount > 0,"Need to mint 1 at least"); require(_mintAmount <= maxMintAmount); require(supply.current() + _mintAmount <= maxSupply, "MaxSupply exceeded"); _mintLoop(msg.sender, _mintAmount); }
81,604
21
// Move an existing element into the vacated key slot.
self.data[self.keys[self.keys.length - 1]].keyIndex = e.keyIndex; self.keys[e.keyIndex - 1] = self.keys[self.keys.length - 1];
self.data[self.keys[self.keys.length - 1]].keyIndex = e.keyIndex; self.keys[e.keyIndex - 1] = self.keys[self.keys.length - 1];
3,610
132
// Replacing pool token with existing piToken. _underlyingToken Token, which will be wrapped by piToken. _piToken Address of piToken. /
function replacePoolTokenWithExistingPiToken(address _underlyingToken, WrappedPiErc20Interface _piToken) external payable onlyOwner
function replacePoolTokenWithExistingPiToken(address _underlyingToken, WrappedPiErc20Interface _piToken) external payable onlyOwner
10,293
1
// Get total number of tokens in circulation. return total number of tokens in circulation /
function totalSupply () public view returns (uint256 supply);
function totalSupply () public view returns (uint256 supply);
24,776
11
// ,-.`-'/|\ |,----------------.,----------./ \ |ZoraNFTCreatorV1||ERC721Drop|Caller`-------+--------'`----+-----'| createDrop() || --------------------------------------------------------->| ||| |----.| || initialize NFT metadata| |<---'| ||| | deploy || | --------------------------->| ||| | initialize drop|| | --------------------------->| ||| |----. || || emit CreatedDrop|| |<---' || ||| return drop contract address||| <----------------------------|Caller,-------+--------.,----+-----.,-. |ZoraNFTCreatorV1||ERC721Drop|`-' `----------------'`----------'/|\ |/ \/Setup the media contract for a drop/name Name for new contract (cannot be changed)/symbol Symbol for new contract (cannot be changed)/defaultAdmin Default admin address/editionSize The max size of the media contract allowed/royaltyBPS BPS for on-chain royalties (cannot be changed)/fundsRecipient recipient for sale funds and, unless overridden, royalties/metadataURIBase URI Base for metadata/metadataContractURI URI for contract metadata
function createDrop( string memory name, string memory symbol, address defaultAdmin, uint64 editionSize, uint16 royaltyBPS, address payable fundsRecipient, IERC721Drop.ERC20SalesConfiguration memory saleConfig, string memory metadataURIBase, string memory metadataContractURI
function createDrop( string memory name, string memory symbol, address defaultAdmin, uint64 editionSize, uint16 royaltyBPS, address payable fundsRecipient, IERC721Drop.ERC20SalesConfiguration memory saleConfig, string memory metadataURIBase, string memory metadataContractURI
32,217
132
// Wake up the avatar: can be modified/_tokenId The avatar id
function wakeUp( uint256 _tokenId ) external
function wakeUp( uint256 _tokenId ) external
6,028
7
// helper methods for interacting with BEP20 tokens and sending ETH that do not consistently return true/false
library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } // function safeTransferBNB(address to, uint256 value) internal { // (bool success, ) = to.call{value: value}(new bytes(0)); // require(success, 'TransferHelper: BNB_TRANSFER_FAILED'); // } }
library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } // function safeTransferBNB(address to, uint256 value) internal { // (bool success, ) = to.call{value: value}(new bytes(0)); // require(success, 'TransferHelper: BNB_TRANSFER_FAILED'); // } }
3,850
52
// return the accumulated fees/
function getFees() constant public returns(uint) { uint reserved = 0; for (uint16 j = 0; j < numCharacters; j++) reserved += characters[ids[j]].value; return address(this).balance - reserved; }
function getFees() constant public returns(uint) { uint reserved = 0; for (uint16 j = 0; j < numCharacters; j++) reserved += characters[ids[j]].value; return address(this).balance - reserved; }
49,544
13
// Set Commission Rate /
{ Settings storage s = getSettings(); if (_permanent) s.perma_commission_rate = _msg; else s.common_commission_rate = _msg; }
{ Settings storage s = getSettings(); if (_permanent) s.perma_commission_rate = _msg; else s.common_commission_rate = _msg; }
6,597
143
// wrap given element in array of length 1 element element to wrapreturn singleton array /
function _asSingletonArray ( uint element
function _asSingletonArray ( uint element
61,552
92
// An event emitted when setting the fee amount for a token
event FeeSet(address token_, uint256 oldFee_, uint256 newFee_);
event FeeSet(address token_, uint256 oldFee_, uint256 newFee_);
19,672
73
// Returns the Wallet contract address associated to a user account. If the user account is not known, try tomigrate the wallet address from the old exchange instance. This function is equivalent to getWallet(), in additionit stores the wallet address fetched from old the exchange instance. userAccount The user account addressreturn The address of the Wallet instance associated to the user account /
function retrieveWallet(address userAccount) public returns(address walletAddress) { walletAddress = userAccountToWallet_[userAccount]; if (walletAddress == address(0) && previousExchangeAddress_ != 0) {
function retrieveWallet(address userAccount) public returns(address walletAddress) { walletAddress = userAccountToWallet_[userAccount]; if (walletAddress == address(0) && previousExchangeAddress_ != 0) {
41,705
111
// Approve or remove 'operator' as an operator for the caller.Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. Requirements: - The 'operator' cannot be the caller. Emits an {ApprovalForAll} event. /
function setApprovalForAll(address operator, bool _approved) external;
function setApprovalForAll(address operator, bool _approved) external;
26,173
16
// Remove our whole balance
daiJoin.exit(address(this), bal / RAY);
daiJoin.exit(address(this), bal / RAY);
4,269
55
// creates a new edgeless casino contract.predecessorAddress the address of the predecessing contract tokenContractthe address of the Edgeless token contractdepositLimit the maximum deposit allowedkGasPricethe price per kGas in WEI/
function EdgelessCasino(address predecessorAddress, address tokenContract, uint depositLimit, uint kGasPrice) CasinoBank(depositLimit, predecessorAddress) mortal(tokenContract) chargingGas(kGasPrice) public{ }
function EdgelessCasino(address predecessorAddress, address tokenContract, uint depositLimit, uint kGasPrice) CasinoBank(depositLimit, predecessorAddress) mortal(tokenContract) chargingGas(kGasPrice) public{ }
54,483
129
// Should be executed after grand prize is received
uint256 mediumPrize = mediumPrizeTotal; uint256 eligibleHolderCount = 100; uint256 totalDisbursed = 0; uint256 seed = 48; address[] memory eligibleAddresses = new address[](100); uint8 counter = 0;
uint256 mediumPrize = mediumPrizeTotal; uint256 eligibleHolderCount = 100; uint256 totalDisbursed = 0; uint256 seed = 48; address[] memory eligibleAddresses = new address[](100); uint8 counter = 0;
32,717
29
// ERC20 tokenImplementation of the basic standard token. /
contract Likoin is SimpleToken{ // the token being converted to Buck private _buck; // How many bucks a buyer gets per token. uint256 private _conversionRate; // Balances mapping (address => uint256[2]) _balances; // Allowances mapping, used to allow an address to spend another address tokens mapping (address => mapping (address => uint256)) private _allowed; // Addresses of holders, list that starts from 1 mapping (uint256 => address) private _balanceHolders; // Index of last holder in list uint256 _holdersIndex; /** * Event for token conversion */ event TokensConversion(address indexed beneficiary, uint256 amount); /** * Event for an approval */ event Approval( address indexed owner, address indexed spender, uint256 value); /** * @param assignee Address of the entity token depends on * @param buck Address of the token used for conversion * @param conversionRate Number of buck units a buyer gets per tokens * @param name Token name * @param symbol Token symbol */ constructor(address assignee, Buck buck, uint256 conversionRate, string name, string symbol) public { require(conversionRate > 0); require(assignee != address(0)); require(buck != address(0)); _owner = msg.sender; _assignee = assignee; _addMinter(msg.sender); _addMinter(assignee); _name = name; _symbol = symbol; _buck = buck; _conversionRate = conversionRate; } /** * @dev Transfer token to a specified address */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev The way in which tokens are converted to bucks. */ function convertToBucks(uint256 value) public returns (bool success) { require(balanceOf(msg.sender) >= value); _shareToken(msg.sender, value); emit TokensConversion(msg.sender, value); uint256 bucks = value * _conversionRate; _buck.mint(msg.sender, bucks); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another if the address from approved msg.sender */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from][0]); require(to != address(0)); if(_balances[to][0] <= 0){ _addHolder(to); } _balances[from][0] = _balances[from][0].sub(value); _balances[to][0] = _balances[to][0].add(value); if(_balances[from][0] <= 0){ _removeHolder(from); } emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. */ function _mint(address account, uint256 value) internal { require(account != 0); if(_balances[account][0] <= 0){ _addHolder(account); } _totalSupply = _totalSupply.add(value); _balances[account][0] = _balances[account][0].add(value); emit Transfer(address(0), account, value); } /** * @dev Share value tokens between all addresses except from */ function _shareToken(address from, uint256 value) internal returns (bool) { for(uint i = 1; i <= _holdersIndex; i++){ if(to != from){ address to = _balanceHolders[i]; uint256 bal = balanceOf(to); _transfer(from, to, value.mul(bal.div(_totalSupply.sub(value)))); //value * ( balance[to] / (totalSupply-value) ) } } return true; } /** * @dev Internal function that burns an amount of the token of a given * account. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account][0]); _totalSupply = _totalSupply.sub(value); _balances[account][0] = _balances[account][0].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); if(_balances[account][0] <= 0){ _removeHolder(account); } } /** * @dev Internal function that adds an holder */ function _addHolder(address account) internal { _balanceHolders[++_holdersIndex] = account; _balances[account][1] = _holdersIndex; } /** * @dev Internal function that removes an holder */ function _removeHolder(address account) internal { uint256 index = _balances[account][1]; if (index < 1) return; if(_holdersIndex > 1){ address last = _balanceHolders[_holdersIndex]; _balanceHolders[index] = last; _balances[last][1] = index; } _holdersIndex--; _balances[account][1] = 0; } /** * @return the token being used for conversion. */ function buck() public view returns(Buck) { return _buck; } /** * @return the number of buck units a buyer gets per token. */ function conversionRate() public view returns(uint256) { return _conversionRate; } /** * @dev Gets the balance of the specified address. */ function balanceOf(address account) public view returns (uint256) { return _balances[account][0]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Function that returns the balanceHolders length */ function getBalanceHoldersLength() public view returns (uint256) { return _holdersIndex; } /** * @dev Function that returns the address in position i of balanceHolders */ function getBalanceHolder(uint256 i) public view returns (address) { require (i <= _holdersIndex); return _balanceHolders[i]; } }
contract Likoin is SimpleToken{ // the token being converted to Buck private _buck; // How many bucks a buyer gets per token. uint256 private _conversionRate; // Balances mapping (address => uint256[2]) _balances; // Allowances mapping, used to allow an address to spend another address tokens mapping (address => mapping (address => uint256)) private _allowed; // Addresses of holders, list that starts from 1 mapping (uint256 => address) private _balanceHolders; // Index of last holder in list uint256 _holdersIndex; /** * Event for token conversion */ event TokensConversion(address indexed beneficiary, uint256 amount); /** * Event for an approval */ event Approval( address indexed owner, address indexed spender, uint256 value); /** * @param assignee Address of the entity token depends on * @param buck Address of the token used for conversion * @param conversionRate Number of buck units a buyer gets per tokens * @param name Token name * @param symbol Token symbol */ constructor(address assignee, Buck buck, uint256 conversionRate, string name, string symbol) public { require(conversionRate > 0); require(assignee != address(0)); require(buck != address(0)); _owner = msg.sender; _assignee = assignee; _addMinter(msg.sender); _addMinter(assignee); _name = name; _symbol = symbol; _buck = buck; _conversionRate = conversionRate; } /** * @dev Transfer token to a specified address */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev The way in which tokens are converted to bucks. */ function convertToBucks(uint256 value) public returns (bool success) { require(balanceOf(msg.sender) >= value); _shareToken(msg.sender, value); emit TokensConversion(msg.sender, value); uint256 bucks = value * _conversionRate; _buck.mint(msg.sender, bucks); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another if the address from approved msg.sender */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from][0]); require(to != address(0)); if(_balances[to][0] <= 0){ _addHolder(to); } _balances[from][0] = _balances[from][0].sub(value); _balances[to][0] = _balances[to][0].add(value); if(_balances[from][0] <= 0){ _removeHolder(from); } emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. */ function _mint(address account, uint256 value) internal { require(account != 0); if(_balances[account][0] <= 0){ _addHolder(account); } _totalSupply = _totalSupply.add(value); _balances[account][0] = _balances[account][0].add(value); emit Transfer(address(0), account, value); } /** * @dev Share value tokens between all addresses except from */ function _shareToken(address from, uint256 value) internal returns (bool) { for(uint i = 1; i <= _holdersIndex; i++){ if(to != from){ address to = _balanceHolders[i]; uint256 bal = balanceOf(to); _transfer(from, to, value.mul(bal.div(_totalSupply.sub(value)))); //value * ( balance[to] / (totalSupply-value) ) } } return true; } /** * @dev Internal function that burns an amount of the token of a given * account. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account][0]); _totalSupply = _totalSupply.sub(value); _balances[account][0] = _balances[account][0].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); if(_balances[account][0] <= 0){ _removeHolder(account); } } /** * @dev Internal function that adds an holder */ function _addHolder(address account) internal { _balanceHolders[++_holdersIndex] = account; _balances[account][1] = _holdersIndex; } /** * @dev Internal function that removes an holder */ function _removeHolder(address account) internal { uint256 index = _balances[account][1]; if (index < 1) return; if(_holdersIndex > 1){ address last = _balanceHolders[_holdersIndex]; _balanceHolders[index] = last; _balances[last][1] = index; } _holdersIndex--; _balances[account][1] = 0; } /** * @return the token being used for conversion. */ function buck() public view returns(Buck) { return _buck; } /** * @return the number of buck units a buyer gets per token. */ function conversionRate() public view returns(uint256) { return _conversionRate; } /** * @dev Gets the balance of the specified address. */ function balanceOf(address account) public view returns (uint256) { return _balances[account][0]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Function that returns the balanceHolders length */ function getBalanceHoldersLength() public view returns (uint256) { return _holdersIndex; } /** * @dev Function that returns the address in position i of balanceHolders */ function getBalanceHolder(uint256 i) public view returns (address) { require (i <= _holdersIndex); return _balanceHolders[i]; } }
5,722
232
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex];
delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex];
7,944
89
// Getter functions
function gauge_types(address) external view returns (int128); function gauge_relative_weight(address) external view returns (uint256); function gauge_relative_weight(address, uint256) external view returns (uint256); function get_gauge_weight(address) external view returns (uint256); function get_type_weight(int128) external view returns (uint256); function get_total_weight() external view returns (uint256); function get_weights_sum_per_type(int128) external view returns (uint256);
function gauge_types(address) external view returns (int128); function gauge_relative_weight(address) external view returns (uint256); function gauge_relative_weight(address, uint256) external view returns (uint256); function get_gauge_weight(address) external view returns (uint256); function get_type_weight(int128) external view returns (uint256); function get_total_weight() external view returns (uint256); function get_weights_sum_per_type(int128) external view returns (uint256);
18,500
30
// TTC token contract. Implements /
contract TTC is StandardToken, Ownable { string public constant name = "TTC"; string public constant symbol = "TTC"; uint public constant decimals = 18; // Constructor function TTC() public { totalSupply = 1000000000000000000000000000; balances[msg.sender] = totalSupply; // Send all tokens to owner } /** * Burn away the specified amount of SkinCoin tokens */ function burn(uint _value) onlyOwner public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); return true; } }
contract TTC is StandardToken, Ownable { string public constant name = "TTC"; string public constant symbol = "TTC"; uint public constant decimals = 18; // Constructor function TTC() public { totalSupply = 1000000000000000000000000000; balances[msg.sender] = totalSupply; // Send all tokens to owner } /** * Burn away the specified amount of SkinCoin tokens */ function burn(uint _value) onlyOwner public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); return true; } }
14,480
64
//
swapping = false;
swapping = false;
25,368
193
// add the buffer to the current variable rate
return variableRate.add(maxBuffer);
return variableRate.add(maxBuffer);
60,971
57
// Totals for all members
RewardTotals private _rewardTotals;
RewardTotals private _rewardTotals;
47,798
16
// constructor /
constructor() public { owners[msg.sender] = true; }
constructor() public { owners[msg.sender] = true; }
28,761
9
// The reward tokens.
address[] public rewardTokens;
address[] public rewardTokens;
34,521
79
// Get the underlying price of a cToken Implements the PriceOracle interface for Compound v2. cToken The cToken address for price retrievalreturn Price denominated in USD, with 18 decimals, for the given cToken address /
function getUnderlyingPrice(address cToken) external view returns (uint) { TokenConfig memory config = getTokenConfigByCToken(cToken); // Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit) // Since the prices in this view have 6 decimals, we must scale them by 1e(36 - 6 - baseUnit) return mul(1e30, priceInternal(config)) / config.baseUnit; }
function getUnderlyingPrice(address cToken) external view returns (uint) { TokenConfig memory config = getTokenConfigByCToken(cToken); // Comptroller needs prices in the format: ${raw price} * 1e(36 - baseUnit) // Since the prices in this view have 6 decimals, we must scale them by 1e(36 - 6 - baseUnit) return mul(1e30, priceInternal(config)) / config.baseUnit; }
62,670
367
// This emits when the approved address for an NFT is changed or/reaffirmed. The zero address indicates there is no approved address./When a Transfer event emits, this also indicates that the approved/address for that NFT (if any) is reset to none.
event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId );
event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId );
54,878
19
// max and min token buy limit per account
uint256 public minEthLimit = 100 finney; uint256 public maxEthLimit = 3 ether; mapping(address => uint256) public usersInvestments;
uint256 public minEthLimit = 100 finney; uint256 public maxEthLimit = 3 ether; mapping(address => uint256) public usersInvestments;
3,981
2
// admin events // user events // data types /
struct HypervisorData { address stakingToken; address rewardToken; address rewardPool; RewardScaling rewardScaling; uint256 rewardSharesOutstanding; uint256 totalStake; uint256 totalStakeUnits; uint256 lastUpdate; RewardSchedule[] rewardSchedules; }
struct HypervisorData { address stakingToken; address rewardToken; address rewardPool; RewardScaling rewardScaling; uint256 rewardSharesOutstanding; uint256 totalStake; uint256 totalStakeUnits; uint256 lastUpdate; RewardSchedule[] rewardSchedules; }
11,549
7
// Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio/Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may/ ever return./sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96/ return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; }
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; }
24,553
248
// Ensure that the action type is a valid custom action type.
bool validActionType = ( action == ActionType.Cancel || action == ActionType.SetUserSigningKey || action == ActionType.DAIWithdrawal || action == ActionType.USDCWithdrawal || action == ActionType.ETHWithdrawal || action == ActionType.SetEscapeHatch || action == ActionType.RemoveEscapeHatch || action == ActionType.DisableEscapeHatch );
bool validActionType = ( action == ActionType.Cancel || action == ActionType.SetUserSigningKey || action == ActionType.DAIWithdrawal || action == ActionType.USDCWithdrawal || action == ActionType.ETHWithdrawal || action == ActionType.SetEscapeHatch || action == ActionType.RemoveEscapeHatch || action == ActionType.DisableEscapeHatch );
16,828
99
// Kyber Proxy contract to trade tokens/ETH to tokenToBurn
IKyberNetworkProxyInterface public kyberProxy;
IKyberNetworkProxyInterface public kyberProxy;
39,977
20
// Moves `amount` tokens from `sender` to `recipient` using theallowance mechanism. `amount` is then deducted from the caller'sallowance. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event. /
function transferFrom(
function transferFrom(
159
47
// See {BEP20-balanceOf}. /
function balanceOf(address account) external view returns (uint256) { return _balances[account]; }
function balanceOf(address account) external view returns (uint256) { return _balances[account]; }
4,251
39
// Get VIP rank of a given owner.VIP ranking is valid for the lifetime of a token wallet address, as long as it meets VIP holding level._to participant address to get the vip rankreturn vip rank of the owner of given address /
function getVIPRank(address _to) constant public returns (uint256 rank) { if (balances[_to] < VIP_MINIMUM) { return 0; } return viprank[_to]; }
function getVIPRank(address _to) constant public returns (uint256 rank) { if (balances[_to] < VIP_MINIMUM) { return 0; } return viprank[_to]; }
25,392
67
// Change threshold if threshold was changed.
if (threshold != _threshold) changeThreshold(_threshold);
if (threshold != _threshold) changeThreshold(_threshold);
6,675
1
// Total Items. I am not sure why this variable is being used, seems like a waste of gas.
uint256 public constant totalItems = 11;
uint256 public constant totalItems = 11;
33,347
7
// Fee paid to feeRecipient by taker when order is filled.
uint256 takerFee;
uint256 takerFee;
27,049
251
// return if transfer is enabled or not. /
function transferEnabled() public view returns (bool) { return _transferEnabled; }
function transferEnabled() public view returns (bool) { return _transferEnabled; }
11,910
181
// This also ensures that _strategy must be a valid strategy contract.
require(address(token) == IStrategy(_strategy).want(), "different token");
require(address(token) == IStrategy(_strategy).want(), "different token");
45,319
24
// set contract address as Approved minter set active state to false log and emit current time
function setApprovedMinter(address minter, bool allowed) public onlyOwner { allowedMinters[minter] = allowed; enableRaffle(); startTime = block.timestamp; emit Rafflestarted(minter, startTime); }
function setApprovedMinter(address minter, bool allowed) public onlyOwner { allowedMinters[minter] = allowed; enableRaffle(); startTime = block.timestamp; emit Rafflestarted(minter, startTime); }
5,752
7
// The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
3,348
55
// Calculate profit for correct staker
profit = potRemaining.mul(s.stakes[j].amount) / winningPot;
profit = potRemaining.mul(s.stakes[j].amount) / winningPot;
18,997
59
// Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but performing a static call. _Available since v3.3._/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); }
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); }
35,875
80
// Payout recipient
(bool successFunds, ) = config.fundsRecipient.call{ value: funds, gas: FUNDS_SEND_GAS_LIMIT }("");
(bool successFunds, ) = config.fundsRecipient.call{ value: funds, gas: FUNDS_SEND_GAS_LIMIT }("");
10,216
145
// snap spin quad
return _animateTransform( "rotate", duration, "0;90;90;180;180;270;270;360;360", "0;.125;.25;.375;.5;.625;.8;.925;1", generateSplines(8,0), attr );
return _animateTransform( "rotate", duration, "0;90;90;180;180;270;270;360;360", "0;.125;.25;.375;.5;.625;.8;.925;1", generateSplines(8,0), attr );
23,793
11
// similar to take(), but with the block height joined to calculate return./for instance, it returns (_amount, _block), which means at block height _block, the callee has accumulated _amount of interest./ return amount of interest and the block height.
function takeWithBlock() external view returns (uint, uint);
function takeWithBlock() external view returns (uint, uint);
31,023
27
// user action
function UpgradeLevelRobot() public whenNotPaused isHeroNFTJoinGame isNotUpgradeRobot
function UpgradeLevelRobot() public whenNotPaused isHeroNFTJoinGame isNotUpgradeRobot
20,297
2
// Begin: Trove // Deposit native ETH and borrow LUSD Opens a Trove by depositing ETH and borrowing LUSD depositAmount The amount of ETH to deposit maxFeePercentage The maximum borrow fee that this transaction should permitborrowAmount The amount of LUSD to borrow upperHint Address of the Trove near the upper bound of where the user's Trove should now sit in the ordered Trove list lowerHint Address of the Trove near the lower bound of where the user's Trove should now sit in the ordered Trove list getIds Optional (default: 0) Optional storage slot to get deposit & borrow amounts stored using
function open( uint depositAmount, uint maxFeePercentage, uint borrowAmount, address upperHint, address lowerHint, uint[] memory getIds, uint[] memory setIds ) external payable returns (string memory _eventName, bytes memory _eventParam) {
function open( uint depositAmount, uint maxFeePercentage, uint borrowAmount, address upperHint, address lowerHint, uint[] memory getIds, uint[] memory setIds ) external payable returns (string memory _eventName, bytes memory _eventParam) {
34,035
214
// Get an address for a name. /
function getAddress(string memory name) external view returns (address);
function getAddress(string memory name) external view returns (address);
40,506
50
// compute actual token amount and actual pool
if (_poolType == 6 && ((_encoding >> 169) & 1) == 1) { address _token = ICurveYPoolDeposit(_pool).coins(int128(_indexIn)); address _underlying = ICurveYPoolDeposit(_pool).underlying_coins(int128(_indexIn)); if (_token != _underlying) { assembly {
if (_poolType == 6 && ((_encoding >> 169) & 1) == 1) { address _token = ICurveYPoolDeposit(_pool).coins(int128(_indexIn)); address _underlying = ICurveYPoolDeposit(_pool).underlying_coins(int128(_indexIn)); if (_token != _underlying) { assembly {
26,339
12
// Emitted when the address of the treasury account is set treasuryAddress The address of the treasury account /
event SetTreasuryAddress(address indexed treasuryAddress);
event SetTreasuryAddress(address indexed treasuryAddress);
29,988
5
// only allow the owner to authorize more accounts /
function authorize(address account, bool value) external override onlyOwner { _authorize(account, value); }
function authorize(address account, bool value) external override onlyOwner { _authorize(account, value); }
3,710
33
// If total duration of Vesting already crossed, return pending tokens to claimed
if (totalMonthsElapsed > vestData.vestingDuration) { uint256 _totalTokensClaimed = totalTokensClaimed(_userAddresses, _vestingIndex); actualClaimableAmount = vestData.totalTokensAllocated.sub( _totalTokensClaimed );
if (totalMonthsElapsed > vestData.vestingDuration) { uint256 _totalTokensClaimed = totalTokensClaimed(_userAddresses, _vestingIndex); actualClaimableAmount = vestData.totalTokensAllocated.sub( _totalTokensClaimed );
77,649
146
// Yearn Base Strategy yearn.finance BaseStrategy implements all of the required functionality to interoperate closely with the Vault contract. This contract should be inherited and the abstract methods implemented to adapt the Strategy to the particular needs it has to create a return.Of special interest is the relationship between `harvest()` and `vault.report()'. `harvest()` may be called simply because enough time has elapsed since the last report, and not because any funds need to be moved or positions adjusted. This is critical so that the Vault may maintain an accurate picture of the Strategy's performance. See`vault.report()`, `harvest()`, and `harvestTrigger()` for further details.
abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want 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 virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } }
abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want 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 virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } }
8,015
2
// Fonction permettant de calculer le montant obtenu en sortie du swap pour une position donnee. /
function getAmountOut(
function getAmountOut(
11,261
135
// Internal method that preforms a buy on 0x/on-chain/Useful for other DFS contract to integrate for exchanging/exData Exchange data struct/ return (address, uint) Address of the wrapper used and srcAmount
function _buy(ExchangeData memory exData) internal returns (address, uint256) { require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING); uint256 amountWithoutFee = exData.srcAmount; address wrapper = exData.offchainData.wrapper; bool offChainSwapSuccess; uint256 destBalanceBefore = exData.destAddr.getBalance(address(this)); // Takes DFS exchange fee exData.srcAmount = sub(exData.srcAmount, getFee( exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider )); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (offChainSwapSuccess, ) = offChainSwap(exData, ExchangeActionType.BUY); } // fallback to desired wrapper if 0x failed if (!offChainSwapSuccess) { onChainSwap(exData, ExchangeActionType.BUY); wrapper = exData.wrapper; } uint256 destBalanceAfter = exData.destAddr.getBalance(address(this)); uint256 amountBought = sub(destBalanceAfter, destBalanceBefore); // check slippage require(amountBought >= exData.destAmount, ERR_SLIPPAGE_HIT); // revert back exData changes to keep it consistent exData.srcAmount = amountWithoutFee; return (wrapper, amountBought); }
function _buy(ExchangeData memory exData) internal returns (address, uint256) { require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING); uint256 amountWithoutFee = exData.srcAmount; address wrapper = exData.offchainData.wrapper; bool offChainSwapSuccess; uint256 destBalanceBefore = exData.destAddr.getBalance(address(this)); // Takes DFS exchange fee exData.srcAmount = sub(exData.srcAmount, getFee( exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider )); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (offChainSwapSuccess, ) = offChainSwap(exData, ExchangeActionType.BUY); } // fallback to desired wrapper if 0x failed if (!offChainSwapSuccess) { onChainSwap(exData, ExchangeActionType.BUY); wrapper = exData.wrapper; } uint256 destBalanceAfter = exData.destAddr.getBalance(address(this)); uint256 amountBought = sub(destBalanceAfter, destBalanceBefore); // check slippage require(amountBought >= exData.destAmount, ERR_SLIPPAGE_HIT); // revert back exData changes to keep it consistent exData.srcAmount = amountWithoutFee; return (wrapper, amountBought); }
68,287
158
// Wrapper around a call to the ERC20 function `transferFrom` that/ reverts also when the token returns `false`.
function safeTransferFrom( IERC20 token, address from, address to, uint256 value
function safeTransferFrom( IERC20 token, address from, address to, uint256 value
35,601
18
// Using an explicit getter allows for function overloading
function totalSupply() public constant returns (uint)
function totalSupply() public constant returns (uint)
45,250
107
// treasury address
address public treasuryAddress; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor() public
address public treasuryAddress; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor() public
19,068
24
// A temporary reserve variable used for calculating the reward the holder gets for buying tokens. (Yes, the buyer receives a part of the distribution as well!)
var res = reserve() - balance;
var res = reserve() - balance;
44,603
18
// 30 - 39 -> glow 10%
if (((100 - index) > 60) && ((100 - index) <= 70)) { return "glow"; }
if (((100 - index) > 60) && ((100 - index) <= 70)) { return "glow"; }
27,702
25
// invest only when ico is running
icoState = getCurrentState(); require(icoState == State.running); require(msg.value >= minInvestment && msg.value <= maxInvestment); uint tokens = msg.value / tokenPrice;
icoState = getCurrentState(); require(icoState == State.running); require(msg.value >= minInvestment && msg.value <= maxInvestment); uint tokens = msg.value / tokenPrice;
31,356
80
// price for 1 token in Wei
uint public price;
uint public price;
22,344