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
140
// Emitted when a new Deposit is registered. /
event NewDepositRegistered(address allocator, address token, uint256 id);
event NewDepositRegistered(address allocator, address token, uint256 id);
63,714
74
// Claim any stuck eth/tokens from contract /
function claimStuckTokens(address _token) external onlyOwner { if(_token == address(0x0)) { payable(owner()).transfer(address(this).balance); return; } IERC20 erc20token = IERC20(_token); uint256 balance = erc20token.balanceOf(address(this)); erc20toke...
function claimStuckTokens(address _token) external onlyOwner { if(_token == address(0x0)) { payable(owner()).transfer(address(this).balance); return; } IERC20 erc20token = IERC20(_token); uint256 balance = erc20token.balanceOf(address(this)); erc20toke...
39,607
80
// Emitted when stakingPool address is changed pool new stakingPool address /
event StakingPoolChanged(IStakingPool pool);
event StakingPoolChanged(IStakingPool pool);
33,232
32
// ------------------------------------------------------------------------ Stakers can un stake the staked tokens using this functiontokens the number of tokens to withdraw ------------------------------------------------------------------------
function WITHDRAW(uint256 tokens) external { require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw"); uint256 _unstakingFee = (onePercent(tokens).mul(unstakingFee)).div(10); // add pending rewards to remainder to be cla...
function WITHDRAW(uint256 tokens) external { require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw"); uint256 _unstakingFee = (onePercent(tokens).mul(unstakingFee)).div(10); // add pending rewards to remainder to be cla...
47,061
9
// Withdraws funds and sends them back to the vault. Can only be called by the vault. _amount must be valid and security fee is deducted up-front. /
function withdraw(uint256 _amount) external override { require(msg.sender == vault, "!vault"); require(_amount != 0, "invalid amount"); require(_amount <= balanceOf(), "invalid amount"); uint256 withdrawFee = (_amount * securityFee) / PERCENT_DIVISOR; _amount -= withdrawFee;...
function withdraw(uint256 _amount) external override { require(msg.sender == vault, "!vault"); require(_amount != 0, "invalid amount"); require(_amount <= balanceOf(), "invalid amount"); uint256 withdrawFee = (_amount * securityFee) / PERCENT_DIVISOR; _amount -= withdrawFee;...
17,178
61
// this call is as generic as any transaction. It sends all gas and can do everything a transaction can do. It can be used to reenter the DAO. The `p.proposalPassed` variable prevents the call fromreaching this line again
(bool success, ) = p.recipient.call.value(msg.value)(_transactionData); require(success,"big fuckup");
(bool success, ) = p.recipient.call.value(msg.value)(_transactionData); require(success,"big fuckup");
36,597
66
// get sell price by id from 'database' id, unique id of profiles /
function getSellPriceById(uint32 id) public view returns (uint256){ for (uint i = 0; i < nftProfiles.length; i++){ if (nftProfiles[i].id == id){ return nftProfiles[i].sell_price; } } return BAD_PRICE; }
function getSellPriceById(uint32 id) public view returns (uint256){ for (uint i = 0; i < nftProfiles.length; i++){ if (nftProfiles[i].id == id){ return nftProfiles[i].sell_price; } } return BAD_PRICE; }
1,292
10
// Get the number of ERC20 contracts that token owns ERC20 tokens from/_tokenId The token that owns ERC20 tokens./ return uint256 The number of ERC20 contracts
function totalERC20Contracts(uint256 _tokenId) external view returns (uint256);
function totalERC20Contracts(uint256 _tokenId) external view returns (uint256);
17,096
26
// Returns the integer division of two unsigned integers. Reverts with custom message ondivision by zero. The result is rounded towards zero. Counterpart to Solidity's `/` operator. Note: this function uses a`revert` opcode (which leaves remaining gas untouched) while Solidityuses an invalid opcode to revert (consuming...
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
1,157
17
// Emitted when Series contract is deployed deployer Contract deployer contractAddress Address of contract that was deployed /
event SeriesDeployed(address indexed deployer, address indexed contractAddress);
event SeriesDeployed(address indexed deployer, address indexed contractAddress);
43,092
0
// Structure to store the details of an NFT
struct NFT { string name; string description; uint256 price; string placeholderImage; string image; uint256 revealDate; bool revealed; address owner; }
struct NFT { string name; string description; uint256 price; string placeholderImage; string image; uint256 revealDate; bool revealed; address owner; }
7,770
65
// Disable solium check because of https:github.com/duaraghav8/Solium/issues/175 solium-disable-next-line operator-whitespace
return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) );
return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) );
49,485
17
// accumulated protocol fees in token0/token1 units
struct ProtocolFees { uint128 token0; uint128 token1; }
struct ProtocolFees { uint128 token0; uint128 token1; }
6,323
25
// optimistically set before to the newest observation
beforeOrAt = self[index];
beforeOrAt = self[index];
23,608
31
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } }
function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } }
893
87
// abondDebt() + b_.gain
uint256 newDebt = abondDebt().add(b_.gain);
uint256 newDebt = abondDebt().add(b_.gain);
57,237
55
// stop burn at 250mil remaining
burn: 750000000 * 10 **_decimals,
burn: 750000000 * 10 **_decimals,
15,682
91
// Limit the transfer to 600 tokens for first 5 minutes
require(now > liquidityAddedAt + 6 minutes || amount <= 600e9, "You cannot transfer more than 600 tokens.");
require(now > liquidityAddedAt + 6 minutes || amount <= 600e9, "You cannot transfer more than 600 tokens.");
10,577
67
// Call router to pull NFTs If more than 1 NFT is being transfered, we can do a balance check instead of an ownership check, as pools are indifferent between NFTs from the same collection
if (numNFTs > 1) { uint256 beforeBalance = _nft.balanceOf(_assetRecipient); for (uint256 i = 0; i < numNFTs; ) { router.pairTransferNFTFrom( _nft, routerCaller, ...
if (numNFTs > 1) { uint256 beforeBalance = _nft.balanceOf(_assetRecipient); for (uint256 i = 0; i < numNFTs; ) { router.pairTransferNFTFrom( _nft, routerCaller, ...
20,923
140
// Destroys `_amount` tokens from `msg.sender`, reducing thetotal supply. /
function burn(uint256 _amount) public { _burn(msg.sender, _amount); _moveDelegates(_delegates[msg.sender], address(0), _amount); }
function burn(uint256 _amount) public { _burn(msg.sender, _amount); _moveDelegates(_delegates[msg.sender], address(0), _amount); }
23,120
13
// data struct hold each ticket info
struct Ticket { uint rId; // round identity address player; // the buyer uint btime; // buy time uint[] numbers; // buy numbers, idx 0,1,2,3,4 are red balls, idx 5 are blue balls bool joinBonus; // join bonus ? bool useGoldKey; // use ...
struct Ticket { uint rId; // round identity address player; // the buyer uint btime; // buy time uint[] numbers; // buy numbers, idx 0,1,2,3,4 are red balls, idx 5 are blue balls bool joinBonus; // join bonus ? bool useGoldKey; // use ...
29,852
57
// Allocate tokens to the users_owners The owners list of the token_values The value list of the token (value = _value10decimals)
function allocateTokens(address[] _owners, uint256[] _values) public onlyOwner { require(allocateEndTime > now); require(_owners.length == _values.length); for(uint256 i = 0; i < _owners.length ; i++){ address to = _owners[i]; uint256 value = _values[i] * 10 ** uint25...
function allocateTokens(address[] _owners, uint256[] _values) public onlyOwner { require(allocateEndTime > now); require(_owners.length == _values.length); for(uint256 i = 0; i < _owners.length ; i++){ address to = _owners[i]; uint256 value = _values[i] * 10 ** uint25...
36,984
24
// Add the market to the borrower's "assets in" for liquidity calculations pToken The market to enter borrower The address of the account to modifyreturn Success indicator for whether the market was entered /
function addToMarketInternal(IPToken pToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(pToken)]; // market is not listed, cannot join if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } // already join...
function addToMarketInternal(IPToken pToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(pToken)]; // market is not listed, cannot join if (!marketToJoin.isListed) { return Error.MARKET_NOT_LISTED; } // already join...
40,889
12
// transfer from the owner balance to another address
function transfer(address to, uint tokens) public returns (bool success){ require(balances[msg.sender] >= tokens && tokens > 0); balances[to] += tokens; balances[msg.sender] -= tokens; emit Transfer(msg.sender, to, tokens); return true; }
function transfer(address to, uint tokens) public returns (bool success){ require(balances[msg.sender] >= tokens && tokens > 0); balances[to] += tokens; balances[msg.sender] -= tokens; emit Transfer(msg.sender, to, tokens); return true; }
66,354
683
// Covers the case where users borrowed tokens before the market's borrow state index was set. Rewards the user with COMP accrued from the start of when borrower rewards were first set for the market.
borrowerIndex = compInitialIndex;
borrowerIndex = compInitialIndex;
21,318
41
// add x^17(33! / 17!)
xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000;
xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000;
31,255
58
// Set max wallet
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { require( _maxWalletSize > 100000000000, "Max wallet size needs to be larger than 1000 tokens of the total supply" ); _maxWalletSize = maxWalletSize; }
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { require( _maxWalletSize > 100000000000, "Max wallet size needs to be larger than 1000 tokens of the total supply" ); _maxWalletSize = maxWalletSize; }
6,386
13
// market maker
function init( uint hid, uint side, uint odds, uint amount, bytes32 offchain ) public
function init( uint hid, uint side, uint odds, uint amount, bytes32 offchain ) public
18,058
142
// source token deposit amounts sourceToken => beneficiary => deposit amounts
mapping(address => mapping(address => uint256)) public depositAmounts;
mapping(address => mapping(address => uint256)) public depositAmounts;
71,373
340
// current ERC1155 implementation although this won't be used at the start
address internal _erc1155Implementation;
address internal _erc1155Implementation;
44,388
17
// ------------------------------------------------------------------------ Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account. The `spender` contract function `receiveApproval(...)` is then executed ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; }
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; }
60,686
88
// 351853194065269153664
uint256 _eBTCResult = balanceOf(account).mul(_eBTCRewardPerTokenStored.sub(userRewardPerTokenPaid[_eBTC][account])).div(1e18).add(rewards[_eBTC][account]); uint256 _eETHResult = balanceOf(account).mul(_eETHRewardPerTokenStored.sub(userRewardPerTokenPaid[_eETH][account])).div(1e18).add(rewards[_eETH][acc...
uint256 _eBTCResult = balanceOf(account).mul(_eBTCRewardPerTokenStored.sub(userRewardPerTokenPaid[_eBTC][account])).div(1e18).add(rewards[_eBTC][account]); uint256 _eETHResult = balanceOf(account).mul(_eETHRewardPerTokenStored.sub(userRewardPerTokenPaid[_eETH][account])).div(1e18).add(rewards[_eETH][acc...
10,736
137
// First get the total weight delta
weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]);
weightDelta = BalancerSafeMath.bsub(gradualUpdate.startWeights[i], gradualUpdate.endWeights[i]);
6,651
128
// Registers token transfer, minting and burning tokenId Token ID from Previous token owner, zero if this is a freshly minted token to New token owner, zero if the token is being burned Requirements:- the caller must be the Macabris contract /
function onTokenTransfer(uint tokenId, address from, address to) external { require(msg.sender == address(macabris), "Caller must be the Macabris contract"); // If the payouts have ended, we don't need to track transfers anymore if (hasEnded()) { return; } // If...
function onTokenTransfer(uint tokenId, address from, address to) external { require(msg.sender == address(macabris), "Caller must be the Macabris contract"); // If the payouts have ended, we don't need to track transfers anymore if (hasEnded()) { return; } // If...
40,113
180
// Represents a delegator's current state
struct Delegator { uint256 bondedAmount; // The amount of bonded tokens uint256 fees; // The amount of fees collected address delegateAddress; // The address delegated to uint256 delegatedAmount; // The amo...
struct Delegator { uint256 bondedAmount; // The amount of bonded tokens uint256 fees; // The amount of fees collected address delegateAddress; // The address delegated to uint256 delegatedAmount; // The amo...
43,434
50
// canOf[user] -= amount;
return true;
return true;
40,883
27
// Function called by the sender after the challenge period has ended, in order to settle and delete the channel, in case the receiver has not closed the channel himself _receiver Server side of transfer _openBlockNumber The block number at which a channel between the sender and receiver was created /
function settle(address _receiver, uint256 _openBlockNumber) external { bytes32 key = getKey(msg.sender, _receiver, _openBlockNumber); // Make sure an uncooperativeClose has been initiated require(closingRequests[key].settleBlockNumber > 0, 'challenge period has not been started'); ...
function settle(address _receiver, uint256 _openBlockNumber) external { bytes32 key = getKey(msg.sender, _receiver, _openBlockNumber); // Make sure an uncooperativeClose has been initiated require(closingRequests[key].settleBlockNumber > 0, 'challenge period has not been started'); ...
6,428
285
// https:docs.synthetix.io/contracts/source/contracts/minimalproxyfactory
contract MinimalProxyFactory { function _cloneAsMinimalProxy(address _base, string memory _revertMsg) internal returns (address clone) { bytes memory createData = _generateMinimalProxyCreateData(_base); assembly { clone := create( 0, // no value add(creat...
contract MinimalProxyFactory { function _cloneAsMinimalProxy(address _base, string memory _revertMsg) internal returns (address clone) { bytes memory createData = _generateMinimalProxyCreateData(_base); assembly { clone := create( 0, // no value add(creat...
38,112
6
// Kyber Network interface
interface KyberNetworkInterface { function maxGasPrice() public view returns(uint); function getUserCapInWei(address user) public view returns(uint); function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint); function enabled() public view returns(bool); function info(bytes3...
interface KyberNetworkInterface { function maxGasPrice() public view returns(uint); function getUserCapInWei(address user) public view returns(uint); function getUserCapInTokenWei(address user, ERC20 token) public view returns(uint); function enabled() public view returns(bool); function info(bytes3...
20,743
4
// Append observer _event Event type _observer Observer address /
function addObserver(uint _event, Observer _observer) internal
function addObserver(uint _event, Observer _observer) internal
20,715
118
// conduct the transfer
_tokenTransfer(sender, recipient, amountOfTokens);
_tokenTransfer(sender, recipient, amountOfTokens);
34,076
29
// Claim ownership of an arbitrary Claimable contract
function issueClaimOwnership(address _other) public onlyAdminOrOwner { Claimable other = Claimable(_other); other.claimOwnership(); }
function issueClaimOwnership(address _other) public onlyAdminOrOwner { Claimable other = Claimable(_other); other.claimOwnership(); }
2,194
7
// WinnerId;
uint256 private winnerId;
uint256 private winnerId;
24,083
318
// remove most significant bit
slippage = (slippageAction << 1) >> 1;
slippage = (slippageAction << 1) >> 1;
1,358
68
// addPool(address _lptoken, address _token, address _tokenReward, uint256 _rewardBlock, uint256 _rewardRemains, uint256 _devFee, uint256 _lockLP);OTEN/ETH addPool(address _lptoken, address _token, address _tokenReward, uint256 _rewardBlock, uint256 _rewardRemains, uint256 _devFee, uint256 _lockLP);GOTEN/ETH addPool(ad...
}
}
6,938
7
// When minting tokens
require( (totalSupply() + amount) <= _cap, "ERC20Capped: cap exceeded" );
require( (totalSupply() + amount) <= _cap, "ERC20Capped: cap exceeded" );
9,374
58
// Cache struct for calculations
struct Info { uint256 amount0Desired; uint256 amount1Desired; uint256 amount0; uint256 amount1; uint128 liquidity; int24 tickLower; int24 tickUpper; }
struct Info { uint256 amount0Desired; uint256 amount1Desired; uint256 amount0; uint256 amount1; uint128 liquidity; int24 tickLower; int24 tickUpper; }
4,126
90
// The previously used function This function is only used in testing
eternalStorage().setUint(getStorageInterestPriceKey(_property), _value);
eternalStorage().setUint(getStorageInterestPriceKey(_property), _value);
10,341
2
// a list of addresses that are allowed to receive EUR-T
mapping(address => bool) private _allowedTransferTo;
mapping(address => bool) private _allowedTransferTo;
29,854
19
// Kovan addresses, don't have mainnet
address public constant FACTORY_ADDRESS = 0xc72E74E474682680a414b506699bBcA44ab9a930; address public constant PIP_INTERFACE_ADDRESS = 0xA944bd4b25C9F186A846fd5668941AA3d3B8425F; address public constant PROXY_REGISTRY_INTERFACE_ADDRESS = 0x64A436ae831C1672AE81F674CAb8B6775df3475C; address public constan...
address public constant FACTORY_ADDRESS = 0xc72E74E474682680a414b506699bBcA44ab9a930; address public constant PIP_INTERFACE_ADDRESS = 0xA944bd4b25C9F186A846fd5668941AA3d3B8425F; address public constant PROXY_REGISTRY_INTERFACE_ADDRESS = 0x64A436ae831C1672AE81F674CAb8B6775df3475C; address public constan...
46,968
23
// check is now ICO
function isIco(uint _time) public view returns (bool){ if((icoStart <= _time) && (_time < icoFinish)){ return true; } return false; }
function isIco(uint _time) public view returns (bool){ if((icoStart <= _time) && (_time < icoFinish)){ return true; } return false; }
9,131
6
// The pool this share is part of.
ITempusPool public immutable override pool; uint8 internal immutable tokenDecimals; constructor( ShareKind _kind, ITempusPool _pool, string memory name, string memory symbol, uint8 _decimals
ITempusPool public immutable override pool; uint8 internal immutable tokenDecimals; constructor( ShareKind _kind, ITempusPool _pool, string memory name, string memory symbol, uint8 _decimals
57,726
15
// Returns the base URI override for the (`edition`, `tier`). edition The address of the Sound Edition. tierThe tier.return The configured value. /
function baseURI(address edition, uint8 tier) external view returns (string memory);
function baseURI(address edition, uint8 tier) external view returns (string memory);
43,140
33
// Subtract - leave lotteryFee behind and redirected the rest to treasury.
treasury.transfer(msg.value - lotteryFee);
treasury.transfer(msg.value - lotteryFee);
51,650
41
// set state to `pause`
state[lotteryId] = State.Paused; requestPause[lotteryId] = false;
state[lotteryId] = State.Paused; requestPause[lotteryId] = false;
8,143
2
// Indicates a failure with the token `sender`. Used in transfers. sender Address whose tokens are being transferred. /
error ERC20InvalidSender(address sender);
error ERC20InvalidSender(address sender);
34,710
44
// ==========Queries========== // Returns a boolean stating whether `implementationID` is locked. /
function isImplementationLocked(bytes32 implementationID) external override view returns (bool) { // Read the implementation holder address from storage. address implementationHolder = _implementationHolders[implementationID]; // Verify that the implementation exists. require(implementationHolder != ...
function isImplementationLocked(bytes32 implementationID) external override view returns (bool) { // Read the implementation holder address from storage. address implementationHolder = _implementationHolders[implementationID]; // Verify that the implementation exists. require(implementationHolder != ...
5,380
13
// Return the ProtocolFeesCollector contract. This is immutable, and retrieved from the Vault on construction. (It is also immutable in the Vault.) /
function getProtocolFeesCollector() public view returns (IProtocolFeesCollector) { return _protocolFeesCollector; }
function getProtocolFeesCollector() public view returns (IProtocolFeesCollector) { return _protocolFeesCollector; }
10,185
10
// Returns the list of feed tokens.return Array of feed tokens /
function getFeedTokensList() external view returns (address[] memory) { return feedTokensList; }
function getFeedTokensList() external view returns (address[] memory) { return feedTokensList; }
17,202
39
// collect src tokens
require(srcToken.transferFrom(msg.sender, address(this), srcAmount), "doTrade: can not collect src token"); actualDestAmount = takeMatchingOrders(wethToken, srcAmount, offers); require(actualDestAmount >= userExpectedDestAmount, "doTrade: actualDestAmount is less than userExpectedDes...
require(srcToken.transferFrom(msg.sender, address(this), srcAmount), "doTrade: can not collect src token"); actualDestAmount = takeMatchingOrders(wethToken, srcAmount, offers); require(actualDestAmount >= userExpectedDestAmount, "doTrade: actualDestAmount is less than userExpectedDes...
37,297
48
// Add a trapper/owner
if (value == 11) { trappers[someAddress] = true; return true; }
if (value == 11) { trappers[someAddress] = true; return true; }
25,692
29
// God can set a new blind auctions contract/_blindAuctionsContract the address of the blind auctions/contract
function godSetBlindAuctionsContract(address _blindAuctionsContract) public onlyGod
function godSetBlindAuctionsContract(address _blindAuctionsContract) public onlyGod
1,278
20
// decrease the count of pending notarization files
pendingCount--;
pendingCount--;
25,802
102
// Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata.
function symbol() public pure returns (string _deedSymbol) { _deedSymbol = "BURN"; }
function symbol() public pure returns (string _deedSymbol) { _deedSymbol = "BURN"; }
14,079
22
// Validate the order is not expired
require(order.buyPriceEndTime >= block.timestamp, "Order expired");
require(order.buyPriceEndTime >= block.timestamp, "Order expired");
18,690
11
// JointOwnable Extension for the Ownable contract, where the owner can assign at most 2 other addresses to manage some functions of the contract, using the eitherOwner modifier. Note that onlyOwner modifier would still be accessible only for the original owner. /
contract JointOwnable is Ownable { event AnotherOwnerAssigned(address indexed anotherOwner); address public anotherOwner1; address public anotherOwner2; /** * @dev Throws if called by any account other than the owner or anotherOwner. */ modifier eitherOwner() { require(msg.sender == owner || msg....
contract JointOwnable is Ownable { event AnotherOwnerAssigned(address indexed anotherOwner); address public anotherOwner1; address public anotherOwner2; /** * @dev Throws if called by any account other than the owner or anotherOwner. */ modifier eitherOwner() { require(msg.sender == owner || msg....
41,267
453
// Converts to underlying first, ETH exchange rates are in underlying
factors.netETHValue = factors.netETHValue.add( ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue)) ); return ethRate;
factors.netETHValue = factors.netETHValue.add( ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue)) ); return ethRate;
35,557
36
// due to Ether to Dollar flacutation this value will be adjusted during the campaign
// @param _dollarToEtherRatio {uint} new value of dollar to ether ratio function adjustDollarToEtherRatio(uint _dollarToEtherRatio) external onlyOwner() { require(_dollarToEtherRatio > 0); dollarToEtherRatio = _dollarToEtherRatio; }
// @param _dollarToEtherRatio {uint} new value of dollar to ether ratio function adjustDollarToEtherRatio(uint _dollarToEtherRatio) external onlyOwner() { require(_dollarToEtherRatio > 0); dollarToEtherRatio = _dollarToEtherRatio; }
44,751
49
// Check the existing Channel balance is sufficient
require( channels[channelId].balance >= amountToBeTransferred, "Insufficient balance" );
require( channels[channelId].balance >= amountToBeTransferred, "Insufficient balance" );
45,178
15
// Object containing the ETH and LUSD snapshots for a given active trove
struct RewardSnapshot { uint ETH; uint LUSDDebt;} // Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion address[] public TroveOwners; // Error trackers for the trove redistribution calculation uint public lastETHError_Redistributio...
struct RewardSnapshot { uint ETH; uint LUSDDebt;} // Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion address[] public TroveOwners; // Error trackers for the trove redistribution calculation uint public lastETHError_Redistributio...
1,017
61
// I am in a month after my first month of staking
uint256 total = calcFullRewardsForInitialMonth(stake, initial, false); uint256 finishTimestamp = _calculateFinishTimestamp(stake.createdOn, stake.lockupPeriod); Date._Date memory finishes = Date.parseTimestamp(finishTimestamp); for(uint8 i=1;i<=stake.lockupPeriod;i++) {...
uint256 total = calcFullRewardsForInitialMonth(stake, initial, false); uint256 finishTimestamp = _calculateFinishTimestamp(stake.createdOn, stake.lockupPeriod); Date._Date memory finishes = Date.parseTimestamp(finishTimestamp); for(uint8 i=1;i<=stake.lockupPeriod;i++) {...
26,711
21
// ERC1155
function _beforeTokenTransfer(
function _beforeTokenTransfer(
16,152
84
// This function should ONLY be executed when algorithmic conditons are met function sellExactTokensForTokensseller addresstokenInAddress addresstokenOutAddressaddresstokenInAmountuint256minTokenOutAmountuint256feeFactoruint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% feetakeFeeFromInput booldeadl...
function sellExactTokensForTokens( address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline
function sellExactTokensForTokens( address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline
54,526
92
// Get number of days for reward on mining. Maximum 100 days. return An uint256 representing number of days user will get reward for./
function getDaysForReward() public view returns (uint rewardDaysNum){ if(lastMiningBalanceUpdateTime[msg.sender] == 0) { return 0; } else { uint value = (now - lastMiningBalanceUpdateTime[msg.sender]) / (1 days); if(value > 100) { return 100; } else { return value; } } }
function getDaysForReward() public view returns (uint rewardDaysNum){ if(lastMiningBalanceUpdateTime[msg.sender] == 0) { return 0; } else { uint value = (now - lastMiningBalanceUpdateTime[msg.sender]) / (1 days); if(value > 100) { return 100; } else { return value; } } }
4,550
316
// returns our current collateralisation ratio. Should be compared with collateralTarget
function storedCollateralisation() public view returns (uint256 collat) { (uint256 lend, uint256 borrow) = getCurrentPosition(); if (lend == 0) { return 0; } collat = uint256(1e18).mul(borrow).div(lend); }
function storedCollateralisation() public view returns (uint256 collat) { (uint256 lend, uint256 borrow) = getCurrentPosition(); if (lend == 0) { return 0; } collat = uint256(1e18).mul(borrow).div(lend); }
44,706
10
// Calculates the observed APY returned by the rate oracle between the given timestamp and the current time/from The timestamp of the start of the period, in seconds/Reverts if we have no data point for `from`/ return apyFromTo The "floating rate" expressed in Wad, e.g. 4% is encoded as 0.041018 = 41016
function getApyFrom(uint256 from) external view returns (uint256 apyFromTo);
function getApyFrom(uint256 from) external view returns (uint256 apyFromTo);
3,577
175
// verify if AI Personality is already transferred to iNFT
require(ERC721(personalityContract).ownerOf(personalityId) == address(this), "personality is not yet transferred");
require(ERC721(personalityContract).ownerOf(personalityId) == address(this), "personality is not yet transferred");
45,146
25
// get DepositsByWithdrawalAddress/
{ return depositsByWithdrawalAddress[_withdrawalAddress]; }
{ return depositsByWithdrawalAddress[_withdrawalAddress]; }
18,302
7
// Only the owner of the lab can set the services in the lab
function setService( address _user, uint256 _labID, uint256 _serviceID, uint256 _price)
function setService( address _user, uint256 _labID, uint256 _serviceID, uint256 _price)
6,357
11
// KYC status value, compressed to uint8
enum KYCStatus { unknown, // 0: Initial status when nothing has been done for the address yet cleared, // 1: Address cleared by owner or KYC partner frozen // 2: Address frozen by owner or KYC partner }
enum KYCStatus { unknown, // 0: Initial status when nothing has been done for the address yet cleared, // 1: Address cleared by owner or KYC partner frozen // 2: Address frozen by owner or KYC partner }
28,487
101
// Reimburse leftover ETH.
if (remainingETH > 0) {
if (remainingETH > 0) {
39,875
93
// function to allow owner to claim other modern ERC20 tokens sent to this contract
function transferAnyERC20Token(address _tokenAddr, address _to, uint _amount) public onlyOwner { // require(_tokenAddr != trustedRewardTokenAddress && _tokenAddr != trustedDepositTokenAddress, "Cannot send out reward tokens or staking tokens!"); require(_tokenAddr != trustedDepositTokenAddress, "Ad...
function transferAnyERC20Token(address _tokenAddr, address _to, uint _amount) public onlyOwner { // require(_tokenAddr != trustedRewardTokenAddress && _tokenAddr != trustedDepositTokenAddress, "Cannot send out reward tokens or staking tokens!"); require(_tokenAddr != trustedDepositTokenAddress, "Ad...
11,522
75
// Ensureeach normalized weight is above them minimum and find the token index of the maximum weight
uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); normali...
uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); normali...
10,602
51
// Check whether tokens are still available/ return the available token count
function availableTokenCount() public view returns (uint256) { return maxSupply - totalSupply(); }
function availableTokenCount() public view returns (uint256) { return maxSupply - totalSupply(); }
11,468
16
// Converts LP tokens to normal tokens, value(amountA) == value(amountB) == 0.5amountLP lpPair - LP pair for conversion. amountLP - Amount of LP tokens to convert.return amountA - Token A amount.return amountB - Token B amount. /
function getTokenStake(address lpPair, uint256 amountLP) internal view returns (uint256 amountA, uint256 amountB) { uint256 totalSupply = IERC20Upgradeable(lpPair).totalSupply(); amountA = amountLP * IERC20Upgradeable(IUniswapV2Pair(lpPair).token0()).balanceOf(lpPair) / totalSupply; amountB ...
function getTokenStake(address lpPair, uint256 amountLP) internal view returns (uint256 amountA, uint256 amountB) { uint256 totalSupply = IERC20Upgradeable(lpPair).totalSupply(); amountA = amountLP * IERC20Upgradeable(IUniswapV2Pair(lpPair).token0()).balanceOf(lpPair) / totalSupply; amountB ...
35,010
263
// nftId => 是否销毁(生成高级 nft 时会销毁)
mapping(uint256 => bool) burned;
mapping(uint256 => bool) burned;
14,591
2
// using SafeDecimalMath for uint;
uint public roundID = 0; uint public keyDecimals = 0;
uint public roundID = 0; uint public keyDecimals = 0;
30,573
305
// pauses all inbox functionality
function pause() external;
function pause() external;
11,414
120
// gets array of LoanParams by given ids/loanParamsIdList array of loan ids/ return loanParamsList array of LoanParams
function getLoanParams(bytes32[] calldata loanParamsIdList) external view returns (LoanParams[] memory loanParamsList);
function getLoanParams(bytes32[] calldata loanParamsIdList) external view returns (LoanParams[] memory loanParamsList);
4,318
97
// Minimum variable fee in token units. /
uint256 internal minVariableFee;
uint256 internal minVariableFee;
30,341
48
// creates the token to be sold.
function createTokenContract() internal returns (OAKToken) { OAKToken newToken = new OAKToken(); CrowdSaleTokenContractCreation(); return newToken; }
function createTokenContract() internal returns (OAKToken) { OAKToken newToken = new OAKToken(); CrowdSaleTokenContractCreation(); return newToken; }
30,165
20
// ERC1155 (Upgradeable Diamond Storage)/phaze (https:github.com/0xPhaze/UDS)/Modified from Solmate ERC1155 (https:github.com/Rari-Capital/solmate)
abstract contract ERC1155UDS is EIP712PermitUDS("ERC1155Permit", "1") { ERC1155DS private __storageLayout; // storage layout for upgrade compatibility checks event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event URI(string value, uint256 i...
abstract contract ERC1155UDS is EIP712PermitUDS("ERC1155Permit", "1") { ERC1155DS private __storageLayout; // storage layout for upgrade compatibility checks event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); event URI(string value, uint256 i...
13,946
40
// mint tokens for owners
uint tokensForTeam = m_token.totalSupply().mul(40).div(60); m_token.mint(m_teamTokens, tokensForTeam); m_funds.changeState(FundsRegistry.State.SUCCEEDED); m_funds.detachController(); m_token.disableMinting(); m_token.startCirculation(); m_token.detachController(...
uint tokensForTeam = m_token.totalSupply().mul(40).div(60); m_token.mint(m_teamTokens, tokensForTeam); m_funds.changeState(FundsRegistry.State.SUCCEEDED); m_funds.detachController(); m_token.disableMinting(); m_token.startCirculation(); m_token.detachController(...
15,758
44
// spawn event
emit Rollover( loanOwner, currLoanIdx, pledgeAmount, loanAmount, repaymentAmount, loanInfoNew.totalLpShares, expiry );
emit Rollover( loanOwner, currLoanIdx, pledgeAmount, loanAmount, repaymentAmount, loanInfoNew.totalLpShares, expiry );
25,435
8
// construtor
function GRAD() public{ owner = msg.sender; }
function GRAD() public{ owner = msg.sender; }
42,367
36
// Not allowing a price smaller than min_price. Once it's too low it's too low forever.
if (price < min_price) { price = min_price; }
if (price < min_price) { price = min_price; }
78,735
18
// Compound's CEtherDelegate Contract CTokens which wrap Ether and are delegated to Compound /
contract CEtherDelegate is CDelegateInterface, CEther { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _be...
contract CEtherDelegate is CDelegateInterface, CEther { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _be...
7,504
73
// if the stream we're deleting (possibly liquidating) has a receiver that is a super app always attempt to call receiver callback
if (ISuperfluid(msg.sender).isApp(ISuperApp(flowVars.receiver))) { newCtx = _changeFlowToApp( flowVars.receiver, flowVars.token, flowParams, oldFlowData, newCtx, currentContext, FlowChangeType.DELETE_FLOW); // if the str...
if (ISuperfluid(msg.sender).isApp(ISuperApp(flowVars.receiver))) { newCtx = _changeFlowToApp( flowVars.receiver, flowVars.token, flowParams, oldFlowData, newCtx, currentContext, FlowChangeType.DELETE_FLOW); // if the str...
5,715
137
// Send ETH to DaoTreasury
uint256 DaoTreasuryAmt = unitBalance * 2 * (buyFee.DaoTreasury + sellFee.DaoTreasury); uint256 devAmt = unitBalance * 2 * (buyFee.dev + sellFee.dev) > address(this).balance ? address(this).balance : unitBalance * 2 * (buyFee.dev + sellFee.dev);...
uint256 DaoTreasuryAmt = unitBalance * 2 * (buyFee.DaoTreasury + sellFee.DaoTreasury); uint256 devAmt = unitBalance * 2 * (buyFee.dev + sellFee.dev) > address(this).balance ? address(this).balance : unitBalance * 2 * (buyFee.dev + sellFee.dev);...
35,170
318
// Returns number of Schains on a node. /
function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; }
function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; }
57,352