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
13
// Removes an Oracle. token The address of the token. oracleAddress The address of the oracle. index The index of `oracleAddress` in the list of oracles. /
function removeOracle( address token, address oracleAddress, uint256 index
function removeOracle( address token, address oracleAddress, uint256 index
26,018
46
// Hook that is called after any transfer of tokens. This includes minting and burning. Calling conditions:- when `from` and `to` are both non-zero, `amount` of ``from``'s tokenshas been transferred to `to`.- when `from` is zero, `amount` tokens have been minted for `to`.- when `to` is zero, `amount` of ``from``'s tokens have been burned.- `from` and `to` are never both zero. /
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} }
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} }
36,846
38
// Check end
checkEnd();
checkEnd();
10,424
29
// Updates crediBond balance
function _deliverCreditBond(address _beneficiary, uint256 _bondAmount) ito_Timelock internal { itoInfo.remaining_itoCreditsSupply = itoInfo.remaining_itoCreditsSupply.sub(_bondAmount); userItoInfo[_beneficiary]._pendingCreditBalance = userItoInfo[_beneficiary]._pendingCreditBalance.add(_bondAmount);
function _deliverCreditBond(address _beneficiary, uint256 _bondAmount) ito_Timelock internal { itoInfo.remaining_itoCreditsSupply = itoInfo.remaining_itoCreditsSupply.sub(_bondAmount); userItoInfo[_beneficiary]._pendingCreditBalance = userItoInfo[_beneficiary]._pendingCreditBalance.add(_bondAmount);
39,977
1,001
// IERC20(_token).safeTransfer(blackhole, _fee);
IERC20(_token).safeTransfer(msg.sender, _amount);
IERC20(_token).safeTransfer(msg.sender, _amount);
35,866
102
// Remove the ask on a piece of media /
function removeAsk(uint256 tokenId) external;
function removeAsk(uint256 tokenId) external;
4,909
1
// Mapping of all talents
struct CyberBrokerTalent { string talent; string species; string class; string description; }
struct CyberBrokerTalent { string talent; string species; string class; string description; }
71,841
179
// Exits `amount` collateral into the system and credits it to `user`/tokenId ERC1155 or ERC721 style TokenId (leave at 0 for ERC20)/user Address to whom the collateral should be credited to/amount Amount of collateral to exit [tokenScale]
function exit( uint256, /* tokenId */ address user, uint256 amount
function exit( uint256, /* tokenId */ address user, uint256 amount
59,181
58
// bucket is not emptywe just need to find our neighbor in the bucket
uint160 cursor = checkPoints[bucket].head;
uint160 cursor = checkPoints[bucket].head;
4,760
98
// write in the exact amount we are selling/buing in an order
if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else {
if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else {
14,329
17
// Set a cutoff timestamp to invalidate all orders whose timestamp/is smaller than or equal to the new value of the address's cutoff/timestamp./cutoff The cutoff timestamp, will default to `block.timestamp`/if it is 0.
function cancelAllOrders( uint cutoff ) external;
function cancelAllOrders( uint cutoff ) external;
42,272
552
// Claimable if collateral ratio below target ratio
if (ratio < targetRatio) { return (true, anyRateIsInvalid); }
if (ratio < targetRatio) { return (true, anyRateIsInvalid); }
34,275
66
// How many token units a buyer gets per wei. The rate is the conversion between wei and the smallest and indivisible token unit. So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
uint256 private _rate;
18,008
70
// _tokenID The ID of the tokenreturnaddress of the owner for this token /
function ownerOf(uint256 _tokenID) external view returns(address);
function ownerOf(uint256 _tokenID) external view returns(address);
41,328
37
// marginUsd = (amountIn - openFee) / token.price
uint marginUsd = (data.amountIn - openFee) * 1e26 / (token.price * (10 ** token.decimals));
uint marginUsd = (data.amountIn - openFee) * 1e26 / (token.price * (10 ** token.decimals));
34,073
51
// called to send tokens to contributors after ICO and lockup period.
// @param _backer {address} address of beneficiary // @return true if successful function claimTokensForUser(address _backer) internal returns(bool) { require(currentStep == Step.Claiming); Backer storage backer = backers[_backer]; require(!backer.refunded); // if refunded, don't allow for another refund require(!backer.claimed); // if tokens claimed, don't allow refunding require(backer.tokensToSend != 0); // only continue if there are any tokens to send claimCount++; claimed[_backer] = backer.tokensToSend; // save claimed tokens backer.claimed = true; totalClaimed += backer.tokensToSend; if (!token.transfer(_backer, backer.tokensToSend)) revert(); // send claimed tokens to contributor account TokensClaimed(_backer, backer.tokensToSend); }
// @param _backer {address} address of beneficiary // @return true if successful function claimTokensForUser(address _backer) internal returns(bool) { require(currentStep == Step.Claiming); Backer storage backer = backers[_backer]; require(!backer.refunded); // if refunded, don't allow for another refund require(!backer.claimed); // if tokens claimed, don't allow refunding require(backer.tokensToSend != 0); // only continue if there are any tokens to send claimCount++; claimed[_backer] = backer.tokensToSend; // save claimed tokens backer.claimed = true; totalClaimed += backer.tokensToSend; if (!token.transfer(_backer, backer.tokensToSend)) revert(); // send claimed tokens to contributor account TokensClaimed(_backer, backer.tokensToSend); }
24,290
107
// Added to support recovering LP Rewards and other mistaken tokens from other systems to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); }
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { // Only the owner address can ever receive the recovery withdrawal TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount); emit RecoveredERC20(tokenAddress, tokenAmount); }
16,329
15
// Create a flow between sender and receiverA flow created by an approved flow operator (see above for details on callbacks)token Super token addresssender Flow sender address (has granted permissions)receiver Flow receiver addressflowRate New flow rate in amount per secondctx Context bytes (see ISuperfluid.sol for Context struct)/
function createFlowByOperator(
function createFlowByOperator(
13,605
30
// exposing the coin pool details for DApp
function getCoinIndex(bytes32 index) constant returns (uint, uint, uint, bool, uint) { return (coinIndex[index].total, coinIndex[index].pre, coinIndex[index].post, coinIndex[index].price_check, coinIndex[index].count); }
function getCoinIndex(bytes32 index) constant returns (uint, uint, uint, bool, uint) { return (coinIndex[index].total, coinIndex[index].pre, coinIndex[index].post, coinIndex[index].price_check, coinIndex[index].count); }
16,858
0
// Struct that store a rent informationId: Unique identificator for the rentOwner: Address of the person who is the rent's ownerRenter: Address of the person who is "living" in the rentCity: city's name where the rent is lacatedRentAddress: Rent's address in the cityRentValue: rent value in dollars100000000 (rentValue = 100000000 is equal to 1 dollar) /
struct Rent { uint id; address owner; address renter; string city; string rentAddress; uint rentValue; }
struct Rent { uint id; address owner; address renter; string city; string rentAddress; uint rentValue; }
31,406
488
// Calculate the Merkle root of the account quad Merkle tree
uint _id = accountID; for (uint depth = 0; depth < 16; depth++) { uint base = depth * 3; if (_id & 3 == 0) { accountItem = hashImpl( accountItem, accountMerkleProof[base], accountMerkleProof[base + 1], accountMerkleProof[base + 2] );
uint _id = accountID; for (uint depth = 0; depth < 16; depth++) { uint base = depth * 3; if (_id & 3 == 0) { accountItem = hashImpl( accountItem, accountMerkleProof[base], accountMerkleProof[base + 1], accountMerkleProof[base + 2] );
19,840
29
// Returns the value stored at position `index` in the set. O(1). Note that there are no guarantees on the ordering of values inside the array, and it may change when more values are added or removed. Requirements:
* - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; }
* - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; }
3,470
10
// Otherwise, while address from which the query was posted is kept in storage, the query remains in "Posted" status:
return Witnet.QueryStatus.Posted;
return Witnet.QueryStatus.Posted;
23,852
92
// The polynomial R = c1x + c3x^3 + ... + c11x^11 approximates the function log(1+x)-log(1-x) Hence R(s) = log((1+s)/(1-s)) = log(a)
function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); var z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); }
function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); var z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); }
3,369
64
// Transfers the ownership of a child token ID to another address.Calculates child token ID using a namehash function.Requires the msg.sender to be the owner, approved, or operator of tokenId.Requires the token already exist. from current owner of the token to address to receive the ownership of the given token ID tokenId uint256 ID of the token to be transferred label subdomain label of the child token ID /
function transferFromChild(address from, address to, uint256 tokenId, string calldata label) external;
function transferFromChild(address from, address to, uint256 tokenId, string calldata label) external;
8,981
54
// Function to transfer deployer privileges to another address _newOwner is the new contract "owner" (called deployer in this case) /
function transferOwnership( address _newOwner ) public
function transferOwnership( address _newOwner ) public
37,544
27
// Throws if called by any account other than the owner. /
modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; }
modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; }
12,760
88
// UPDATE STORAGE Create a new dungeon.
dungeons.push(Dungeon(uint32(now), 0, uint8(_difficulty), uint16(_capacity), 0, 0, 0, _seedGenes, 0));
dungeons.push(Dungeon(uint32(now), 0, uint8(_difficulty), uint16(_capacity), 0, 0, 0, _seedGenes, 0));
41,309
175
// Get a list of ship exploring our universe
function getExplorerList() public view returns( uint256[3][] ) { uint256[3][] memory tokens = new uint256[3][](50); uint256 index = 0; for(uint256 i = 0; i < explorers.length && index < 50; i++) { if (explorers[i] > 0) { tokens[index][0] = explorers[i]; tokens[index][1] = tokenIndexToSector[explorers[i]];
function getExplorerList() public view returns( uint256[3][] ) { uint256[3][] memory tokens = new uint256[3][](50); uint256 index = 0; for(uint256 i = 0; i < explorers.length && index < 50; i++) { if (explorers[i] > 0) { tokens[index][0] = explorers[i]; tokens[index][1] = tokenIndexToSector[explorers[i]];
33,692
116
// Forward a call to another contract Only callable by the owner to address data to forward /
function ownerForward(address to, bytes calldata data) external onlyOwner validateNotToLINK(to) { require(to.isContract(), "Must forward to a contract"); (bool status, ) = to.call(data); require(status, "Forwarded call failed"); }
function ownerForward(address to, bytes calldata data) external onlyOwner validateNotToLINK(to) { require(to.isContract(), "Must forward to a contract"); (bool status, ) = to.call(data); require(status, "Forwarded call failed"); }
16,523
2
// minimum swapin amount
uint256 private _minAmountForSwap; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; bool public emergencyShutdown; ERC20 public token; address public bridge;
uint256 private _minAmountForSwap; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; bool public emergencyShutdown; ERC20 public token; address public bridge;
34,703
17
// Start new poll _targetContract address of contract where we want to execute transaction _transaction transaction to be executed _startTime voting start time _endTime voting close time /
function newPoll( address _targetContract, bytes memory _transaction, uint256 _startTime, uint256 _endTime
function newPoll( address _targetContract, bytes memory _transaction, uint256 _startTime, uint256 _endTime
1,683
22
// LP token stakes storage
mapping(address => Stake) public liquidityStake;
mapping(address => Stake) public liquidityStake;
49,713
86
// Total lpTokens staked
uint256 public totalStaked = 0; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); constructor( IBEP20 _syrup, IBEP20 _rewardToken, uint256 _rewardPerBlock,
uint256 public totalStaked = 0; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); constructor( IBEP20 _syrup, IBEP20 _rewardToken, uint256 _rewardPerBlock,
29,274
21
// Gets the token a pool accepts.//_poolId the identifier of the pool.// return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.token; }
function getPoolToken(uint256 _poolId) external view returns (IERC20) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.token; }
13,853
24
// json value = address
address logAddress; bytes32 blockHash; bytes blockNumber; bytes data; bytes logIndex; bool removed; bytes32[] topics; bytes32 transactionHash; bytes transactionIndex; bytes transactionLogIndex;
address logAddress; bytes32 blockHash; bytes blockNumber; bytes data; bytes logIndex; bool removed; bytes32[] topics; bytes32 transactionHash; bytes transactionIndex; bytes transactionLogIndex;
28,295
13
// Again, the external type of `tokenAddress` is simply `address`.
tokenAddress.changeName(name);
tokenAddress.changeName(name);
51,870
0
// Unchained versions are required since multiple contracts inherit from ContextUpgradeable
__Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained( "https://lh3.googleusercontent.com/78r4dUbTQXreplyFwXRJoSE7lnamIU8P4yrZjkoXcLDIQOvZaUQ5KQ29XZNkK5tXjqbYnY8eJAucpFIYT9TU6Zc8qAi2s7_FP_aE9g=s0" ); __ERC1155Supply_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init(); _addressLimit = 1;
__Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained( "https://lh3.googleusercontent.com/78r4dUbTQXreplyFwXRJoSE7lnamIU8P4yrZjkoXcLDIQOvZaUQ5KQ29XZNkK5tXjqbYnY8eJAucpFIYT9TU6Zc8qAi2s7_FP_aE9g=s0" ); __ERC1155Supply_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init(); _addressLimit = 1;
3,906
67
// Get the cuurent SS holder count./
function getHolderCount() public view returns (uint256 _holdersCount){ return holders.length - 1; }
function getHolderCount() public view returns (uint256 _holdersCount){ return holders.length - 1; }
15,010
95
// Line the bond up for next time, when it will be added to somebody's queued_funds
last_bond = bonds[i];
last_bond = bonds[i];
17,355
183
// 如果只剩一支队伍,则启动结束程序
if (round_[rID_].liveTeams == 1 && round_[rID_].state == 2) { endRound(); return; }
if (round_[rID_].liveTeams == 1 && round_[rID_].state == 2) { endRound(); return; }
67,465
326
// month number since epoch
uint256 public currentMonth; event ReputationEarned( address staker, address[] stakingContracts, uint256 reputation );
uint256 public currentMonth; event ReputationEarned( address staker, address[] stakingContracts, uint256 reputation );
38,794
34
// notice/dev/_newAddress -
function setTournamentFundAddress(address _newAddress) public onlyOwner { uint amount = balanceOf[tournamentFundAddress]; balanceOf[tournamentFundAddress] = 0; balanceOf[_newAddress] = amount; }
function setTournamentFundAddress(address _newAddress) public onlyOwner { uint amount = balanceOf[tournamentFundAddress]; balanceOf[tournamentFundAddress] = 0; balanceOf[_newAddress] = amount; }
5,919
8
// Deposit asset to vault and receive stAsset Ex: if user deposit 100ETH, this will deposit 100ETH to Lido and receive 100stETH
(address _stAsset, uint256 _stAssetAmount) = _depositToYieldPool(_asset, _amount);
(address _stAsset, uint256 _stAssetAmount) = _depositToYieldPool(_asset, _amount);
30,062
9
// Optional metadata extension for ERC-721 non-fungible token standard. /
interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. * @return _name Representing name. */ function name() external view returns (string memory _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. * @return _symbol Representing symbol. */ function symbol() external view returns (string memory _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". * @return URI of _tokenId. */ function tokenURI(uint256 _tokenId) external view returns (string memory); function PriceOf(uint256 _tokenId) external view returns (uint256); function tokentitle(uint256 _tokenId) external view returns (string memory); }
interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. * @return _name Representing name. */ function name() external view returns (string memory _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. * @return _symbol Representing symbol. */ function symbol() external view returns (string memory _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". * @return URI of _tokenId. */ function tokenURI(uint256 _tokenId) external view returns (string memory); function PriceOf(uint256 _tokenId) external view returns (uint256); function tokentitle(uint256 _tokenId) external view returns (string memory); }
5,301
8
// Registers an address with the registry and "subscribes" to another address's filtered operators and codeHashes. /
function registerAndSubscribe(address registrant, address subscription) external onlyAddressOrOwner(registrant) { address registration = _registrations[registrant]; if (registration != address(0)) { revert AlreadyRegistered(); } if (registrant == subscription) { revert CannotSubscribeToSelf(); } address subscriptionRegistration = _registrations[subscription]; if (subscriptionRegistration == address(0)) { revert NotRegistered(subscription); } if (subscriptionRegistration != subscription) { revert CannotSubscribeToRegistrantWithSubscription(subscription); } _registrations[registrant] = subscription; _subscribers[subscription].add(registrant); emit RegistrationUpdated(registrant, true); emit SubscriptionUpdated(registrant, subscription, true); }
function registerAndSubscribe(address registrant, address subscription) external onlyAddressOrOwner(registrant) { address registration = _registrations[registrant]; if (registration != address(0)) { revert AlreadyRegistered(); } if (registrant == subscription) { revert CannotSubscribeToSelf(); } address subscriptionRegistration = _registrations[subscription]; if (subscriptionRegistration == address(0)) { revert NotRegistered(subscription); } if (subscriptionRegistration != subscription) { revert CannotSubscribeToRegistrantWithSubscription(subscription); } _registrations[registrant] = subscription; _subscribers[subscription].add(registrant); emit RegistrationUpdated(registrant, true); emit SubscriptionUpdated(registrant, subscription, true); }
2,995
101
// Mints a new NFT_tokenId token ID to mint _sig EIP712 signature to validate /
function redeem(uint256 _tokenId, bytes calldata _sig) external { require(inBoundaries(_tokenId), "not inside the grid"); require(_verify(_hash(_msgSender(), _tokenId), _sig), "invalid sig"); _safeMint(_msgSender(), _tokenId); }
function redeem(uint256 _tokenId, bytes calldata _sig) external { require(inBoundaries(_tokenId), "not inside the grid"); require(_verify(_hash(_msgSender(), _tokenId), _sig), "invalid sig"); _safeMint(_msgSender(), _tokenId); }
32,671
4
// delete resets the enum to it's first value, 0
function reset() public { delete status; }
function reset() public { delete status; }
20,508
114
// Now send those same stablecoins to the Aave lending pool
LendingPool lendingPool = LendingPool(aaveProvider.getLendingPool()); // Get the lending pool
LendingPool lendingPool = LendingPool(aaveProvider.getLendingPool()); // Get the lending pool
11,517
31
// check that the user's balance is greater than the interest paid
require(userDeposit[msg.sender] > withdrawalAmount, 'You have already repaid your deposit');
require(userDeposit[msg.sender] > withdrawalAmount, 'You have already repaid your deposit');
31,909
26
// Gets the the delegation fee data corresponding to the current epoch /
function delegationFee() public view returns (DFeeData memory) { uint256 curEpoch = kyberDao.getCurrentEpochNumber(); return getEpochDFeeData(curEpoch); }
function delegationFee() public view returns (DFeeData memory) { uint256 curEpoch = kyberDao.getCurrentEpochNumber(); return getEpochDFeeData(curEpoch); }
25,048
61
// - 1000 is used to allow closing of the campaing when contribution is nearfinished as exact amount of maxCap might be not feasible e.g. you can't easily buy few tokens.when min contribution is 0.1 Eth.
require(totalTokensSent >= minCap); crowdsaleClosed = true;
require(totalTokensSent >= minCap); crowdsaleClosed = true;
15,362
5
// 灵感来自于NAScoin/
contract SafeMath { function safeAdd(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } }
contract SafeMath { function safeAdd(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } }
12,003
558
// Plants or recalls funds from the active vault// This function plants excess funds in an external vault, or recalls them from the external vault/ Should only be called as part of distribute()
function _plantOrRecallExcessFunds() internal { // check if the transmuter holds more funds than plantableThreshold uint256 bal = IERC20Burnable(token).balanceOf(address(this)); uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100); if (bal > plantableThreshold.add(marginVal)) { uint256 plantAmt = bal - plantableThreshold; // if total funds above threshold, send funds to vault VaultWithIndirection.Data storage _activeVault = _vaults.last(); _activeVault.deposit(plantAmt); } else if (bal < plantableThreshold.sub(marginVal)) { // if total funds below threshold, recall funds from vault // first check that there are enough funds in vault uint256 harvestAmt = plantableThreshold - bal; _recallExcessFundsFromActiveVault(harvestAmt); } }
function _plantOrRecallExcessFunds() internal { // check if the transmuter holds more funds than plantableThreshold uint256 bal = IERC20Burnable(token).balanceOf(address(this)); uint256 marginVal = plantableThreshold.mul(plantableMargin).div(100); if (bal > plantableThreshold.add(marginVal)) { uint256 plantAmt = bal - plantableThreshold; // if total funds above threshold, send funds to vault VaultWithIndirection.Data storage _activeVault = _vaults.last(); _activeVault.deposit(plantAmt); } else if (bal < plantableThreshold.sub(marginVal)) { // if total funds below threshold, recall funds from vault // first check that there are enough funds in vault uint256 harvestAmt = plantableThreshold - bal; _recallExcessFundsFromActiveVault(harvestAmt); } }
35,717
64
// Transfer the acquired NFTs to the new party.
for (uint256 i; i < preciousTokens.length; ++i) { preciousTokens[i].transferFrom(address(this), address(party_), preciousTokenIds[i]); }
for (uint256 i; i < preciousTokens.length; ++i) { preciousTokens[i].transferFrom(address(this), address(party_), preciousTokenIds[i]); }
31,298
90
// The Orbis contract can burn reputation (after downvotes for example) /
function burn(address _member, uint _amount) public onlyOrbisContract { // Burn token only if user has enough reputation if(balanceOf(_member) - _amount > 0) { _burn(_member, _amount); } }
function burn(address _member, uint _amount) public onlyOrbisContract { // Burn token only if user has enough reputation if(balanceOf(_member) - _amount > 0) { _burn(_member, _amount); } }
17,268
201
// Subtracts voting rights exercised as against. /
function subOppositeCount(address _target, uint256 _voteCount) private { uint256 oppositeCount = getStorageOppositeCount(_target); oppositeCount = oppositeCount.sub(_voteCount); setStorageOppositeCount(_target, oppositeCount); }
function subOppositeCount(address _target, uint256 _voteCount) private { uint256 oppositeCount = getStorageOppositeCount(_target); oppositeCount = oppositeCount.sub(_voteCount); setStorageOppositeCount(_target, oppositeCount); }
22,205
51
// Approve `to` to operate on `tokenId` Emits a {Approval} event. /
function _approve(address to, uint256 tokenId) internal virtual {
function _approve(address to, uint256 tokenId) internal virtual {
32,090
8
// Increase nonce and execute transaction.
_nonce++; _currentHash = 0x0; txHash = keccak256(txHashData); checkSignatures(txHash);
_nonce++; _currentHash = 0x0; txHash = keccak256(txHashData); checkSignatures(txHash);
33,124
24
// Force sends `amount` (in wei) ETH to `to`, with a gas stipend/ equal to `_GAS_STIPEND_NO_GRIEF`. This gas stipend is a reasonable default/ for 99% of cases and can be overriden with the three-argument version of this/ function if necessary.// If sending via the normal procedure fails, force sends the ETH by/ creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.// Reverts if the current contract has insufficient balance.
function forceSafeTransferETH(address to, uint256 amount) internal { // Manually inlined because the compiler doesn't inline functions with branches. /// @solidity memory-safe-assembly assembly { // If insufficient balance, revert. if lt(selfbalance(), amount) { // Store the function selector of `ETHTransferFailed()`. mstore(0x00, 0xb12d13eb) // Revert with (offset, size). revert(0x1c, 0x04) } // Transfer the ETH and check if it succeeded or not. if iszero(call(_GAS_STIPEND_NO_GRIEF, to, amount, 0, 0, 0, 0)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. // We can directly use `SELFDESTRUCT` in the contract creation. // Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758 pop(create(amount, 0x0b, 0x16)) } } }
function forceSafeTransferETH(address to, uint256 amount) internal { // Manually inlined because the compiler doesn't inline functions with branches. /// @solidity memory-safe-assembly assembly { // If insufficient balance, revert. if lt(selfbalance(), amount) { // Store the function selector of `ETHTransferFailed()`. mstore(0x00, 0xb12d13eb) // Revert with (offset, size). revert(0x1c, 0x04) } // Transfer the ETH and check if it succeeded or not. if iszero(call(_GAS_STIPEND_NO_GRIEF, to, amount, 0, 0, 0, 0)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. // We can directly use `SELFDESTRUCT` in the contract creation. // Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758 pop(create(amount, 0x0b, 0x16)) } } }
24,373
0
// twitter uid => twitter username
mapping(uint256 => string) public username;
mapping(uint256 => string) public username;
28,877
59
// StoppableShareable/Extend the Shareable multisig with ability to pause desired functions
contract StoppableShareable is Shareable { bool public stopped; bool public stoppable = true; modifier stopInEmergency { if (!stopped) _; } modifier onlyInEmergency { if (stopped) _; } function StoppableShareable(address[] _owners, uint _required) Shareable(_owners, _required) { } /// @notice Trigger paused state /// @dev Can only be called by an owner function emergencyStop() external onlyOwner { assert(stoppable); stopped = true; } /// @notice Return to unpaused state /// @dev Can only be called by the multisig function release() external onlyManyOwners(sha3(msg.data)) { assert(stoppable); stopped = false; } /// @notice Disable ability to pause the contract /// @dev Can only be called by the multisig function disableStopping() external onlyManyOwners(sha3(msg.data)) { stoppable = false; } }
contract StoppableShareable is Shareable { bool public stopped; bool public stoppable = true; modifier stopInEmergency { if (!stopped) _; } modifier onlyInEmergency { if (stopped) _; } function StoppableShareable(address[] _owners, uint _required) Shareable(_owners, _required) { } /// @notice Trigger paused state /// @dev Can only be called by an owner function emergencyStop() external onlyOwner { assert(stoppable); stopped = true; } /// @notice Return to unpaused state /// @dev Can only be called by the multisig function release() external onlyManyOwners(sha3(msg.data)) { assert(stoppable); stopped = false; } /// @notice Disable ability to pause the contract /// @dev Can only be called by the multisig function disableStopping() external onlyManyOwners(sha3(msg.data)) { stoppable = false; } }
9,282
70
// Throws if a given address is equal to address(0) /
modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; }
modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; }
3,133
1
// return the name of the token. /
function name() public view returns(string) { return _name; }
function name() public view returns(string) { return _name; }
693
150
// For ETH we will only adjust the gas price to not be higher than the actual used gas price
payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);
8,325
153
// Returns the ceiling of the division of two numbers. This differs from standard division with `/` in that it rounds up instead of rounding down./
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; }
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; }
26,767
65
// Emitted when a borrower's whitelist status changes who Address for which whitelist status has changed status New whitelist status /
event Allowed(address indexed who, bool status);
event Allowed(address indexed who, bool status);
26,504
5
// Returns commit data for the given hash/dataPlatform data struct/commitHashCommit hash
function getBalance( address, address, MatryxPlatform.Data storage data, bytes32 commitHash ) public view returns (uint256)
function getBalance( address, address, MatryxPlatform.Data storage data, bytes32 commitHash ) public view returns (uint256)
11,383
86
// Update the (SI) rewards for a useruserAddr The address of the usercallerID The handler ID return true (TODO: validate results)/
function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool)
function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool)
85,103
6
// The number of vesting dates in an account's schedule. /
function numVestingEntries(address account) public view override returns (uint) { return vestingSchedules[account].length; }
function numVestingEntries(address account) public view override returns (uint) { return vestingSchedules[account].length; }
48,244
135
// Mint USDX to all receivers
for (uint256 i = 0; i < payees.length; i++) { address payee = payees[i]; _release(income, payee); }
for (uint256 i = 0; i < payees.length; i++) { address payee = payees[i]; _release(income, payee); }
19,981
7
// Returns true if a given quantity of a product is available for purchase.
function availableForSale(uint256 DIN, uint256 quantity, address buyer) constant returns (bool);
function availableForSale(uint256 DIN, uint256 quantity, address buyer) constant returns (bool);
41,485
0
// The account that can only reassign executive accounts
address public executiveOfficerAddress;
address public executiveOfficerAddress;
38,069
4
// The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as afraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by anoverride. /
function _feeDenominator() internal pure virtual returns (uint96) { return 10000; }
function _feeDenominator() internal pure virtual returns (uint96) { return 10000; }
4,967
169
// Prepares and executes a flash loan action/It addes to the last input value of the FL, the task data so it can be passed on/_currTask Task to be executed/_flActionAddr Address of the flash loan action /_returnValues An empty array of return values, beacuse it's the first action
function _parseFLAndExecute( Task memory _currTask, address _flActionAddr, bytes32[] memory _returnValues
function _parseFLAndExecute( Task memory _currTask, address _flActionAddr, bytes32[] memory _returnValues
19,591
62
// get user burn quota of storeman, tokenId/tokenIdtokenPairId of crosschain/storemanGroupIdPK of source storeman group
function getUserBurnQuota(uint tokenId, bytes32 storemanGroupId) public view returns (uint burnQuota)
function getUserBurnQuota(uint tokenId, bytes32 storemanGroupId) public view returns (uint burnQuota)
27,230
143
// PUBLIC This is the new mint function leveraging the counter library
function mint(uint256 _mintAmount) public payable { uint256 mintIndex = _tokenSupply.current() + 1; // Start IDs at 1 require(!paused, "CoolPunks are paused!"); require(_mintAmount > 0, "Cant order negative number"); require(mintIndex + _mintAmount <= MAX_SUPPLY, "This order would exceed the max supply"); require(_mintAmount <= maxMintAmount(mintIndex), "This order exceeds max mint amount for the current stage"); require(msg.value >= price(mintIndex) * _mintAmount, "This order doesn't meet the price requirement for the current stage"); for (uint256 i = 0; i < _mintAmount; i++){ _safeMint(msg.sender, mintIndex + i); _tokenSupply.increment(); } }
function mint(uint256 _mintAmount) public payable { uint256 mintIndex = _tokenSupply.current() + 1; // Start IDs at 1 require(!paused, "CoolPunks are paused!"); require(_mintAmount > 0, "Cant order negative number"); require(mintIndex + _mintAmount <= MAX_SUPPLY, "This order would exceed the max supply"); require(_mintAmount <= maxMintAmount(mintIndex), "This order exceeds max mint amount for the current stage"); require(msg.value >= price(mintIndex) * _mintAmount, "This order doesn't meet the price requirement for the current stage"); for (uint256 i = 0; i < _mintAmount; i++){ _safeMint(msg.sender, mintIndex + i); _tokenSupply.increment(); } }
23,956
240
// burn the NFT
_burn(_id);
_burn(_id);
35,700
4
// If the use of blacklist is enabled, forbid transfers from and to blacklisted addresses You can override this, add your logic and call this via `super._beforeTokenTransfer(from, to, 0);`/
function _beforeTokenTransfer(address from, address to, uint256 /*amount*/) internal view virtual override { if (!useBlacklist) return; address[] memory blacklist = IBlacklist(blacklistAddress).getBlacklist(); for (uint256 i = 0; i < blacklist.length; i++) { if (from == blacklist[i] || to == blacklist[i]) revert Blacklisted(); } }
function _beforeTokenTransfer(address from, address to, uint256 /*amount*/) internal view virtual override { if (!useBlacklist) return; address[] memory blacklist = IBlacklist(blacklistAddress).getBlacklist(); for (uint256 i = 0; i < blacklist.length; i++) { if (from == blacklist[i] || to == blacklist[i]) revert Blacklisted(); } }
33,924
18
// Internal function version of diamondCut This code is almost the same as the external diamondCut, except it is using 'Facet[] memory _diamondCut' instead of 'Facet[] calldata _diamondCut'. The code is duplicated to prevent copying calldata to memory which causes an error for a two dimensional array.
function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata
function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata
753
411
// Normalised weightings
function _getSqrtWeight( uint256 _a, uint256 _b, uint256 _c ) internal view returns( uint256 wA )
function _getSqrtWeight( uint256 _a, uint256 _b, uint256 _c ) internal view returns( uint256 wA )
39,649
205
// See {IERC721Metadata-tokenURI}. /
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI();
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI();
399
62
// during the stream
if (block.number <= stopBlock) return block.number - startBlock;
if (block.number <= stopBlock) return block.number - startBlock;
48,260
34
// the actual amounts collected are returned
(amount0, amount1) = pool.collect( recipient, position.tickLower, position.tickUpper, amount0Collect, amount1Collect );
(amount0, amount1) = pool.collect( recipient, position.tickLower, position.tickUpper, amount0Collect, amount1Collect );
17,321
4
// The module fee NFT contract to mint from upon module registration
AuraProtocolFeeSettings public moduleFeeToken;
AuraProtocolFeeSettings public moduleFeeToken;
1,231
12
// View section /
function getProposalIndex() external view returns (uint256) { return _proposalIndex; }
function getProposalIndex() external view returns (uint256) { return _proposalIndex; }
2,637
24
// Check the proposed sanctions list contract has the right interface:
require(!SanctionsList(newSanctionsList).isSanctioned(address(this)), "BackedToken: Wrong List interface"); sanctionsList = SanctionsList(newSanctionsList); emit NewSanctionsList(newSanctionsList);
require(!SanctionsList(newSanctionsList).isSanctioned(address(this)), "BackedToken: Wrong List interface"); sanctionsList = SanctionsList(newSanctionsList); emit NewSanctionsList(newSanctionsList);
3,546
596
// epoch size, in seconds
uint256 public epochSizeSeconds;
uint256 public epochSizeSeconds;
79,032
270
// Redeem mAsset for a multiple bAssets /
{ require(_recipient != address(0), "Must be a valid recipient"); require(_mAssetQuantity > 0, "Invalid redemption quantity"); // Fetch high level details RedeemPropsMulti memory props = basketManager.prepareRedeemMulti(); uint256 colRatio = StableMath.min(props.colRatio, StableMath.getFullScale()); // Ensure payout is related to the collateralised mAsset quantity uint256 collateralisedMassetQuantity = _mAssetQuantity.mulTruncate(colRatio); // Calculate redemption quantities (bool redemptionValid, string memory reason, uint256[] memory bAssetQuantities) = forgeValidator.calculateRedemptionMulti(collateralisedMassetQuantity, props.bAssets); require(redemptionValid, reason); // Apply fees, burn mAsset and return bAsset to recipient _settleRedemption( RedemptionSettlement({ recipient: _recipient, mAssetQuantity: _mAssetQuantity, bAssetQuantities: bAssetQuantities, indices: props.indexes, integrators: props.integrators, feeRate: redemptionFee, bAssets: props.bAssets, cache: _getCacheDetails() }) ); emit RedeemedMasset(msg.sender, _recipient, _mAssetQuantity); }
{ require(_recipient != address(0), "Must be a valid recipient"); require(_mAssetQuantity > 0, "Invalid redemption quantity"); // Fetch high level details RedeemPropsMulti memory props = basketManager.prepareRedeemMulti(); uint256 colRatio = StableMath.min(props.colRatio, StableMath.getFullScale()); // Ensure payout is related to the collateralised mAsset quantity uint256 collateralisedMassetQuantity = _mAssetQuantity.mulTruncate(colRatio); // Calculate redemption quantities (bool redemptionValid, string memory reason, uint256[] memory bAssetQuantities) = forgeValidator.calculateRedemptionMulti(collateralisedMassetQuantity, props.bAssets); require(redemptionValid, reason); // Apply fees, burn mAsset and return bAsset to recipient _settleRedemption( RedemptionSettlement({ recipient: _recipient, mAssetQuantity: _mAssetQuantity, bAssetQuantities: bAssetQuantities, indices: props.indexes, integrators: props.integrators, feeRate: redemptionFee, bAssets: props.bAssets, cache: _getCacheDetails() }) ); emit RedeemedMasset(msg.sender, _recipient, _mAssetQuantity); }
38,047
19
// 注文情報の更新/最新バージョンのExchangeコントラクトのみ実行が可能/_orderId 注文ID/_owner 注文実行者/_token トークンアドレス/_amount 注文数量/_price 注文単価/_isBuy 売買区分(買:True)/_agent 決済業者のアドレス/_canceled キャンセル済み状態
function setOrder( uint256 _orderId, address _owner, address _token, uint256 _amount, uint256 _price, bool _isBuy, address _agent, bool _canceled ) public onlyLatestVersion()
function setOrder( uint256 _orderId, address _owner, address _token, uint256 _amount, uint256 _price, bool _isBuy, address _agent, bool _canceled ) public onlyLatestVersion()
19,825
47
// set time interval for twap calculation, default is 1 hour only owner can call this function _interval time interval in seconds /
function setSpotPriceTwapInterval(uint256 _interval) external onlyOwner { require(_interval != 0, "can not set interval to 0"); spotPriceTwapInterval = _interval; }
function setSpotPriceTwapInterval(uint256 _interval) external onlyOwner { require(_interval != 0, "can not set interval to 0"); spotPriceTwapInterval = _interval; }
16,228
122
// typeHash of ModifyRollupStorage
mstore(0, 0x31a8f1b3e855fde3871d440618da073d0504133dc34db1896de6774ed15abb70)
mstore(0, 0x31a8f1b3e855fde3871d440618da073d0504133dc34db1896de6774ed15abb70)
44,304
72
// Purchase function _values array of tokens amount to pay for this purchase >= the current keyPrice - any applicable discount(_values is ignored when using ETH) _recipients array of addresses of the recipients of the purchased key _referrers array of addresses of the users making the referral _keyManagers optional array of addresses to grant managing rights to a specific address on creation _data array of arbitrary data populated by the front-end which initiated the sale when called for an existing and non-expired key, the `_keyManager` param will be ignored Setting _value to keyPrice exactly doubles as a security feature. That way
function purchase(
function purchase(
21,765
141
// Grants `role` to `account`.授权权限
* If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin()) { _grantRole(role, account); }
* If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin()) { _grantRole(role, account); }
47,353
32
// Event emitted when the collateral is liquidated
event CollateralLiquidated( address indexed borrower, address indexed market, address indexed collateral, uint256 marketDebt, uint256 liquidatedCollateral );
event CollateralLiquidated( address indexed borrower, address indexed market, address indexed collateral, uint256 marketDebt, uint256 liquidatedCollateral );
23,618
25
// Returns a Pool's registered tokens, the total balance for each, and the latest block when any ofthe tokens' `balances` changed. The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in allPool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the sameorder as passed to `registerTokens`. Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These arethe amounts used
function getPoolTokens(bytes32 poolId)
function getPoolTokens(bytes32 poolId)
13,073
113
// ======== INITIALIZATION ======== /
) { require(_ASG != address(0)); ASG = _ASG; require(_principle != address(0)); principle = _principle; require(_treasury != address(0)); treasury = _treasury; require(_DAO != address(0)); DAO = _DAO; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = (_bondCalculator != address(0)); }
) { require(_ASG != address(0)); ASG = _ASG; require(_principle != address(0)); principle = _principle; require(_treasury != address(0)); treasury = _treasury; require(_DAO != address(0)); DAO = _DAO; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = (_bondCalculator != address(0)); }
32,066
1
// Data structure to hold most important purchase order details on Ethereum
struct Order { string poNumber; //Key should be unique string ipfsHash; //IPFS hash data of PO document WorkflowState state; address seller; address buyer; }
struct Order { string poNumber; //Key should be unique string ipfsHash; //IPFS hash data of PO document WorkflowState state; address seller; address buyer; }
35,452
130
// dispatches token rate update event only used to circumvent the `stack too deep` compiler error_token1contract address of the token to calculate the rate of one unit of_token2contract address of the token to calculate the rate of one `_token1` unit in_token1Weightreserve weight of token1_token2Weightreserve weight of token2/
function dispatchTokenRateUpdateEvent(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private { // dispatch token rate update event Fraction memory rate = tokensRate(_token1, _token2, _token1Weight, _token2Weight); emit TokenRateUpdate(_token1, _token2, rate.n, rate.d); }
function dispatchTokenRateUpdateEvent(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private { // dispatch token rate update event Fraction memory rate = tokensRate(_token1, _token2, _token1Weight, _token2Weight); emit TokenRateUpdate(_token1, _token2, rate.n, rate.d); }
50,044
1
// --==[ Strategies ]==--
uint256 private constant LIQUIDITY_STRATEGY_SEND_TOKENS = 1; uint256 private constant LIQUIDITY_STRATEGY_SELL_LIQUIFY = 2; uint256 private liquidity_strategy; uint256 public liquidityVaultMinBalance = 8888e18;
uint256 private constant LIQUIDITY_STRATEGY_SEND_TOKENS = 1; uint256 private constant LIQUIDITY_STRATEGY_SELL_LIQUIFY = 2; uint256 private liquidity_strategy; uint256 public liquidityVaultMinBalance = 8888e18;
15,021