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
16
// Decreases the approval of the spender./ This function is overriden to leverage transfer state feature./ _spender The address of the spender to decrease the allocation from./ _subtractedValue The amount of tokens to subtract from the approved allocation.
function decreaseApproval(address _spender, uint256 _subtractedValue) public canTransfer(msg.sender) returns (bool) { require(_spender != address(0)); return super.decreaseApproval(_spender, _subtractedValue); }
function decreaseApproval(address _spender, uint256 _subtractedValue) public canTransfer(msg.sender) returns (bool) { require(_spender != address(0)); return super.decreaseApproval(_spender, _subtractedValue); }
43,504
59
// Give them our money
balances[ownerOfTradeOffer] += payedValue; balances[msg.sender] -= payedValue;
balances[ownerOfTradeOffer] += payedValue; balances[msg.sender] -= payedValue;
50,490
94
// Increase total contributions.
totalContributions += amount;
totalContributions += amount;
26,362
10
// increase amount
IStaker(staker).increaseAmount(crvBalanceStaker); uint256 unlockAt = block.timestamp + MAXTIME; uint256 unlockInWeeks = (unlockAt/WEEK)*WEEK;
IStaker(staker).increaseAmount(crvBalanceStaker); uint256 unlockAt = block.timestamp + MAXTIME; uint256 unlockInWeeks = (unlockAt/WEEK)*WEEK;
3,025
132
// Interactions During the first deposit, we check that this token is 'real'
if (token_ == USE_ETHEREUM) {
if (token_ == USE_ETHEREUM) {
64,356
1
// Returns true if `_account` is the current owner_account The address to test against /
function isOwner(address _account) public view returns (bool);
function isOwner(address _account) public view returns (bool);
35,212
9
// Get things to work on OpenSea with mock methods below/
function safeTransferFrom(address _from, address _to, uint256 _optionId, uint256 _amount, bytes calldata _data) external; function balanceOf(address _owner, uint256 _optionId) external view returns (uint256); function isApprovedForAll(address _owner, address _operator) external view returns (bool);
function safeTransferFrom(address _from, address _to, uint256 _optionId, uint256 _amount, bytes calldata _data) external; function balanceOf(address _owner, uint256 _optionId) external view returns (uint256); function isApprovedForAll(address _owner, address _operator) external view returns (bool);
2,663
2
// getKeyRetrieves the public key for the given address. Throws an error if the key is not registered. _address - address to queryreturn pubKey - ABI encoded public key retrieved from storage /
function getKey(address _address) public view returns (bytes memory pubKey) { pubKey = new bytes(64); bytes32[2] memory key = mappedKeys[_address]; require(key[0] != bytes32(0), "Key not mapped."); assembly { mstore(add(pubKey, 32), mload(key)) mstore(add(pubKey, 64), mload(add(key, 32))) } }
function getKey(address _address) public view returns (bytes memory pubKey) { pubKey = new bytes(64); bytes32[2] memory key = mappedKeys[_address]; require(key[0] != bytes32(0), "Key not mapped."); assembly { mstore(add(pubKey, 32), mload(key)) mstore(add(pubKey, 64), mload(add(key, 32))) } }
17,102
71
// 1. Ensure aggregate root has been proven.
verifyAggregateRoot(_aggregateRoot);
verifyAggregateRoot(_aggregateRoot);
22,754
89
// Changes the dex to use when swap tokens/_isUniswap If true, uses Uniswap, otherwise uses Sushiswap
function switchDex(bool _isUniswap) external onlyAuthorized { if (_isUniswap) { dex = UNISWAP_ADDRESS; } else { dex = SUSHISWAP_ADDRESS; } _approveDex(); }
function switchDex(bool _isUniswap) external onlyAuthorized { if (_isUniswap) { dex = UNISWAP_ADDRESS; } else { dex = SUSHISWAP_ADDRESS; } _approveDex(); }
19,999
0
// Interface contract to be implemented by SyscoinERC20Manager
interface SyscoinTransactionProcessorI { function processTransaction(uint txHash, uint value, address destinationAddress, uint32 assetGuid) external; function freezeBurnERC20(uint value, uint32 assetGuid, string calldata syscoinAddress) external payable returns (bool); function processAsset(uint txHash, uint32 assetGuid, uint64 height, address erc20ContractAddress, uint8 _precision) external; }
interface SyscoinTransactionProcessorI { function processTransaction(uint txHash, uint value, address destinationAddress, uint32 assetGuid) external; function freezeBurnERC20(uint value, uint32 assetGuid, string calldata syscoinAddress) external payable returns (bool); function processAsset(uint txHash, uint32 assetGuid, uint64 height, address erc20ContractAddress, uint8 _precision) external; }
49,531
7
// Functions to interact with attributes of UserAccount:MyName,MyPubKey
function getMyName(bytes32 Identity) constant returns (bytes32 MyName) { address target = UserMappingList[sha256(Identity)]; MyName = UserAccount(target).MyNickname(); }
function getMyName(bytes32 Identity) constant returns (bytes32 MyName) { address target = UserMappingList[sha256(Identity)]; MyName = UserAccount(target).MyNickname(); }
2,217
71
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) {
uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) {
4,841
226
// INTERNAL FUNCTIONS/ Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); }
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); }
29,265
13
// The Lender implementation
contract FlashLender is IERC3156FlashLender { bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); mapping(address => bool) public supportedTokens; uint256 public fee; // 1 == 0.0001 %. constructor(address[] memory supportedTokens_, uint256 fee_) { for (uint256 i = 0; i < supportedTokens_.length; i++) { supportedTokens[supportedTokens_[i]] = true; } fee = fee_; } function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) external override returns(bool) { require(supportedTokens[token], "FlashLender: Unsupported currency"); fee = _flashFee(amount); require(IERC20(token).transfer(address(receiver), amount),"FlashLender: Transfer failed"); require(receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS,"FlashLender: Callback failed"); require(IERC20(token).transferFrom(address(receiver), address(this), amount + fee),"FlashLender: Repay failed"); return true; } function flashFee(address token, uint256 amount) external view override returns (uint256) { require(supportedTokens[token],"FlashLender: Unsupported currency"); return _flashFee(amount); } function _flashFee(uint256 amount) internal view returns (uint256) { return amount * fee / 10000; } function maxFlashLoan(address token) external view override returns (uint256) { return supportedTokens[token] ? IERC20(token).balanceOf(address(this)) : 0; } }
contract FlashLender is IERC3156FlashLender { bytes32 public constant CALLBACK_SUCCESS = keccak256("ERC3156FlashBorrower.onFlashLoan"); mapping(address => bool) public supportedTokens; uint256 public fee; // 1 == 0.0001 %. constructor(address[] memory supportedTokens_, uint256 fee_) { for (uint256 i = 0; i < supportedTokens_.length; i++) { supportedTokens[supportedTokens_[i]] = true; } fee = fee_; } function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) external override returns(bool) { require(supportedTokens[token], "FlashLender: Unsupported currency"); fee = _flashFee(amount); require(IERC20(token).transfer(address(receiver), amount),"FlashLender: Transfer failed"); require(receiver.onFlashLoan(msg.sender, token, amount, fee, data) == CALLBACK_SUCCESS,"FlashLender: Callback failed"); require(IERC20(token).transferFrom(address(receiver), address(this), amount + fee),"FlashLender: Repay failed"); return true; } function flashFee(address token, uint256 amount) external view override returns (uint256) { require(supportedTokens[token],"FlashLender: Unsupported currency"); return _flashFee(amount); } function _flashFee(uint256 amount) internal view returns (uint256) { return amount * fee / 10000; } function maxFlashLoan(address token) external view override returns (uint256) { return supportedTokens[token] ? IERC20(token).balanceOf(address(this)) : 0; } }
18,429
45
// Approval not supported
function approve(address spender, uint256 amount) public virtual override(ERC20) returns (bool) { spender; amount; revert(); }
function approve(address spender, uint256 amount) public virtual override(ERC20) returns (bool) { spender; amount; revert(); }
27,044
10
// Return the amount of token out as liquidation reward for liquidating token in./tokenIn Input ERC20 token/tokenOut Output ERC1155 token/tokenOutId Output ERC1155 token id/amountIn Input ERC20 token amount
function convertForLiquidation( address tokenIn, address tokenOut, uint tokenOutId, uint amountIn
function convertForLiquidation( address tokenIn, address tokenOut, uint tokenOutId, uint amountIn
47,522
0
// Abstract ERC20 token interface
contract AbstractToken { function balanceOf(address owner) public view returns (uint256 balance); function transfer(address to, uint256 value) public returns (bool success); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); function allowance(address owner, address spender) public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
contract AbstractToken { function balanceOf(address owner) public view returns (uint256 balance); function transfer(address to, uint256 value) public returns (bool success); function transferFrom(address from, address to, uint256 value) public returns (bool success); function approve(address spender, uint256 value) public returns (bool success); function allowance(address owner, address spender) public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
15,540
61
// only owner can show address for safety reasons
return multisig;
return multisig;
57,620
127
// Transfers the ownership of a given asset from one address to another addressWarning! This function does not attempt to verify that the target address can sendtokens._from address sending the asset _to address to receive the ownership of the asset _assetId uint256 ID of the asset to be transferred /
function transferFrom(address _from, address _to, uint256 _assetId) external { return _doTransferFrom( _from, _to, _assetId, "", false ); }
function transferFrom(address _from, address _to, uint256 _assetId) external { return _doTransferFrom( _from, _to, _assetId, "", false ); }
15,398
9
// Internal functions
function mixinNextSnapshotId() internal returns (uint256)
function mixinNextSnapshotId() internal returns (uint256)
23,017
12
// add new token by admin
function addNewTokenByAdmin(address _tokenAddress, string _tokenName,uint8 decimal) onlyAuthorizedAdmin() public
function addNewTokenByAdmin(address _tokenAddress, string _tokenName,uint8 decimal) onlyAuthorizedAdmin() public
20,902
2
// lib/dss-interfaces/src/dss/DaiJoinAbstract.sol/ pragma solidity >=0.5.12; / https:github.com/makerdao/dss/blob/master/src/join.sol
interface DaiJoinAbstract { function wards(address) external view returns (uint256); function rely(address usr) external; function deny(address usr) external; function vat() external view returns (address); function dai() external view returns (address); function live() external view returns (uint256); function cage() external; function join(address, uint256) external; function exit(address, uint256) external; }
interface DaiJoinAbstract { function wards(address) external view returns (uint256); function rely(address usr) external; function deny(address usr) external; function vat() external view returns (address); function dai() external view returns (address); function live() external view returns (uint256); function cage() external; function join(address, uint256) external; function exit(address, uint256) external; }
78,553
8
// This notifies clients about the amount locked
event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity);
event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity);
16,917
0
// TokenTimelockFactory Allows creation of timelock wallet. /
contract TokenTimelockFactory { /** * @dev Allows verified creation of token timelock wallet. * @param _token Address of the token being locked. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred. * @param _releaseTime The release times after which the tokens can be withdrawn. * @return Returns wallet address. */ function create( ERC20 _token, address _beneficiary, uint256 _releaseTime ) public returns (address wallet); }
contract TokenTimelockFactory { /** * @dev Allows verified creation of token timelock wallet. * @param _token Address of the token being locked. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred. * @param _releaseTime The release times after which the tokens can be withdrawn. * @return Returns wallet address. */ function create( ERC20 _token, address _beneficiary, uint256 _releaseTime ) public returns (address wallet); }
30,213
1
// ROLE_CHAIRPERSON is granted to the/ original contract deployer//See {Roleplay::grantRole()}/
constructor() public { grantRole(ROLE_CHAIRPERSON, msg.sender); }
constructor() public { grantRole(ROLE_CHAIRPERSON, msg.sender); }
41,730
49
// Mask out irrelevant bytes and check again
uint256 mask = type(uint256).max; // 0xffff... if (shortest < 32) { mask = ~(2**(8 * (32 - shortest + idx)) - 1); }
uint256 mask = type(uint256).max; // 0xffff... if (shortest < 32) { mask = ~(2**(8 * (32 - shortest + idx)) - 1); }
33,095
11
// extra data
uint payload;
uint payload;
50,111
6
// assertEquals(blovote.getQuestionPointInfo(1, 0), point2);assertEquals(blovote.getQuestionPointInfo(1, 1), point4);
blovote.updateState(Blovote.State.Active); uint8[] memory ans1 = new uint8[](2); ans1[1] = 0; ans1[0] = 1;
blovote.updateState(Blovote.State.Active); uint8[] memory ans1 = new uint8[](2); ans1[1] = 0; ans1[0] = 1;
19,178
18
// return bool true if crowdsale event has ended /
function hasEnded() public constant returns (bool) { return now > endTime; }
function hasEnded() public constant returns (bool) { return now > endTime; }
22,345
148
// function to calculate the interest using a linear interest rate formula _rate the interest rate, in ray _lastUpdateTimestamp the timestamp of the last update of the interestreturn the interest rate linearly accumulated during the timeDelta, in ray /
{ //solium-disable-next-line uint256 timeDifference = block.timestamp.sub( uint256(_lastUpdateTimestamp) ); uint256 timeDelta = timeDifference.wadToRay().rayDiv( SECONDS_PER_YEAR.wadToRay() ); return _rate.rayMul(timeDelta).add(WadRayMath.ray()); }
{ //solium-disable-next-line uint256 timeDifference = block.timestamp.sub( uint256(_lastUpdateTimestamp) ); uint256 timeDelta = timeDifference.wadToRay().rayDiv( SECONDS_PER_YEAR.wadToRay() ); return _rate.rayMul(timeDelta).add(WadRayMath.ray()); }
23,860
50
// Maps tokenId to 2D (true) or 3D (false)
mapping(uint256 => bool) public tokenIdToUpgraded;
mapping(uint256 => bool) public tokenIdToUpgraded;
35,795
6
// Sets the max private batch for private sale _privateMaxBatch new max private batch /
function setPrivateMaxBatch(uint256 _privateMaxBatch) external onlyOwner { privateMaxBatch = _privateMaxBatch; }
function setPrivateMaxBatch(uint256 _privateMaxBatch) external onlyOwner { privateMaxBatch = _privateMaxBatch; }
14,320
85
// Else the Replace the found Relayer with the requestor and transfer the locked funds back to his address
uint256 refund = relayers[targetEpoch][toBeReplacedRelayerIndex] .remainingPenaltyFunds; epochRelayerIndex[targetEpoch][toBeReplacedRelayer] = 0; relayers[targetEpoch][toBeReplacedRelayerIndex].fee = fee; relayers[targetEpoch][toBeReplacedRelayerIndex].maxUsers = maxUsers; relayers[targetEpoch][toBeReplacedRelayerIndex].maxCoins = maxCoins; relayers[targetEpoch][toBeReplacedRelayerIndex] .maxTxThroughput = maxTxThroughput; relayers[targetEpoch][toBeReplacedRelayerIndex] .offchainTxDelay = offchainTxDelay;
uint256 refund = relayers[targetEpoch][toBeReplacedRelayerIndex] .remainingPenaltyFunds; epochRelayerIndex[targetEpoch][toBeReplacedRelayer] = 0; relayers[targetEpoch][toBeReplacedRelayerIndex].fee = fee; relayers[targetEpoch][toBeReplacedRelayerIndex].maxUsers = maxUsers; relayers[targetEpoch][toBeReplacedRelayerIndex].maxCoins = maxCoins; relayers[targetEpoch][toBeReplacedRelayerIndex] .maxTxThroughput = maxTxThroughput; relayers[targetEpoch][toBeReplacedRelayerIndex] .offchainTxDelay = offchainTxDelay;
45,211
116
// Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
for (y >>= 1; y > 0; y >>= 1) { x = PRBMath.mulDivFixedPoint(x, x);
for (y >>= 1; y > 0; y >>= 1) { x = PRBMath.mulDivFixedPoint(x, x);
36,366
15
// updates new admin fee address/can only be updated after timelock
function updateNewAdminFeeAddress() external override { uint256 _feeToUpdateTime = feeToUpdateTime; require(_feeToUpdateTime != 0, "Factory: !Proposed"); require(block.timestamp >= _feeToUpdateTime, "Factory: UPDATE_TIME"); feeTo = pendingFeeTo; delete feeToUpdateTime; }
function updateNewAdminFeeAddress() external override { uint256 _feeToUpdateTime = feeToUpdateTime; require(_feeToUpdateTime != 0, "Factory: !Proposed"); require(block.timestamp >= _feeToUpdateTime, "Factory: UPDATE_TIME"); feeTo = pendingFeeTo; delete feeToUpdateTime; }
43,565
107
// Amount of credit needed to cover debt+fees for all active auctions [wad]
uint256 public override globalDebtOnAuction;
uint256 public override globalDebtOnAuction;
11,352
6
// Metadata is a URL that points to a json dictionary
mapping(uint256 => string) tokenIdToMetadata;
mapping(uint256 => string) tokenIdToMetadata;
37,449
22
// turn on directly another pool if it exists
newIncentive = isLimitFarming ? virtualPools.eternalVirtualPool : virtualPools.limitVirtualPool;
newIncentive = isLimitFarming ? virtualPools.eternalVirtualPool : virtualPools.limitVirtualPool;
28,290
6
// Parse 1inch calldata and validate parameters match expected inputs solium-disable-next-line security/no-inline-assembly
assembly { signature := mload(add(_data, 32)) fromToken := mload(add(_data, 36)) toToken := mload(add(_data, 68)) fromTokenAmount := mload(add(_data, 100)) minReturnAmount := mload(add(_data, 132)) }
assembly { signature := mload(add(_data, 32)) fromToken := mload(add(_data, 36)) toToken := mload(add(_data, 68)) fromTokenAmount := mload(add(_data, 100)) minReturnAmount := mload(add(_data, 132)) }
2,301
142
// destination for operational costs account
address public opVaultAddr;
address public opVaultAddr;
77,272
28
// OneSplit contract interface.Only the functions required for OneSplitInteractiveAdapter contract are added.The OneSplit contract is available heregithub.com/CryptoManiacsZone/1split/blob/master/contracts/OneSplit.sol. /
interface OneSplit { function swap( address, address, uint256, uint256, uint256[] calldata, uint256 ) external payable; function getExpectedReturn( address, address, uint256, uint256, uint256 ) external view returns (uint256, uint256[] memory); }
interface OneSplit { function swap( address, address, uint256, uint256, uint256[] calldata, uint256 ) external payable; function getExpectedReturn( address, address, uint256, uint256, uint256 ) external view returns (uint256, uint256[] memory); }
33,980
7
// Withdraws ERC20 token from an account to Escrow Admin.The transfer action is done inside this function. account The account to withdraw ERC20 token. token The ERC20 token to withdraw. amount The amount of ERC20 tokens to withdraw. /
function withdrawByAdmin(address account, address token, uint256 amount) public override onlyAdmin { require(account != address(0x0), "EscrowBase: Account not set"); require(token != address(0x0), "EscrowBase: Token not set"); require(amount > 0, "EscrowBase: Amount not set"); require(getTokenBalance(account, token) >= amount, "EscrowBase: Insufficient Balance"); // Updates the balance _decreaseBalance(account, token, amount); IERC20(token).safeTransfer(msg.sender, amount); }
function withdrawByAdmin(address account, address token, uint256 amount) public override onlyAdmin { require(account != address(0x0), "EscrowBase: Account not set"); require(token != address(0x0), "EscrowBase: Token not set"); require(amount > 0, "EscrowBase: Amount not set"); require(getTokenBalance(account, token) >= amount, "EscrowBase: Insufficient Balance"); // Updates the balance _decreaseBalance(account, token, amount); IERC20(token).safeTransfer(msg.sender, amount); }
50,386
2
// Returns the amount of tokens owned by `account`./
function balanceOf(address account) external view returns(uint256);
function balanceOf(address account) external view returns(uint256);
16,097
38
// Emitted when the state bridge is enabled or disabled.//isEnabled Set to `true` if the event comes from the state bridge being enabled,/`false` otherwise.
event StateBridgeStateChange(bool indexed isEnabled);
event StateBridgeStateChange(bool indexed isEnabled);
8,607
113
// Map from token ID to their corresponding sale.
mapping (uint256 => Sale) tokenIdToSale; event SaleCreated(uint256 tokenId, uint256 price); event SaleSuccessful(uint256 tokenId, uint256 price, address buyer); event SaleCancelled(uint256 tokenId);
mapping (uint256 => Sale) tokenIdToSale; event SaleCreated(uint256 tokenId, uint256 price); event SaleSuccessful(uint256 tokenId, uint256 price, address buyer); event SaleCancelled(uint256 tokenId);
77,907
18
// -------------------------------------------------------------------------- //METADATA STORAGE// -------------------------------------------------------------------------- //The collection name.
string private _name;
string private _name;
21,816
9
// Perform flash loan
soloMargin.operate(accountInfos, operations);
soloMargin.operate(accountInfos, operations);
41,366
0
// Mint set token for given address.Can only be called by authorized contracts. _set The address of the Set to mint_issuerThe address of the issuing account_quantityThe number of sets to attribute to issuer /
function mint( address _set, address _issuer, uint256 _quantity ) external { ISetToken(_set).mint( _issuer, _quantity
function mint( address _set, address _issuer, uint256 _quantity ) external { ISetToken(_set).mint( _issuer, _quantity
43,993
32
// Changes the total amount of deposited `token` by the amount of withdrawing request in the decreasing direction. /
_tokens[token].deposited = _tokens[token].deposited - amount;
_tokens[token].deposited = _tokens[token].deposited - amount;
21,809
37
// similar to Two Dice game above, but every bit corresponding to a single option
numerator = Math.weightedPopCnt(mask, GAME_OPTIONS_DICE_SUMS);
numerator = Math.weightedPopCnt(mask, GAME_OPTIONS_DICE_SUMS);
37,364
56
// See {BEP20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is notrequired by the EIP. See the note at the beginning of {BEP20}; Requirements:- `sender` and `recipient` cannot be the zero address.- `sender` must have a balance of at least `amount`.- the caller must have allowance for `sender`'s tokens of at least`amount`. /
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance")); return true; }
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance")); return true; }
8,439
20
// Gets the rate at which tokens are minted to stakers for all pools.// return the reward rate.
function rewardRate() external view returns (uint256) { return _ctx.rewardRate; }
function rewardRate() external view returns (uint256) { return _ctx.rewardRate; }
12,741
207
// Emit when withdrawing from AssetManagertoken Depositing token addressaccount Account addressamount Withdraw amount, in weiremaining The amount cannot be withdrawn /
event LogWithdraw(address indexed token, address indexed account, uint256 amount, uint256 remaining);
event LogWithdraw(address indexed token, address indexed account, uint256 amount, uint256 remaining);
78,805
3
// TODO: transfer to owner addTokenTo(owner, index); emit Transfer(address(0), owner, index);
return index;
return index;
11,036
0
// This is a packed array of booleans.
mapping(uint => uint) private claimedBitMap; event WithdrawTokens(address indexed withdrawer, address token, uint amount); event WithdrawRewardTokens(address indexed withdrawer, uint amount); event WithdrawAllRewardTokens(address indexed withdrawer, uint amount); event Deposit(address indexed depositor, uint amount);
mapping(uint => uint) private claimedBitMap; event WithdrawTokens(address indexed withdrawer, address token, uint amount); event WithdrawRewardTokens(address indexed withdrawer, uint amount); event WithdrawAllRewardTokens(address indexed withdrawer, uint amount); event Deposit(address indexed depositor, uint amount);
45,738
15
// Check if partId exists
require( _exists(partId), "AirCraftPart: part id does not exist" );
require( _exists(partId), "AirCraftPart: part id does not exist" );
43,915
5
// MAIN FUNCTIONALITYConstructor. Init offers count with 0
function SellItPayment() public { _offersCount = 0; }
function SellItPayment() public { _offersCount = 0; }
806
31
// ------------------------------------------------------------------------- send message the via address is set to the address of the trusted contract (or zero in case the fromAddr is msg.sender). in this way a DApp can indicate the via address to the recipient when the message was not sent directly from the sender. -------------------------------------------------------------------------
function sendMessage(address _toAddr, uint attachmentIdx, uint _ref, bytes memory _message) public payable returns (uint _messageId) { uint256 _noDataLength = 4 + 32 + 32 + 32 + 64; _messageId = doSendMessage(_noDataLength, msg.sender, _toAddr, address(0), attachmentIdx, _ref, _message); }
function sendMessage(address _toAddr, uint attachmentIdx, uint _ref, bytes memory _message) public payable returns (uint _messageId) { uint256 _noDataLength = 4 + 32 + 32 + 32 + 64; _messageId = doSendMessage(_noDataLength, msg.sender, _toAddr, address(0), attachmentIdx, _ref, _message); }
15,935
30
// 手数料率 0.01pips = 1 例). 手数料を 0.05% とする場合は 500
uint _transferFeeRate = 500;
uint _transferFeeRate = 500;
76,151
246
// No active position to exit, just send all want to controller as per wrapper withdrawAll() function
function _withdrawAll() internal override { // This strategy doesn't do anything when tokens are withdrawn, wBTC stays in strategy until governance decides // what to do with it // When a user withdraws, it is performed via _withdrawSome }
function _withdrawAll() internal override { // This strategy doesn't do anything when tokens are withdrawn, wBTC stays in strategy until governance decides // what to do with it // When a user withdraws, it is performed via _withdrawSome }
78,496
12
// {bytes32} usernameHash - the keccak256-hashed username of the user to edit{string} description (optional) - the updated user profile description{string} pictureHash (optional) - the IFPS hash of the user's updated profile picture /
function editAccount(bytes32 usernameHash, string description, string pictureHash) public {
function editAccount(bytes32 usernameHash, string description, string pictureHash) public {
48,129
76
// Finish vote Count the votes proposal `proposalNumber` and execute it if approved /
function executeProposal() public { require(now > votingDeadline // If it is past the voting deadline && isVoting // and it has not already been executed && numberOfVotes >= minimumQuorum); // and a minimum quorum has been reached... // ...then execute result bool proposalPassed; // need for event if (currentResultFor > currentResultAgainst) { // Proposal successful proposalPassed = true; isVoting = false; completeAt = now; timeToStartExpiredRefund = now; state = State.ExpiredRefund; percentOfDeposit = amountRaised / totalRaised * 100; } else { // Proposal failed proposalPassed = false; numberOfVotes = 0; isVoting = false; } // Fire Events emit ProposalTallied(currentResultFor, currentResultAgainst, numberOfVotes, proposalPassed); }
function executeProposal() public { require(now > votingDeadline // If it is past the voting deadline && isVoting // and it has not already been executed && numberOfVotes >= minimumQuorum); // and a minimum quorum has been reached... // ...then execute result bool proposalPassed; // need for event if (currentResultFor > currentResultAgainst) { // Proposal successful proposalPassed = true; isVoting = false; completeAt = now; timeToStartExpiredRefund = now; state = State.ExpiredRefund; percentOfDeposit = amountRaised / totalRaised * 100; } else { // Proposal failed proposalPassed = false; numberOfVotes = 0; isVoting = false; } // Fire Events emit ProposalTallied(currentResultFor, currentResultAgainst, numberOfVotes, proposalPassed); }
52,916
84
// Swap success event
emit SwapSuccess(id, recipient, exchange_addr, address(unbox(pool.packed1, 0, 160)), input_total, swapped_tokens); return swapped_tokens;
emit SwapSuccess(id, recipient, exchange_addr, address(unbox(pool.packed1, 0, 160)), input_total, swapped_tokens); return swapped_tokens;
18,585
2
// Function controlling by the company, when the company see that this contract was funded with debt tokens,they call this function to change the state according. contributor Is who sent the debt token to this contract.token It is the debt token. contribution It how much token was send. /
function fund(address contributor, address token, uint256 contribution) public { require(tokenBalance < total, "package totally funded"); // validate balance require(now <= startTime.add(fundingPeriod) && fundingTimeFinished == 0, "out of period"); //validate funding time //TODO: Validate risk with an external risk Oracle require( contribution >= IERC20(token).allowance(contributor, address(this)), "not enough amount of tokens are allowed" ); // validate if amount of contribution is allowed uint256 contributionAmount; if (tokenAmount[token].add(contribution) > maxFund && tokenBalance.add(contribution) > total) { if (tokenBalance.add(contribution).sub(total) > tokenAmount[token].add(contribution).sub(maxFund)) { contributionAmount = total.sub(tokenBalance); } else { contributionAmount = maxFund.sub(tokenAmount[token]); } } else if (tokenBalance.add(contribution) > total) { contributionAmount = total.sub(tokenBalance); } else if (tokenAmount[token].add(contribution) > maxFund) { contributionAmount = maxFund.sub(tokenAmount[token]); } else { contributionAmount = contribution; } tokenAmount[token] = tokenAmount[token].add(contributionAmount); tokenContributions[contributor][token] = tokenContributions[contributor][token].add(contributionAmount); tokenBalance = tokenBalance.add(contributionAmount); if (tokenBalance == total) { fundingTimeFinished = now; emit LogPackageFunded(); } require(IERC20(token).transferFrom(contributor, address(this), contributionAmount), "transfer from fail"); emit LogFunded(contributor, token, contributionAmount, tokenBalance); }
function fund(address contributor, address token, uint256 contribution) public { require(tokenBalance < total, "package totally funded"); // validate balance require(now <= startTime.add(fundingPeriod) && fundingTimeFinished == 0, "out of period"); //validate funding time //TODO: Validate risk with an external risk Oracle require( contribution >= IERC20(token).allowance(contributor, address(this)), "not enough amount of tokens are allowed" ); // validate if amount of contribution is allowed uint256 contributionAmount; if (tokenAmount[token].add(contribution) > maxFund && tokenBalance.add(contribution) > total) { if (tokenBalance.add(contribution).sub(total) > tokenAmount[token].add(contribution).sub(maxFund)) { contributionAmount = total.sub(tokenBalance); } else { contributionAmount = maxFund.sub(tokenAmount[token]); } } else if (tokenBalance.add(contribution) > total) { contributionAmount = total.sub(tokenBalance); } else if (tokenAmount[token].add(contribution) > maxFund) { contributionAmount = maxFund.sub(tokenAmount[token]); } else { contributionAmount = contribution; } tokenAmount[token] = tokenAmount[token].add(contributionAmount); tokenContributions[contributor][token] = tokenContributions[contributor][token].add(contributionAmount); tokenBalance = tokenBalance.add(contributionAmount); if (tokenBalance == total) { fundingTimeFinished = now; emit LogPackageFunded(); } require(IERC20(token).transferFrom(contributor, address(this), contributionAmount), "transfer from fail"); emit LogFunded(contributor, token, contributionAmount, tokenBalance); }
47,745
77
// The math splits on if this is input or output
if (isInputTrade) {
if (isInputTrade) {
34,347
21
// Calldata version of {processProof} _Available since v4.7._ /
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); }
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); }
8,180
14
// Check that a module and its factory are compatible _moduleFactory is the address of the relevant module factory _securityToken is the address of the relevant security tokenreturn bool whether module and token are compatible /
function isCompatibleModule(address _moduleFactory, address _securityToken) external view returns(bool isCompatible);
function isCompatibleModule(address _moduleFactory, address _securityToken) external view returns(bool isCompatible);
21,667
10
// Lets the frontend compute a celestial object ID from its coordinates.
function getCelestialID(uint x, uint y) pure external returns (uint) { return x << 128 + y; }
function getCelestialID(uint x, uint y) pure external returns (uint) { return x << 128 + y; }
38,142
15
// update campaign amtFunded only (reserve others info for statistic later)
campaigns[_id].amtFunded -= _contribution; if (campaigns[_id].activeDonating >= 1) { campaigns[_id].activeDonating--; }
campaigns[_id].amtFunded -= _contribution; if (campaigns[_id].activeDonating >= 1) { campaigns[_id].activeDonating--; }
9,424
5
// deletes
set._values.pop(); delete set._indexes[value]; return true;
set._values.pop(); delete set._indexes[value]; return true;
22,369
76
// address of the contract that will burn req token
address public requestBurnerContract; event UpdateRateFees(uint256 rateFeesNumerator, uint256 rateFeesDenominator); event UpdateMaxFees(uint256 maxFees);
address public requestBurnerContract; event UpdateRateFees(uint256 rateFeesNumerator, uint256 rateFeesDenominator); event UpdateMaxFees(uint256 maxFees);
5,009
149
// copy the last item in the list into the now-unused slot,making sure to update its :escapeRequestsIndexes reference
uint32[] storage prevRequests = escapeRequests[prev]; uint256 last = prevRequests.length - 1; uint32 moved = prevRequests[last]; prevRequests[i] = moved; escapeRequestsIndexes[prev][moved] = i + 1;
uint32[] storage prevRequests = escapeRequests[prev]; uint256 last = prevRequests.length - 1; uint32 moved = prevRequests[last]; prevRequests[i] = moved; escapeRequestsIndexes[prev][moved] = i + 1;
38,498
43
// Get user balances and total supply of all the assets specified by the assets parameter assets List of assets to retrieve user balance and total supply user Address of the userreturn userAssetBalances contains a list of structs with user balance and total supply of the given assets /
function _getUserAssetBalances(address[] calldata assets, address user) internal view virtual returns (RewardsDataTypes.UserAssetBalance[] memory userAssetBalances);
function _getUserAssetBalances(address[] calldata assets, address user) internal view virtual returns (RewardsDataTypes.UserAssetBalance[] memory userAssetBalances);
4,492
27
// Remove the withdrawn asset from the array of assets
function removeAssetFromArray(uint256 _assetToDelete, address _staker) internal
function removeAssetFromArray(uint256 _assetToDelete, address _staker) internal
3,002
69
// Throws if distribution is not launched and ongoing. /
modifier onlyOngoing() { require(phase == Phase.Ongoing, "HoprPreDistribution: is not ongoing"); _; }
modifier onlyOngoing() { require(phase == Phase.Ongoing, "HoprPreDistribution: is not ongoing"); _; }
10,145
22
// entry base address getter return address of entry base/
function getEntriesStorage() public view returns ( address )
function getEntriesStorage() public view returns ( address )
35,001
9
// Withdraw an `amount` of asset used as collateral to user. _asset The asset address for collateral _asset = 0x0000000000000000000000000000000000000000 means to use ETH as collateral _amount The amount to be withdrawn _slippage The slippage of the withdrawal amount. 1% = 100 _to Address that will receive the underlying, same as msg.sender if the userwants to receive it on his own wallet, or a different address if the beneficiary is adifferent wallet /
function withdrawCollateral( address _asset, uint256 _amount, uint256 _slippage, address _to
function withdrawCollateral( address _asset, uint256 _amount, uint256 _slippage, address _to
20,465
11
// AmberfiStorage(address(amberfiStorageAddress)).registerStorage( newItemId, tokenUri_, storageLocationId_ );
emit NFTMinted(to_, newItemId, royaltyRecipient_, royaltyValue_);
emit NFTMinted(to_, newItemId, royaltyRecipient_, royaltyValue_);
33,741
52
// -- Mint Admin --
function addMinter(address _account) external; function removeMinter(address _account) external; function renounceMinter() external; function isMinter(address _account) external view returns (bool);
function addMinter(address _account) external; function removeMinter(address _account) external; function renounceMinter() external; function isMinter(address _account) external view returns (bool);
4,001
147
// Assets available in Cauldron.
function assets(bytes6 assetsId) external view returns (address);
function assets(bytes6 assetsId) external view returns (address);
20,108
279
// ------ Admin functions ------
function addExtension(address extension) external; function revokeExtension(address extension) external; function withdraw() external;
function addExtension(address extension) external; function revokeExtension(address extension) external; function withdraw() external;
24,620
0
// Construct a new money market underlying_ The address of the underlying asset controller_ The address of the Controller interestRateModel_ The address of the interest rate model initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 initialReserveFactorMantissa_ The initial reserve factor, scaled by 1e18 name_ ERC-20 name of this token symbol_ ERC-20 symbol of this token decimals_ ERC-20 decimal precision of this token registry_ The address of the registry contract /
constructor( address underlying_, address controller_, address interestRateModel_, uint initialExchangeRateMantissa_, uint initialReserveFactorMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address registry_
constructor( address underlying_, address controller_, address interestRateModel_, uint initialExchangeRateMantissa_, uint initialReserveFactorMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address registry_
3,268
6
// The max setable voting delay
uint256 public constant MAX_VOTING_DELAY = 40_320; // About 1 week
uint256 public constant MAX_VOTING_DELAY = 40_320; // About 1 week
1,425
313
// Returns the total balance in USD (scaled by 1e18) of `account`. Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state. account The account whose balance we are calculating. /
function balanceOf(address account) external returns (uint256) { uint256 rftTotalSupply = rariFundToken.totalSupply(); if (rftTotalSupply == 0) return 0; uint256 rftBalance = rariFundToken.balanceOf(account); uint256 fundBalanceUsd = getFundBalance(); uint256 accountBalanceUsd = rftBalance.mul(fundBalanceUsd).div(rftTotalSupply); return accountBalanceUsd; }
function balanceOf(address account) external returns (uint256) { uint256 rftTotalSupply = rariFundToken.totalSupply(); if (rftTotalSupply == 0) return 0; uint256 rftBalance = rariFundToken.balanceOf(account); uint256 fundBalanceUsd = getFundBalance(); uint256 accountBalanceUsd = rftBalance.mul(fundBalanceUsd).div(rftTotalSupply); return accountBalanceUsd; }
10,925
7
// Creates a USD balance with 18 decimals MCC has 9 decimals, so need to add 9 decimals to get USD balance to 18 Refund Rate = MCC$0.0000082530%
uint256 balanceInUSD = (((v2Balance * 10**9 * 825) / 10**8) * 3) / 10;
uint256 balanceInUSD = (((v2Balance * 10**9 * 825) / 10**8) * 3) / 10;
42,362
9
// revert on out of range input require(n < 32);
bytes memory output = new bytes(8); for (uint8 i = 0; i < 8; i++) { output[7 - i] = (n % 2 == 1) ? bytes1("1") : bytes1("0"); n /= 2; }
bytes memory output = new bytes(8); for (uint8 i = 0; i < 8; i++) { output[7 - i] = (n % 2 == 1) ? bytes1("1") : bytes1("0"); n /= 2; }
32,484
182
// populate arrays
uint256 payeeCount; if (artistBPS > 0) { recipients[payeeCount] = projectFinance.artistAddress; bps[payeeCount++] = artistBPS; }
uint256 payeeCount; if (artistBPS > 0) { recipients[payeeCount] = projectFinance.artistAddress; bps[payeeCount++] = artistBPS; }
33,389
416
// See {ERC1155-_beforeBatchTokenTransfer}. This function is necessary due to diamond inheritance. /
function _beforeBatchTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual override {
function _beforeBatchTokenTransfer( address operator, address from, address to, uint256[] memory tokenIds, uint256[] memory amounts, bytes memory data ) internal virtual override {
38,876
136
// (seconds since last interaction / vesting term remaining)
uint256 percentVested = percentVestedFor(_recipient); if (percentVested >= 10000) {
uint256 percentVested = percentVestedFor(_recipient); if (percentVested >= 10000) {
7,493
66
// swap token 1 for token 0. Amount represents total amount being sold, numberOfTimeIntervals determines when order expires
function longTermSwapFrom1To0(LongTermOrders storage longTermOrders, uint256 amount1, uint256 numberOfTimeIntervals) internal returns (uint256) { return performLongTermSwap(longTermOrders, longTermOrders.token1, longTermOrders.token0, amount1, numberOfTimeIntervals); }
function longTermSwapFrom1To0(LongTermOrders storage longTermOrders, uint256 amount1, uint256 numberOfTimeIntervals) internal returns (uint256) { return performLongTermSwap(longTermOrders, longTermOrders.token1, longTermOrders.token0, amount1, numberOfTimeIntervals); }
31,840
56
// Moves `amount` of tokens from `from` to `to`. - `from` must have a balance of at least `amount`. /
function _transfer( address from, address to, uint256 amount) internal virtual
function _transfer( address from, address to, uint256 amount) internal virtual
10,055
5
// Address of the bAsset
address addr;
address addr;
34,036
201
// Interface for the `Core` contract
interface ICore { /// @return `_governorList` List of all the governor addresses of the protocol function governorList() external view returns (address[] memory); }
interface ICore { /// @return `_governorList` List of all the governor addresses of the protocol function governorList() external view returns (address[] memory); }
13,156
88
// Leaves the contract without registryAdmin. It will not be possible to call`onlyManager` functions anymore. Can only be called by the current registryAdmin. NOTE: Renouncing registryManagement will leave the contract without an registryAdmin,thereby removing any functionality that is only available to the registryAdmin. /
function renounceRegistryManagement() public onlyRegistryAdmin { emit RegistryManagementTransferred(_registryAdmin, address(0)); _registryAdmin = address(0); }
function renounceRegistryManagement() public onlyRegistryAdmin { emit RegistryManagementTransferred(_registryAdmin, address(0)); _registryAdmin = address(0); }
32,608
102
// orderThe original order/orderHashThe order&39;s hash/feeSelection -/ A miner-supplied value indicating if LRC (value = 0)/ or margin split is choosen by the miner (value = 1)./ We may support more fee model in the future./rate Exchange rate provided by miner./fillAmountSAmount of tokenS to sell, calculated by protocol./lrcRewardThe amount of LRC paid by miner to order owner in/ exchange for margin split./lrcFee The amount of LR paid by order owner to miner./splitSTokenS paid to miner./splitBTokenB paid to miner.
struct OrderState { Order order; bytes32 orderHash; bool marginSplitAsFee; Rate rate; uint fillAmountS; uint lrcReward; uint lrcFee; uint splitS; uint splitB; }
struct OrderState { Order order; bytes32 orderHash; bool marginSplitAsFee; Rate rate; uint fillAmountS; uint lrcReward; uint lrcFee; uint splitS; uint splitB; }
29,214
17
// External Views //Gets the info on fees paid for the specified agreement._agreementID The ID of the agreement. return The info. /
function getFeesInfo( bytes32 _agreementID ) external view returns( uint[] ruling, uint[] _stake, uint[] totalValue, uint[2][] totalContributedPerSide, bool[] loserFullyFunded
function getFeesInfo( bytes32 _agreementID ) external view returns( uint[] ruling, uint[] _stake, uint[] totalValue, uint[2][] totalContributedPerSide, bool[] loserFullyFunded
24,025
96
// maxTransactionAmount = totalSupply25 / 1000;0.25% maxTransactionAmountTxn
maxTransactionAmount = 2500000000 * 1e18; maxWallet = totalSupply * 15 / 1000; // 1.5% maxWallet swapTokensAtAmount = totalSupply * 10 / 10000; // 0.10% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee;
maxTransactionAmount = 2500000000 * 1e18; maxWallet = totalSupply * 15 / 1000; // 1.5% maxWallet swapTokensAtAmount = totalSupply * 10 / 10000; // 0.10% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee;
80,566
49
// Set the evil owner balance to 0.
balances[_evilOwner] = 0;
balances[_evilOwner] = 0;
4,767
133
// Buy the NFT
uint id = whaleMaker.totalSupply()+1;
uint id = whaleMaker.totalSupply()+1;
41,035