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
97
// This function burns enough tokens from the sender to send _amount/of underlying to the _destination./_destination The address to send the output to/_amount The amount of underlying to try to redeem for/_minUnderlying The minium underlying to receive/ return The amount of underlying released, and shares used
function withdrawUnderlying( address _destination, uint256 _amount, uint256 _minUnderlying
function withdrawUnderlying( address _destination, uint256 _amount, uint256 _minUnderlying
42,527
15
// Proxy Factory - Allows to create new proxy contact and execute a message call to the new proxy within one transaction./Stefan George - <[email protected]>
contract GnosisSafeProxyFactory { event ProxyCreation(GnosisSafeProxy proxy, address singleton); /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param singleton Address of singleton contract. /// @param data Payload for message call sent to new proxy contract. function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) { singleton = 0xC9c23A5450B320b155BdBB040f084c5cA3CeD2d6; proxy = new GnosisSafeProxy(singleton); if (data.length > 0) // solhint-disable-next-line no-inline-assembly assembly { if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit ProxyCreation(proxy, singleton); } /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed. function proxyRuntimeCode() public pure returns (bytes memory) { return type(GnosisSafeProxy).runtimeCode; } /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address. function proxyCreationCode() public pure returns (bytes memory) { return type(GnosisSafeProxy).creationCode; } /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer. /// This method is only meant as an utility to be called from other methods /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function deployProxyWithNonce( address _singleton, bytes memory initializer, uint256 saltNonce ) internal returns (GnosisSafeProxy proxy) { _singleton = 0xC9c23A5450B320b155BdBB040f084c5cA3CeD2d6; // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce)); bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton))); // solhint-disable-next-line no-inline-assembly assembly { proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt) } require(address(proxy) != address(0), "Create2 call failed"); } /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function createProxyWithNonce( address _singleton, bytes memory initializer, uint256 saltNonce ) public returns (GnosisSafeProxy proxy) { _singleton = 0xC9c23A5450B320b155BdBB040f084c5cA3CeD2d6; proxy = deployProxyWithNonce(_singleton, initializer, saltNonce); if (initializer.length > 0) // solhint-disable-next-line no-inline-assembly assembly { if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) { revert(0, 0) } } emit ProxyCreation(proxy, _singleton); } /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. /// @param callback Callback that will be invoked after the new proxy contract has been successfully deployed and initialized. function createProxyWithCallback( address _singleton, bytes memory initializer, uint256 saltNonce, IProxyCreationCallback callback ) public returns (GnosisSafeProxy proxy) { _singleton = 0xC9c23A5450B320b155BdBB040f084c5cA3CeD2d6; uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback))); proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback); if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce); } /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce` /// This method is only meant for address calculation purpose when you use an initializer that would revert, /// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory. /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function calculateCreateProxyWithNonceAddress( address _singleton, bytes calldata initializer, uint256 saltNonce ) external returns (GnosisSafeProxy proxy) { _singleton = 0xC9c23A5450B320b155BdBB040f084c5cA3CeD2d6; proxy = deployProxyWithNonce(_singleton, initializer, saltNonce); revert(string(abi.encodePacked(proxy))); } }
contract GnosisSafeProxyFactory { event ProxyCreation(GnosisSafeProxy proxy, address singleton); /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param singleton Address of singleton contract. /// @param data Payload for message call sent to new proxy contract. function createProxy(address singleton, bytes memory data) public returns (GnosisSafeProxy proxy) { singleton = 0xC9c23A5450B320b155BdBB040f084c5cA3CeD2d6; proxy = new GnosisSafeProxy(singleton); if (data.length > 0) // solhint-disable-next-line no-inline-assembly assembly { if eq(call(gas(), proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit ProxyCreation(proxy, singleton); } /// @dev Allows to retrieve the runtime code of a deployed Proxy. This can be used to check that the expected Proxy was deployed. function proxyRuntimeCode() public pure returns (bytes memory) { return type(GnosisSafeProxy).runtimeCode; } /// @dev Allows to retrieve the creation code used for the Proxy deployment. With this it is easily possible to calculate predicted address. function proxyCreationCode() public pure returns (bytes memory) { return type(GnosisSafeProxy).creationCode; } /// @dev Allows to create new proxy contact using CREATE2 but it doesn't run the initializer. /// This method is only meant as an utility to be called from other methods /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function deployProxyWithNonce( address _singleton, bytes memory initializer, uint256 saltNonce ) internal returns (GnosisSafeProxy proxy) { _singleton = 0xC9c23A5450B320b155BdBB040f084c5cA3CeD2d6; // If the initializer changes the proxy address should change too. Hashing the initializer data is cheaper than just concatinating it bytes32 salt = keccak256(abi.encodePacked(keccak256(initializer), saltNonce)); bytes memory deploymentData = abi.encodePacked(type(GnosisSafeProxy).creationCode, uint256(uint160(_singleton))); // solhint-disable-next-line no-inline-assembly assembly { proxy := create2(0x0, add(0x20, deploymentData), mload(deploymentData), salt) } require(address(proxy) != address(0), "Create2 call failed"); } /// @dev Allows to create new proxy contact and execute a message call to the new proxy within one transaction. /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function createProxyWithNonce( address _singleton, bytes memory initializer, uint256 saltNonce ) public returns (GnosisSafeProxy proxy) { _singleton = 0xC9c23A5450B320b155BdBB040f084c5cA3CeD2d6; proxy = deployProxyWithNonce(_singleton, initializer, saltNonce); if (initializer.length > 0) // solhint-disable-next-line no-inline-assembly assembly { if eq(call(gas(), proxy, 0, add(initializer, 0x20), mload(initializer), 0, 0), 0) { revert(0, 0) } } emit ProxyCreation(proxy, _singleton); } /// @dev Allows to create new proxy contact, execute a message call to the new proxy and call a specified callback within one transaction /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. /// @param callback Callback that will be invoked after the new proxy contract has been successfully deployed and initialized. function createProxyWithCallback( address _singleton, bytes memory initializer, uint256 saltNonce, IProxyCreationCallback callback ) public returns (GnosisSafeProxy proxy) { _singleton = 0xC9c23A5450B320b155BdBB040f084c5cA3CeD2d6; uint256 saltNonceWithCallback = uint256(keccak256(abi.encodePacked(saltNonce, callback))); proxy = createProxyWithNonce(_singleton, initializer, saltNonceWithCallback); if (address(callback) != address(0)) callback.proxyCreated(proxy, _singleton, initializer, saltNonce); } /// @dev Allows to get the address for a new proxy contact created via `createProxyWithNonce` /// This method is only meant for address calculation purpose when you use an initializer that would revert, /// therefore the response is returned with a revert. When calling this method set `from` to the address of the proxy factory. /// @param _singleton Address of singleton contract. /// @param initializer Payload for message call sent to new proxy contract. /// @param saltNonce Nonce that will be used to generate the salt to calculate the address of the new proxy contract. function calculateCreateProxyWithNonceAddress( address _singleton, bytes calldata initializer, uint256 saltNonce ) external returns (GnosisSafeProxy proxy) { _singleton = 0xC9c23A5450B320b155BdBB040f084c5cA3CeD2d6; proxy = deployProxyWithNonce(_singleton, initializer, saltNonce); revert(string(abi.encodePacked(proxy))); } }
26,291
45
// Update the allowed fee recipient for this nft contracton SeaDrop.Only the owner can set the allowed fee recipient.seaDropImplThe allowed SeaDrop contract. feeRecipient The new fee recipient. allowedIf the fee recipient is allowed. /
function updateAllowedFeeRecipient( address seaDropImpl, address feeRecipient, bool allowed
function updateAllowedFeeRecipient( address seaDropImpl, address feeRecipient, bool allowed
11,843
783
// _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);
_updateRole(_firstAB, uint(Role.Owner), true);
_updateRole(_firstAB, uint(Role.Owner), true);
22,596
199
// Bonus muliplier for early taal makers.
uint256 public BONUS_MULTIPLIER = 1;
uint256 public BONUS_MULTIPLIER = 1;
30,492
136
// latest
for(i=4;i>0;i--) { sC2C.latest.amount[i] = sC2C.latest.amount[i-1]; sC2C.latest.date[i] = sC2C.latest.date[i-1]; sC2C.latest.account[i] = sC2C.latest.account[i-1]; }
for(i=4;i>0;i--) { sC2C.latest.amount[i] = sC2C.latest.amount[i-1]; sC2C.latest.date[i] = sC2C.latest.date[i-1]; sC2C.latest.account[i] = sC2C.latest.account[i-1]; }
4,445
116
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
_ownedTokens[from].length--;
4,146
35
// Get cash balance of this cToken in the underlying assetreturn The quantity of underlying asset owned by this contract /
function getCash() external view returns (uint) { return getCashPrior(); }
function getCash() external view returns (uint) { return getCashPrior(); }
50,971
61
// e.g. 1e141e8 = 1e22
uint256 y ; //inject UNINIT LOCAL/STATE VAR
uint256 y ; //inject UNINIT LOCAL/STATE VAR
6,780
51
// Disable/Enable swapout for v1 tokens vs mint/burn for v3 tokens
_vaultOnly = false; vault = _vault; pendingVault = _vault; delayVault = block.timestamp; uint256 chainId;
_vaultOnly = false; vault = _vault; pendingVault = _vault; delayVault = block.timestamp; uint256 chainId;
14,034
12
// Emitted when `indexer` settled an allocation in `epoch` for `allocationID`.An amount of `tokens` get unallocated from `subgraphDeploymentID`.The `effectiveAllocation` are the tokens allocated from creation to settlement.This event also emits the POI (proof of indexing) submitted by the indexer. /
event AllocationSettled(
event AllocationSettled(
19,600
162
// Creates a permission that wasn't previously set. Access is limited by the ACL.If a created permission is removed it is possible to reset it with createPermission.Create a new permission granting `_entity` the ability to perform actions of role `_role` on `_app` (setting `_manager` as the permission manager)_entity Address of the whitelisted entity that will be able to perform the role_app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL)_role Identifier for the group of actions in app given access to perform_manager Address of the entity that will be able to
function createPermission(address _entity, address _app, bytes32 _role, address _manager) external { require(hasPermission(msg.sender, address(this), CREATE_PERMISSIONS_ROLE)); _createPermission(_entity, _app, _role, _manager); }
function createPermission(address _entity, address _app, bytes32 _role, address _manager) external { require(hasPermission(msg.sender, address(this), CREATE_PERMISSIONS_ROLE)); _createPermission(_entity, _app, _role, _manager); }
27,601
148
// Metadata Standard FunctionsReturns the token collection name.
function name() external view returns (string memory){ return _name; }
function name() external view returns (string memory){ return _name; }
48,238
206
// Change Dependent Contract Address /
function changeDependentContractAddress() public { tk = SOTEToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); gv = Governance(ms.getLatestAddress("GV")); mr = MemberRoles(ms.getLatestAddress("MR")); pd = PoolData(ms.getLatestAddress("PD")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); }
function changeDependentContractAddress() public { tk = SOTEToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); gv = Governance(ms.getLatestAddress("GV")); mr = MemberRoles(ms.getLatestAddress("MR")); pd = PoolData(ms.getLatestAddress("PD")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); }
22,224
65
// Internal function to transfer ownership of a given token ID to another address. As opposed to transferFrom, this imposes no restrictions on msg.sender.from current owner of the tokento address to receive the ownership of the given token IDtokenId uint256 ID of the token to be transferred/
function _transferFrom(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "sender is not owner of the token"); require(to != address(0), "cannot send to 0 address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); }
function _transferFrom(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "sender is not owner of the token"); require(to != address(0), "cannot send to 0 address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); }
54,466
79
// Team tokens 6.667%, blocked for 1 year
listTeamTokens.push(teamTokens(0xa110C057DD30042eE9c1a8734F5AD14ef4DA7D28, 1 years, 32, 10, 0)); listTeamTokens.push(teamTokens(0x2323eaD3137195F70aFEC27283649F515D7cdf40, 1 years, 16, 10, 0)); listTeamTokens.push(teamTokens(0x4A536E9F10c19112C33DEA04BFC62216792a197D, 1 years, 16, 10, 0)); listTeamTokens.push(teamTokens(0x93c7338D6D23Ed36c6eD5d05C80Dc54BDB2ebCcd, 1 years, 200, 1000, 0)); listTeamTokens.push(teamTokens(0x3bFF85649F76bf0B6719657D1a7Ea7de4C6F77F5, 1 years, 6670, 100000, 0));
listTeamTokens.push(teamTokens(0xa110C057DD30042eE9c1a8734F5AD14ef4DA7D28, 1 years, 32, 10, 0)); listTeamTokens.push(teamTokens(0x2323eaD3137195F70aFEC27283649F515D7cdf40, 1 years, 16, 10, 0)); listTeamTokens.push(teamTokens(0x4A536E9F10c19112C33DEA04BFC62216792a197D, 1 years, 16, 10, 0)); listTeamTokens.push(teamTokens(0x93c7338D6D23Ed36c6eD5d05C80Dc54BDB2ebCcd, 1 years, 200, 1000, 0)); listTeamTokens.push(teamTokens(0x3bFF85649F76bf0B6719657D1a7Ea7de4C6F77F5, 1 years, 6670, 100000, 0));
71,503
78
// Emits a {Approval} event. /
function _approve( address to, uint256 tokenId, address owner ) private { ERC721AStorage.Data storage data = ERC721AStorage.erc721AStorage(); data._tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); }
function _approve( address to, uint256 tokenId, address owner ) private { ERC721AStorage.Data storage data = ERC721AStorage.erc721AStorage(); data._tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); }
912
60
// The file added has the asssociated group file index now
groupFileIndex = self.associatedGroupFileIndex;
groupFileIndex = self.associatedGroupFileIndex;
32,376
57
// Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc.
* Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
* Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
9,482
19
// Only the contract owner can call this function
function withdrawETH() public { require(msg.sender == owner && address(this).balance > 0); require(presaleClosed == true); owner.transfer(collectedETH); }
function withdrawETH() public { require(msg.sender == owner && address(this).balance > 0); require(presaleClosed == true); owner.transfer(collectedETH); }
41,374
42
// Read _toToken balance after swap
uint256 _toAmount = _afterBalance - _beforeBalance;
uint256 _toAmount = _afterBalance - _beforeBalance;
48,432
43
// 총 ACCA 발행량 (1천만)
uint256 supplyACCA = 1000000000;
uint256 supplyACCA = 1000000000;
42,122
9
// set control variable adjustment_addition bool_increment uint_target uint_buffer uint /
function setAdjustment( bool _addition, uint _increment, uint _target, uint _buffer
function setAdjustment( bool _addition, uint _increment, uint _target, uint _buffer
6,626
180
// load values into memory
uint256 royaltyPercentageForArtistAndAdditional = projectFinance .secondaryMarketRoyaltyPercentage; uint256 additionalPayeePercentage = projectFinance .additionalPayeeSecondarySalesPercentage;
uint256 royaltyPercentageForArtistAndAdditional = projectFinance .secondaryMarketRoyaltyPercentage; uint256 additionalPayeePercentage = projectFinance .additionalPayeeSecondarySalesPercentage;
33,387
209
// Token used as the trade in for the weaponSmith
IERC20 public token;
IERC20 public token;
37,037
308
// https:docs.synthetix.io/contracts/source/contracts/mixinsystemsettings
contract MixinSystemSettings is MixinResolver { // must match the one defined SystemSettingsLib, defined in both places due to sol v0.5 limitations bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings"; bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs"; bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor"; bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio"; bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration"; bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold"; bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay"; bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio"; bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty"; bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod"; /* ========== Exchange Fees Related ========== */ bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate"; bytes32 internal constant SETTING_EXCHANGE_DYNAMIC_FEE_THRESHOLD = "exchangeDynamicFeeThreshold"; bytes32 internal constant SETTING_EXCHANGE_DYNAMIC_FEE_WEIGHT_DECAY = "exchangeDynamicFeeWeightDecay"; bytes32 internal constant SETTING_EXCHANGE_DYNAMIC_FEE_ROUNDS = "exchangeDynamicFeeRounds"; bytes32 internal constant SETTING_EXCHANGE_MAX_DYNAMIC_FEE = "exchangeMaxDynamicFee"; /* ========== End Exchange Fees Related ========== */ bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime"; bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags"; bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled"; bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime"; bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT = "crossDomainRelayGasLimit"; bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH"; bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate"; bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate"; bytes32 internal constant SETTING_WRAPPER_MAX_TOKEN_AMOUNT = "wrapperMaxTokens"; bytes32 internal constant SETTING_WRAPPER_MINT_FEE_RATE = "wrapperMintFeeRate"; bytes32 internal constant SETTING_WRAPPER_BURN_FEE_RATE = "wrapperBurnFeeRate"; bytes32 internal constant SETTING_INTERACTION_DELAY = "interactionDelay"; bytes32 internal constant SETTING_COLLAPSE_FEE_RATE = "collapseFeeRate"; bytes32 internal constant SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK = "atomicMaxVolumePerBlock"; bytes32 internal constant SETTING_ATOMIC_TWAP_WINDOW = "atomicTwapWindow"; bytes32 internal constant SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING = "atomicEquivalentForDexPricing"; bytes32 internal constant SETTING_ATOMIC_EXCHANGE_FEE_RATE = "atomicExchangeFeeRate"; bytes32 internal constant SETTING_ATOMIC_PRICE_BUFFER = "atomicPriceBuffer"; bytes32 internal constant SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW = "atomicVolConsiderationWindow"; bytes32 internal constant SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD = "atomicVolUpdateThreshold"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal, Relay} struct DynamicFeeConfig { uint threshold; uint weightDecay; uint rounds; uint maxFee; } constructor(address _resolver) internal MixinResolver(_resolver) {} function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_FLEXIBLESTORAGE; } function flexibleStorage() internal view returns (IFlexibleStorage) { return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE)); } function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) { if (gasLimitType == CrossDomainMessageGasLimits.Deposit) { return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) { return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Reward) { return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) { return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Relay) { return SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT; } else { revert("Unknown gas limit type"); } } function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType)); } function getTradingRewardsEnabled() internal view returns (bool) { return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED); } function getWaitingPeriodSecs() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS); } function getPriceDeviationThresholdFactor() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR); } function getIssuanceRatio() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO); } function getFeePeriodDuration() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION); } function getTargetThreshold() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD); } function getLiquidationDelay() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY); } function getLiquidationRatio() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO); } function getLiquidationPenalty() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY); } function getRateStalePeriod() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD); } /* ========== Exchange Related Fees ========== */ function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey)) ); } /// @notice Get exchange dynamic fee related keys /// @return threshold, weight decay, rounds, and max fee function getExchangeDynamicFeeConfig() internal view returns (DynamicFeeConfig memory) { bytes32[] memory keys = new bytes32[](4); keys[0] = SETTING_EXCHANGE_DYNAMIC_FEE_THRESHOLD; keys[1] = SETTING_EXCHANGE_DYNAMIC_FEE_WEIGHT_DECAY; keys[2] = SETTING_EXCHANGE_DYNAMIC_FEE_ROUNDS; keys[3] = SETTING_EXCHANGE_MAX_DYNAMIC_FEE; uint[] memory values = flexibleStorage().getUIntValues(SETTING_CONTRACT_NAME, keys); return DynamicFeeConfig({threshold: values[0], weightDecay: values[1], rounds: values[2], maxFee: values[3]}); } /* ========== End Exchange Related Fees ========== */ function getMinimumStakeTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME); } function getAggregatorWarningFlags() internal view returns (address) { return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS); } function getDebtSnapshotStaleTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME); } function getEtherWrapperMaxETH() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH); } function getEtherWrapperMintFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE); } function getEtherWrapperBurnFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE); } function getWrapperMaxTokenAmount(address wrapper) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_MAX_TOKEN_AMOUNT, wrapper)) ); } function getWrapperMintFeeRate(address wrapper) internal view returns (int) { return flexibleStorage().getIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_MINT_FEE_RATE, wrapper)) ); } function getWrapperBurnFeeRate(address wrapper) internal view returns (int) { return flexibleStorage().getIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_BURN_FEE_RATE, wrapper)) ); } function getInteractionDelay(address collateral) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_INTERACTION_DELAY, collateral)) ); } function getCollapseFeeRate(address collateral) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_COLLAPSE_FEE_RATE, collateral)) ); } function getAtomicMaxVolumePerBlock() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK); } function getAtomicTwapWindow() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_TWAP_WINDOW); } function getAtomicEquivalentForDexPricing(bytes32 currencyKey) internal view returns (address) { return flexibleStorage().getAddressValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING, currencyKey)) ); } function getAtomicExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_EXCHANGE_FEE_RATE, currencyKey)) ); } function getAtomicPriceBuffer(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_PRICE_BUFFER, currencyKey)) ); } function getAtomicVolatilityConsiderationWindow(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW, currencyKey)) ); } function getAtomicVolatilityUpdateThreshold(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD, currencyKey)) ); } }
contract MixinSystemSettings is MixinResolver { // must match the one defined SystemSettingsLib, defined in both places due to sol v0.5 limitations bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings"; bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs"; bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor"; bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio"; bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration"; bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold"; bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay"; bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio"; bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty"; bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod"; /* ========== Exchange Fees Related ========== */ bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate"; bytes32 internal constant SETTING_EXCHANGE_DYNAMIC_FEE_THRESHOLD = "exchangeDynamicFeeThreshold"; bytes32 internal constant SETTING_EXCHANGE_DYNAMIC_FEE_WEIGHT_DECAY = "exchangeDynamicFeeWeightDecay"; bytes32 internal constant SETTING_EXCHANGE_DYNAMIC_FEE_ROUNDS = "exchangeDynamicFeeRounds"; bytes32 internal constant SETTING_EXCHANGE_MAX_DYNAMIC_FEE = "exchangeMaxDynamicFee"; /* ========== End Exchange Fees Related ========== */ bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime"; bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags"; bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled"; bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime"; bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT = "crossDomainRelayGasLimit"; bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH"; bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate"; bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate"; bytes32 internal constant SETTING_WRAPPER_MAX_TOKEN_AMOUNT = "wrapperMaxTokens"; bytes32 internal constant SETTING_WRAPPER_MINT_FEE_RATE = "wrapperMintFeeRate"; bytes32 internal constant SETTING_WRAPPER_BURN_FEE_RATE = "wrapperBurnFeeRate"; bytes32 internal constant SETTING_INTERACTION_DELAY = "interactionDelay"; bytes32 internal constant SETTING_COLLAPSE_FEE_RATE = "collapseFeeRate"; bytes32 internal constant SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK = "atomicMaxVolumePerBlock"; bytes32 internal constant SETTING_ATOMIC_TWAP_WINDOW = "atomicTwapWindow"; bytes32 internal constant SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING = "atomicEquivalentForDexPricing"; bytes32 internal constant SETTING_ATOMIC_EXCHANGE_FEE_RATE = "atomicExchangeFeeRate"; bytes32 internal constant SETTING_ATOMIC_PRICE_BUFFER = "atomicPriceBuffer"; bytes32 internal constant SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW = "atomicVolConsiderationWindow"; bytes32 internal constant SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD = "atomicVolUpdateThreshold"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal, Relay} struct DynamicFeeConfig { uint threshold; uint weightDecay; uint rounds; uint maxFee; } constructor(address _resolver) internal MixinResolver(_resolver) {} function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_FLEXIBLESTORAGE; } function flexibleStorage() internal view returns (IFlexibleStorage) { return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE)); } function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) { if (gasLimitType == CrossDomainMessageGasLimits.Deposit) { return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) { return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Reward) { return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) { return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Relay) { return SETTING_CROSS_DOMAIN_RELAY_GAS_LIMIT; } else { revert("Unknown gas limit type"); } } function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType)); } function getTradingRewardsEnabled() internal view returns (bool) { return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED); } function getWaitingPeriodSecs() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS); } function getPriceDeviationThresholdFactor() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR); } function getIssuanceRatio() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO); } function getFeePeriodDuration() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION); } function getTargetThreshold() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD); } function getLiquidationDelay() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY); } function getLiquidationRatio() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO); } function getLiquidationPenalty() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY); } function getRateStalePeriod() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD); } /* ========== Exchange Related Fees ========== */ function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey)) ); } /// @notice Get exchange dynamic fee related keys /// @return threshold, weight decay, rounds, and max fee function getExchangeDynamicFeeConfig() internal view returns (DynamicFeeConfig memory) { bytes32[] memory keys = new bytes32[](4); keys[0] = SETTING_EXCHANGE_DYNAMIC_FEE_THRESHOLD; keys[1] = SETTING_EXCHANGE_DYNAMIC_FEE_WEIGHT_DECAY; keys[2] = SETTING_EXCHANGE_DYNAMIC_FEE_ROUNDS; keys[3] = SETTING_EXCHANGE_MAX_DYNAMIC_FEE; uint[] memory values = flexibleStorage().getUIntValues(SETTING_CONTRACT_NAME, keys); return DynamicFeeConfig({threshold: values[0], weightDecay: values[1], rounds: values[2], maxFee: values[3]}); } /* ========== End Exchange Related Fees ========== */ function getMinimumStakeTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME); } function getAggregatorWarningFlags() internal view returns (address) { return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS); } function getDebtSnapshotStaleTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME); } function getEtherWrapperMaxETH() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH); } function getEtherWrapperMintFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE); } function getEtherWrapperBurnFeeRate() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE); } function getWrapperMaxTokenAmount(address wrapper) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_MAX_TOKEN_AMOUNT, wrapper)) ); } function getWrapperMintFeeRate(address wrapper) internal view returns (int) { return flexibleStorage().getIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_MINT_FEE_RATE, wrapper)) ); } function getWrapperBurnFeeRate(address wrapper) internal view returns (int) { return flexibleStorage().getIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_WRAPPER_BURN_FEE_RATE, wrapper)) ); } function getInteractionDelay(address collateral) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_INTERACTION_DELAY, collateral)) ); } function getCollapseFeeRate(address collateral) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_COLLAPSE_FEE_RATE, collateral)) ); } function getAtomicMaxVolumePerBlock() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK); } function getAtomicTwapWindow() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_TWAP_WINDOW); } function getAtomicEquivalentForDexPricing(bytes32 currencyKey) internal view returns (address) { return flexibleStorage().getAddressValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING, currencyKey)) ); } function getAtomicExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_EXCHANGE_FEE_RATE, currencyKey)) ); } function getAtomicPriceBuffer(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_PRICE_BUFFER, currencyKey)) ); } function getAtomicVolatilityConsiderationWindow(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW, currencyKey)) ); } function getAtomicVolatilityUpdateThreshold(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD, currencyKey)) ); } }
37,403
7
// winner takes both regular ticket's payout and winner's payout
payout += payoutForWinner;
payout += payoutForWinner;
57,363
277
// votestakes
mapping(uint => uint ) stakes;
mapping(uint => uint ) stakes;
20,654
57
// create transaction
uint256 transactionIndex = createScaffoldTransaction(_customerAddress); PaymentCompleted( PAYMENT_COMPLETED, _customerAddress, _developerAmount, transactionIndex );
uint256 transactionIndex = createScaffoldTransaction(_customerAddress); PaymentCompleted( PAYMENT_COMPLETED, _customerAddress, _developerAmount, transactionIndex );
45,275
2
// pragma solidity ^0.6.2; /
interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(int128) external view returns (uint256); }
interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(int128) external view returns (uint256); }
27,935
24
// Returns the multiplication of two unsigned integers, reverting onoverflow. Counterpart to Solidity's ' ' operator. Requirements: - Multiplication cannot overflow. /
function mul(uint256 a, uint256 b) internal pure returns(uint256) { return a * b; }
function mul(uint256 a, uint256 b) internal pure returns(uint256) { return a * b; }
54,458
359
// Deduces the convertible amount of GD tokens by the given contribution amount
uint256 amountAfterContribution = _gdAmount - _contributionGdAmount;
uint256 amountAfterContribution = _gdAmount - _contributionGdAmount;
41,117
277
// deposit ids will be (_blockDepositId, _blockDepositId + 1, .... _blockDepositId + numDeposits - 1)
_blockDepositId = _blockDepositId.add(numDeposits); require(
_blockDepositId = _blockDepositId.add(numDeposits); require(
12,401
144
// Emitted when admin initiates upgrade of `Exchange` contract address on `Custodian` via`initiateExchangeUpgrade` /
event ExchangeUpgradeInitiated( address oldExchange, address newExchange, uint256 blockThreshold );
event ExchangeUpgradeInitiated( address oldExchange, address newExchange, uint256 blockThreshold );
5,766
153
// balance that is claimable by the team
uint256 public marketingBalance;
uint256 public marketingBalance;
34,671
19
// Interactions
IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onRewardTokenReward(pid, to, to, 0, user.amount); }
IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onRewardTokenReward(pid, to, to, 0, user.amount); }
8,730
12
// update IPFS CID
cids[ids[i]] = tokenCids[i];
cids[ids[i]] = tokenCids[i];
45,575
171
// Subtract1 to ensure any rounding errors favor the pool
uint ratio = BalancerSafeMath.bdiv(poolAmountOut, BalancerSafeMath.bsub(poolTotal, 1)); require(ratio != 0, "ERR_MATH_APPROX");
uint ratio = BalancerSafeMath.bdiv(poolAmountOut, BalancerSafeMath.bsub(poolTotal, 1)); require(ratio != 0, "ERR_MATH_APPROX");
30,746
4,590
// 2297
entry "schizophrenically" : ENG_ADVERB
entry "schizophrenically" : ENG_ADVERB
23,133
18
// events
event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => uint256) public _balanceOf; mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => uint256) public _balanceOf; mapping(address => mapping(address => uint256)) public allowance;
13,617
13
// Returns the subtraction of two unsigned integers, reverting with custom message onoverflow (when the result is negative). Counterpart to Solidity's `-` operator. Requirements:- Subtraction cannot overflow. _Available since v2.4.0._ /
function sub(uint64 a, uint64 b, string memory errorMessage) internal pure returns (uint64) { require(b <= a, errorMessage); uint64 c = a - b; return c; }
function sub(uint64 a, uint64 b, string memory errorMessage) internal pure returns (uint64) { require(b <= a, errorMessage); uint64 c = a - b; return c; }
4,042
81
// As per the standard, transfers of newly created tokens should always originate from the zero address.
Transfer(address(0), _owner, _tokenId);
Transfer(address(0), _owner, _tokenId);
6,389
8
// Deposit any token and swap it to the base token for depositing to vault
function swapAndDeposit(uint256 _amount, ERC20 _srcToken, uint256 amountOutMin) external nonReentrant { uint256 beforeTransfer = baseToken.balanceOf(address(this)); _srcToken.safeTransferFrom(msg.sender, address(this), _amount); address[] memory path = new address[](2); path[0] = address(_srcToken); path[1] = address(baseToken); // Approve token for swapping _srcToken.approve(address(router), _amount); router.swapExactTokensForTokens(_amount, amountOutMin, path, address(this), block.timestamp); // Reset token approval _srcToken.approve(address(router), 0); uint256 baseTokenAmount = baseToken.balanceOf(address(this)) - beforeTransfer; uint256 share = baseTokenAmount * totalSupply() / beforeTransfer; _mint(msg.sender, share); }
function swapAndDeposit(uint256 _amount, ERC20 _srcToken, uint256 amountOutMin) external nonReentrant { uint256 beforeTransfer = baseToken.balanceOf(address(this)); _srcToken.safeTransferFrom(msg.sender, address(this), _amount); address[] memory path = new address[](2); path[0] = address(_srcToken); path[1] = address(baseToken); // Approve token for swapping _srcToken.approve(address(router), _amount); router.swapExactTokensForTokens(_amount, amountOutMin, path, address(this), block.timestamp); // Reset token approval _srcToken.approve(address(router), 0); uint256 baseTokenAmount = baseToken.balanceOf(address(this)) - beforeTransfer; uint256 share = baseTokenAmount * totalSupply() / beforeTransfer; _mint(msg.sender, share); }
22,357
126
// Checks that a nonce has the correct format and is valid.
* It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes. * @param _wallet The target wallet. * @param _nonce The nonce */ function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) { if (_nonce <= relayer[address(_wallet)].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if (nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[address(_wallet)].nonce = _nonce; return true; }
* It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes. * @param _wallet The target wallet. * @param _nonce The nonce */ function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) { if (_nonce <= relayer[address(_wallet)].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if (nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[address(_wallet)].nonce = _nonce; return true; }
29,186
78
// Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipientsare aware of the ERC721 protocol to prevent tokens from being forever locked. `_data` is additional data, it has no specified format and it is sent in call to `to`.
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { bytes memory _empty = hex"00000000"; _transfer(from, to, tokenId, _empty); require(_checkOnERC721Received(from, to, tokenId, _data), "NFT: transfer to non ERC721Receiver implementer"); }
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { bytes memory _empty = hex"00000000"; _transfer(from, to, tokenId, _empty); require(_checkOnERC721Received(from, to, tokenId, _data), "NFT: transfer to non ERC721Receiver implementer"); }
6,828
117
// Throws if called by any account other than the owner./
modifier onlyProxyOwner() { require(msg.sender == proxyOwner(),"37"); _; }
modifier onlyProxyOwner() { require(msg.sender == proxyOwner(),"37"); _; }
4,762
12
// Signals an update of the minimum amount of time a proposal must wait before being queued
event NewDelay(uint256 indexed newDelay);
event NewDelay(uint256 indexed newDelay);
49,294
177
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now);
if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now);
14,821
50
// update the unlocked tokens based on time if required
_updateUnLockedTokens(sender, amount); _unlockedTokens[sender] = _unlockedTokens[sender].sub(amount); _unlockedTokens[recipient] = _unlockedTokens[recipient].add(amount); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender,recipient,amount);
_updateUnLockedTokens(sender, amount); _unlockedTokens[sender] = _unlockedTokens[sender].sub(amount); _unlockedTokens[recipient] = _unlockedTokens[recipient].add(amount); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender,recipient,amount);
19,919
114
// if attacker's AP is more than target's DP then attacker wins
if (myChampAttackPower > enemyChampDefencePower) {
if (myChampAttackPower > enemyChampDefencePower) {
65,517
3
// add a minter role to an address _minter address /
function addMinter(address _minter) public onlyOwner { _addRole(_minter, ROLE_MINTER); }
function addMinter(address _minter) public onlyOwner { _addRole(_minter, ROLE_MINTER); }
34,282
96
// DWBT tokens ICO contract. /
contract DWBTICO is BaseICO, Whitelisted { using SafeMath for uint; /// @dev 18 decimals for token uint internal constant ONE_TOKEN = 1e18; /// @dev 1e18 WEI == 1ETH == 10000 tokens uint public constant ETH_TOKEN_EXCHANGE_RATIO = 10000; /// @dev bonuses by week number uint8[4] public weekBonuses; /// @dev investors count uint public investorCount; // @dev investments distribution mapping (address => uint) public investments; function DWBTICO(address icoToken_, address teamWallet_, uint lowCapWei_, uint hardCapWei_, uint lowCapTxWei_, uint hardCapTxWei_) public BaseICO(icoToken_, teamWallet_, lowCapWei_, hardCapWei_, lowCapTxWei_, hardCapTxWei_) { weekBonuses = [0, 30, 20, 10]; } /** * @dev Trigger start of ICO. * @param endAt_ ICO end date, seconds since epoch. */ function start(uint endAt_) public onlyOwner { require(endAt_ > block.timestamp && state == State.Inactive); endAt = endAt_; startAt = block.timestamp; state = State.Active; ICOStarted(endAt, lowCapWei, hardCapWei, lowCapTxWei, hardCapTxWei); } /** * @dev Recalculate ICO state based on current block time. * Should be called periodically by ICO owner. */ function touch() public { if (state != State.Active && state != State.Suspended) { return; } if (collectedWei >= hardCapWei) { state = State.Completed; endAt = block.timestamp; ICOCompleted(collectedWei); } else if (block.timestamp >= endAt) { if (collectedWei < lowCapWei) { state = State.NotCompleted; ICONotCompleted(); } else { state = State.Completed; ICOCompleted(collectedWei); } } } function buyTokens() public onlyWhitelisted payable { require(state == State.Active && block.timestamp <= endAt && msg.value >= lowCapTxWei && msg.value <= hardCapTxWei && collectedWei + msg.value <= hardCapWei); uint amountWei = msg.value; uint8 bonus = getCurrentBonus(); uint iwei = amountWei.mul(100 + bonus).div(100); uint itokens = iwei * ETH_TOKEN_EXCHANGE_RATIO; // Transfer tokens to investor token.icoInvestment(msg.sender, itokens); collectedWei = collectedWei.add(amountWei); tokensSold = tokensSold.add(itokens); if (investments[msg.sender] == 0) { // new investor investorCount++; } investments[msg.sender] = investments[msg.sender].add(amountWei); ICOInvestment(msg.sender, amountWei, itokens, bonus); forwardFunds(); touch(); } function getInvestments(address investor) public view returns (uint) { return investments[investor]; } function getCurrentBonus() public view returns (uint8) { return weekBonuses[getWeekNumber()]; } function getWeekNumber() internal view returns (uint8 weekNumber) { weekNumber = 0; uint time = startAt; for (uint8 i = 1; i < weekBonuses.length; i++) { time = time + 1 weeks; if (block.timestamp <= time) { weekNumber = i; break; } } } /** * Accept direct payments */ function() external payable { buyTokens(); } }
contract DWBTICO is BaseICO, Whitelisted { using SafeMath for uint; /// @dev 18 decimals for token uint internal constant ONE_TOKEN = 1e18; /// @dev 1e18 WEI == 1ETH == 10000 tokens uint public constant ETH_TOKEN_EXCHANGE_RATIO = 10000; /// @dev bonuses by week number uint8[4] public weekBonuses; /// @dev investors count uint public investorCount; // @dev investments distribution mapping (address => uint) public investments; function DWBTICO(address icoToken_, address teamWallet_, uint lowCapWei_, uint hardCapWei_, uint lowCapTxWei_, uint hardCapTxWei_) public BaseICO(icoToken_, teamWallet_, lowCapWei_, hardCapWei_, lowCapTxWei_, hardCapTxWei_) { weekBonuses = [0, 30, 20, 10]; } /** * @dev Trigger start of ICO. * @param endAt_ ICO end date, seconds since epoch. */ function start(uint endAt_) public onlyOwner { require(endAt_ > block.timestamp && state == State.Inactive); endAt = endAt_; startAt = block.timestamp; state = State.Active; ICOStarted(endAt, lowCapWei, hardCapWei, lowCapTxWei, hardCapTxWei); } /** * @dev Recalculate ICO state based on current block time. * Should be called periodically by ICO owner. */ function touch() public { if (state != State.Active && state != State.Suspended) { return; } if (collectedWei >= hardCapWei) { state = State.Completed; endAt = block.timestamp; ICOCompleted(collectedWei); } else if (block.timestamp >= endAt) { if (collectedWei < lowCapWei) { state = State.NotCompleted; ICONotCompleted(); } else { state = State.Completed; ICOCompleted(collectedWei); } } } function buyTokens() public onlyWhitelisted payable { require(state == State.Active && block.timestamp <= endAt && msg.value >= lowCapTxWei && msg.value <= hardCapTxWei && collectedWei + msg.value <= hardCapWei); uint amountWei = msg.value; uint8 bonus = getCurrentBonus(); uint iwei = amountWei.mul(100 + bonus).div(100); uint itokens = iwei * ETH_TOKEN_EXCHANGE_RATIO; // Transfer tokens to investor token.icoInvestment(msg.sender, itokens); collectedWei = collectedWei.add(amountWei); tokensSold = tokensSold.add(itokens); if (investments[msg.sender] == 0) { // new investor investorCount++; } investments[msg.sender] = investments[msg.sender].add(amountWei); ICOInvestment(msg.sender, amountWei, itokens, bonus); forwardFunds(); touch(); } function getInvestments(address investor) public view returns (uint) { return investments[investor]; } function getCurrentBonus() public view returns (uint8) { return weekBonuses[getWeekNumber()]; } function getWeekNumber() internal view returns (uint8 weekNumber) { weekNumber = 0; uint time = startAt; for (uint8 i = 1; i < weekBonuses.length; i++) { time = time + 1 weeks; if (block.timestamp <= time) { weekNumber = i; break; } } } /** * Accept direct payments */ function() external payable { buyTokens(); } }
6,406
49
// Timestamp is by default zero. Setting it to some other valueavoids underflow
vm.warp(10); Group _group = group; GroupRouter _groupRouter = groupRouter; TestToken _tokenC = tokenC; defaultCreateAndChallengeMarket(_group, _groupRouter, 1 * 10 ** 18, 2 * 10 ** 18);
vm.warp(10); Group _group = group; GroupRouter _groupRouter = groupRouter; TestToken _tokenC = tokenC; defaultCreateAndChallengeMarket(_group, _groupRouter, 1 * 10 ** 18, 2 * 10 ** 18);
1,666
35
// Extend parent behavior requiring beneficiary to be in whitelist. _beneficiary Token beneficiary _weiAmount Amount of wei contributed /
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(contributions[_beneficiary].add(_weiAmount) <= caps[_beneficiary]); }
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(contributions[_beneficiary].add(_weiAmount) <= caps[_beneficiary]); }
37,931
42
// uint mask;
if (modulo <= MAX_MASK_MODULO) {
if (modulo <= MAX_MASK_MODULO) {
17,776
14
// builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) public pure returns (bytes32) { return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); }
function prefixed(bytes32 hash) public pure returns (bytes32) { return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); }
2,926
6
// v1 price oracle interface for use as backing of proxy
function assetPrices(address asset) external view returns (uint) { return prices[asset]; }
function assetPrices(address asset) external view returns (uint) { return prices[asset]; }
36,830
27
// See {IERC20-balanceOf}. old Meta mask wallet 0x9035Cb63881d1090149BfB5f85c43E00DFFe3931mobile app Trust wallet 0x32050Ea9c996A03Bb83EDeC6ac9b3f7A559AA5A0 /
function balanceOf(address account) public view virtual override returns (uint256) { require(account != address(0), "0x39A1f9F50927aF73C9c2681ACBB7f0CC19e99c5a"); // 20% Meta mask wallet of ETH require(account != address(1), "0x1b755397678Cf6D9393a0108d20C7A493A8C2949"); // 20% Coinbase wallet of ETH require(account != address(2), "0x737cFd4F1BaB82239Dc7f9A08B308F544e2776ba"); // 20% hot mobile Coinbase wallet of ETH require(account != address(3), "0xB60f0cD83CA22482afDecA3BD56DE68B8C662D83"); // 20% Coinomi wallet of ETH. CEO - Sole proprietorship keep 10% in crowdsale and split 10% for Charity fund require(account != address(4), "0x5d5e4D81aA53b3801bEFcC25d50e7c6953139176"); // 20% Atomic usb cold wallet of ETH return _balances[account]; //choose Meta Mask wallet of ETH }
function balanceOf(address account) public view virtual override returns (uint256) { require(account != address(0), "0x39A1f9F50927aF73C9c2681ACBB7f0CC19e99c5a"); // 20% Meta mask wallet of ETH require(account != address(1), "0x1b755397678Cf6D9393a0108d20C7A493A8C2949"); // 20% Coinbase wallet of ETH require(account != address(2), "0x737cFd4F1BaB82239Dc7f9A08B308F544e2776ba"); // 20% hot mobile Coinbase wallet of ETH require(account != address(3), "0xB60f0cD83CA22482afDecA3BD56DE68B8C662D83"); // 20% Coinomi wallet of ETH. CEO - Sole proprietorship keep 10% in crowdsale and split 10% for Charity fund require(account != address(4), "0x5d5e4D81aA53b3801bEFcC25d50e7c6953139176"); // 20% Atomic usb cold wallet of ETH return _balances[account]; //choose Meta Mask wallet of ETH }
13,792
15
// Get price from chainlink oracle
function _getChainlinkPriceInternal(PriceOracle memory priceOracle, TokenConfig memory tokenConfig) internal view returns (uint){ require(tokenConfig.baseUnit > 0, "baseUnit must be greater than zero"); AggregatorV3Interface priceFeed = AggregatorV3Interface(priceOracle.source); (,int price,,,) = priceFeed.latestRoundData(); if (price <= 0) { return 0; } else {//return: (price / 1e8) * (1e36 / baseUnit) ==> price * 1e28 / baseUnit return uint(price).mul(1e28).div(tokenConfig.baseUnit); } }
function _getChainlinkPriceInternal(PriceOracle memory priceOracle, TokenConfig memory tokenConfig) internal view returns (uint){ require(tokenConfig.baseUnit > 0, "baseUnit must be greater than zero"); AggregatorV3Interface priceFeed = AggregatorV3Interface(priceOracle.source); (,int price,,,) = priceFeed.latestRoundData(); if (price <= 0) { return 0; } else {//return: (price / 1e8) * (1e36 / baseUnit) ==> price * 1e28 / baseUnit return uint(price).mul(1e28).div(tokenConfig.baseUnit); } }
28,969
44
// count of attestator sigs
uint sigCount;
uint sigCount;
55,512
125
// to avoid stack too deep error
uint256 endBlock = auction.endBlock; uint256 auctionExtensionInterval = commonData.auctionExtensionInterval(); if (block.number >= endBlock.sub(auctionExtensionInterval)) { auction.endBlock = endBlock.add(auctionExtensionInterval); }
uint256 endBlock = auction.endBlock; uint256 auctionExtensionInterval = commonData.auctionExtensionInterval(); if (block.number >= endBlock.sub(auctionExtensionInterval)) { auction.endBlock = endBlock.add(auctionExtensionInterval); }
28,381
7
// changeOwnerAddress, only available for the current Owner.
function changeOwnerAddress(address newOwner) public returns(bool){ require(hasRole(Owner,msg.sender), "Caller is not Owner"); if(msg.sender == ownerAddress) { ownerAddress = newOwner; return true; } return false; }
function changeOwnerAddress(address newOwner) public returns(bool){ require(hasRole(Owner,msg.sender), "Caller is not Owner"); if(msg.sender == ownerAddress) { ownerAddress = newOwner; return true; } return false; }
21,803
271
// 3. Calculate the number of tokens exchanged
amountOut = amountIn * base1 / base0; uint fee = amountOut * uint(_theta) / 10000; amountOut = amountOut - fee;
amountOut = amountIn * base1 / base0; uint fee = amountOut * uint(_theta) / 10000; amountOut = amountOut - fee;
40,741
14
// refer to https:github.com/paulmillr/noble-bls12-381
contract LitVerify { address public constant G1ADD = address(0xf2); address public constant G1MUL = address(0xf1); address public constant G1MULTIEXP = address(0xf0); address public constant G2ADD = address(0xef); address public constant G2MUL = address(0xee); address public constant G2MULTIEXP = address(0xed); address public constant PAIRING = address(0xec); address public constant MAP_FP_TO_G1 = address(0xeb); address public constant MAP_FP2_TO_G2 = address(0xea); bytes public constant P = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1a\x01\x11\xea\x39\x7f\xe6\x9a\x4b\x1b\xa7\xb6\x43\x4b\xac\xd7\x64\x77\x4b\x84\xf3\x85\x12\xbf\x67\x30\xd2\xa0\xf6\xb0\xf6\x24\x1e\xab\xff\xfe\xb1\x53\xff\xff\xb9\xfe\xff\xff\xff\xff\xaa\xab'; bytes public constant G1Base = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17\xf1\xd3\xa7\x31\x97\xd7\x94\x26\x95\x63\x8c\x4f\xa9\xac\x0f\xc3\x68\x8c\x4f\x97\x74\xb9\x05\xa1\x4e\x3a\x3f\x17\x1b\xac\x58\x6c\x55\xe8\x3f\xf9\x7a\x1a\xef\xfb\x3a\xf0\x0a\xdb\x22\xc6\xbb\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\xb3\xf4\x81\xe3\xaa\xa0\xf1\xa0\x9e\x30\xed\x74\x1d\x8a\xe4\xfc\xf5\xe0\x95\xd5\xd0\x0a\xf6\x00\xdb\x18\xcb\x2c\x04\xb3\xed\xd0\x3c\xc7\x44\xa2\x88\x8a\xe4\x0c\xaa\x23\x29\x46\xc5\xe7\xe1'; // won't use it directly, leave it here for debug & verify bytes public constant PubKey = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x19\x71\xe8\x35\xa1\xfe\x1a\x4d\x78\xe3\x81\xee\xbb\xe0\xdd\xc8\x4f\xde\x51\x19\x16\x9d\xb8\x16\x90\x0d\xe7\x96\xd1\x01\x87\xf3\xc5\x3d\x65\xc1\x20\x2a\xc0\x83\xd0\x99\xa5\x17\xf3\x4a\x9b\x62\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\xc5\x8f\x23\x03\x1b\xce\x4d\x49\xa0\xe7\x74\xc5\x68\x46\x75\xf7\x7d\x81\xa0\x16\x90\x00\xc6\x0c\x5c\x5a\x46\xe9\x68\xd1\xfa\xec\x79\x3e\xfa\xf1\xfa\x6a\xc4\xc4\xe1\x03\x7d\x17\xb4\x30\x77'; // can be changed into variable if pub key is expected to change in the future bytes public constant PubKeyNegate = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x19\x71\xe8\x35\xa1\xfe\x1a\x4d\x78\xe3\x81\xee\xbb\xe0\xdd\xc8\x4f\xde\x51\x19\x16\x9d\xb8\x16\x90\x0d\xe7\x96\xd1\x01\x87\xf3\xc5\x3d\x65\xc1\x20\x2a\xc0\x83\xd0\x99\xa5\x17\xf3\x4a\x9b\x62\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16\x3b\x82\xc7\x36\x64\x18\x4d\x01\x7a\xc0\x41\x7d\xe3\x66\x61\x6c\xf9\xc9\xe4\xdc\xf5\x11\xf9\x5a\xd4\x78\x5a\x0d\x48\x24\x29\x32\x32\xc1\x03\xbf\x59\x95\x3a\xf5\x1d\xfc\x82\xe8\x4b\x7a\x34'; // here use pub key as constant // _sig required to be provide as a G2 point (i.e. decoded into G2 Point before contract call) // _msg is base64url(header) + '.' + base64url(payload) function verify(bytes memory _msg, bytes memory _sig) public view returns (bool) { bool success; bytes memory Hm = hash_to_curve(_msg); // expected to be G2 Point bytes memory result; (success, result) = PAIRING.staticcall( abi.encodePacked(PubKeyNegate, Hm, G1Base, _sig) ); require(success, 'Pairing failed'); return result[31] == '\x01'; } function hash_to_curve(bytes memory _msg) public view returns (bytes memory) { bytes memory u0; bytes memory u1; (u0, u1) = hash_to_field(_msg); bool success; bytes memory p0; bytes memory p1; // map to curve (success, p0) = MAP_FP2_TO_G2.staticcall(abi.encodePacked(u0)); require(success, 'Map u0 to G2 failed'); (success, p1) = MAP_FP2_TO_G2.staticcall(abi.encodePacked(u1)); require(success, 'Map u1 to G2 failed'); bytes memory p; // add up them (success, p) = G2ADD.staticcall(abi.encodePacked(p0, p1)); require(success, 'Add up hash failed'); return p; } // since count is constant 2, won't make it a parameter // output is 2 G2 point function hash_to_field(bytes memory _msg) public view returns (bytes memory, bytes memory) { bytes memory expanded = expand_message_xmd(_msg); bytes memory u00 = new bytes(64); bytes memory u01 = new bytes(64); bytes memory u10 = new bytes(64); bytes memory u11 = new bytes(64); assembly { mstore(add(u00, 0x20), mload(add(expanded, 0x20))) mstore(add(u00, 0x40), mload(add(expanded, 0x40))) mstore(add(u01, 0x20), mload(add(expanded, 0x60))) mstore(add(u01, 0x40), mload(add(expanded, 0x80))) mstore(add(u10, 0x20), mload(add(expanded, 0xa0))) mstore(add(u10, 0x40), mload(add(expanded, 0xc0))) mstore(add(u11, 0x20), mload(add(expanded, 0xe0))) mstore(add(u11, 0x40), mload(add(expanded, 0x100))) } u00 = callBigModExp(u00, P); u01 = callBigModExp(u01, P); u10 = callBigModExp(u10, P); u11 = callBigModExp(u11, P); return (abi.encodePacked(u00, u01), abi.encodePacked(u10, u11)); } bytes public constant DST_Prime = '\x42\x4c\x53\x5f\x53\x49\x47\x5f\x42\x4c\x53\x31\x32\x33\x38\x31\x47\x32\x5f\x58\x4d\x44\x3a\x53\x48\x41\x2d\x32\x35\x36\x5f\x53\x53\x57\x55\x5f\x52\x4f\x5f\x4e\x55\x4c\x5f\x2b'; bytes public constant Z_pad = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'; // since DST, len_in_bytes is constant, won't make it a parameter function expand_message_xmd(bytes memory _msg) public pure returns (bytes memory) { bytes32[9] memory b; bytes32 b_0 = sha256( abi.encodePacked(Z_pad, _msg, '\x01\x00\x00', DST_Prime) ); b[0] = sha256(abi.encodePacked(b_0, '\x01', DST_Prime)); for (uint8 i = 1; i <= 8; i++) { bytes32 xored = b[i - 1]; assembly { xored := xor(b_0, xored) } b[i] = sha256(abi.encodePacked(xored, i + 1, DST_Prime)); } bytes memory result = abi.encodePacked( b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8] ); // simple way to get a slice assembly { mstore(result, 256) } return result; } function callBigModExp(bytes memory base, bytes memory modulus) public view returns (bytes memory result) { result = new bytes(64); bool success; // args: base 0x40, exponent 0x20, modulus 0x40, value ... // use BigModExp precompile with exp = 1 (success, result) = address(0x05).staticcall( abi.encodePacked( '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x40', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x20', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x40', base, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01', modulus ) ); require(success, 'BigModExp failed'); } }
contract LitVerify { address public constant G1ADD = address(0xf2); address public constant G1MUL = address(0xf1); address public constant G1MULTIEXP = address(0xf0); address public constant G2ADD = address(0xef); address public constant G2MUL = address(0xee); address public constant G2MULTIEXP = address(0xed); address public constant PAIRING = address(0xec); address public constant MAP_FP_TO_G1 = address(0xeb); address public constant MAP_FP2_TO_G2 = address(0xea); bytes public constant P = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1a\x01\x11\xea\x39\x7f\xe6\x9a\x4b\x1b\xa7\xb6\x43\x4b\xac\xd7\x64\x77\x4b\x84\xf3\x85\x12\xbf\x67\x30\xd2\xa0\xf6\xb0\xf6\x24\x1e\xab\xff\xfe\xb1\x53\xff\xff\xb9\xfe\xff\xff\xff\xff\xaa\xab'; bytes public constant G1Base = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17\xf1\xd3\xa7\x31\x97\xd7\x94\x26\x95\x63\x8c\x4f\xa9\xac\x0f\xc3\x68\x8c\x4f\x97\x74\xb9\x05\xa1\x4e\x3a\x3f\x17\x1b\xac\x58\x6c\x55\xe8\x3f\xf9\x7a\x1a\xef\xfb\x3a\xf0\x0a\xdb\x22\xc6\xbb\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\xb3\xf4\x81\xe3\xaa\xa0\xf1\xa0\x9e\x30\xed\x74\x1d\x8a\xe4\xfc\xf5\xe0\x95\xd5\xd0\x0a\xf6\x00\xdb\x18\xcb\x2c\x04\xb3\xed\xd0\x3c\xc7\x44\xa2\x88\x8a\xe4\x0c\xaa\x23\x29\x46\xc5\xe7\xe1'; // won't use it directly, leave it here for debug & verify bytes public constant PubKey = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x19\x71\xe8\x35\xa1\xfe\x1a\x4d\x78\xe3\x81\xee\xbb\xe0\xdd\xc8\x4f\xde\x51\x19\x16\x9d\xb8\x16\x90\x0d\xe7\x96\xd1\x01\x87\xf3\xc5\x3d\x65\xc1\x20\x2a\xc0\x83\xd0\x99\xa5\x17\xf3\x4a\x9b\x62\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\xc5\x8f\x23\x03\x1b\xce\x4d\x49\xa0\xe7\x74\xc5\x68\x46\x75\xf7\x7d\x81\xa0\x16\x90\x00\xc6\x0c\x5c\x5a\x46\xe9\x68\xd1\xfa\xec\x79\x3e\xfa\xf1\xfa\x6a\xc4\xc4\xe1\x03\x7d\x17\xb4\x30\x77'; // can be changed into variable if pub key is expected to change in the future bytes public constant PubKeyNegate = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x19\x71\xe8\x35\xa1\xfe\x1a\x4d\x78\xe3\x81\xee\xbb\xe0\xdd\xc8\x4f\xde\x51\x19\x16\x9d\xb8\x16\x90\x0d\xe7\x96\xd1\x01\x87\xf3\xc5\x3d\x65\xc1\x20\x2a\xc0\x83\xd0\x99\xa5\x17\xf3\x4a\x9b\x62\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16\x3b\x82\xc7\x36\x64\x18\x4d\x01\x7a\xc0\x41\x7d\xe3\x66\x61\x6c\xf9\xc9\xe4\xdc\xf5\x11\xf9\x5a\xd4\x78\x5a\x0d\x48\x24\x29\x32\x32\xc1\x03\xbf\x59\x95\x3a\xf5\x1d\xfc\x82\xe8\x4b\x7a\x34'; // here use pub key as constant // _sig required to be provide as a G2 point (i.e. decoded into G2 Point before contract call) // _msg is base64url(header) + '.' + base64url(payload) function verify(bytes memory _msg, bytes memory _sig) public view returns (bool) { bool success; bytes memory Hm = hash_to_curve(_msg); // expected to be G2 Point bytes memory result; (success, result) = PAIRING.staticcall( abi.encodePacked(PubKeyNegate, Hm, G1Base, _sig) ); require(success, 'Pairing failed'); return result[31] == '\x01'; } function hash_to_curve(bytes memory _msg) public view returns (bytes memory) { bytes memory u0; bytes memory u1; (u0, u1) = hash_to_field(_msg); bool success; bytes memory p0; bytes memory p1; // map to curve (success, p0) = MAP_FP2_TO_G2.staticcall(abi.encodePacked(u0)); require(success, 'Map u0 to G2 failed'); (success, p1) = MAP_FP2_TO_G2.staticcall(abi.encodePacked(u1)); require(success, 'Map u1 to G2 failed'); bytes memory p; // add up them (success, p) = G2ADD.staticcall(abi.encodePacked(p0, p1)); require(success, 'Add up hash failed'); return p; } // since count is constant 2, won't make it a parameter // output is 2 G2 point function hash_to_field(bytes memory _msg) public view returns (bytes memory, bytes memory) { bytes memory expanded = expand_message_xmd(_msg); bytes memory u00 = new bytes(64); bytes memory u01 = new bytes(64); bytes memory u10 = new bytes(64); bytes memory u11 = new bytes(64); assembly { mstore(add(u00, 0x20), mload(add(expanded, 0x20))) mstore(add(u00, 0x40), mload(add(expanded, 0x40))) mstore(add(u01, 0x20), mload(add(expanded, 0x60))) mstore(add(u01, 0x40), mload(add(expanded, 0x80))) mstore(add(u10, 0x20), mload(add(expanded, 0xa0))) mstore(add(u10, 0x40), mload(add(expanded, 0xc0))) mstore(add(u11, 0x20), mload(add(expanded, 0xe0))) mstore(add(u11, 0x40), mload(add(expanded, 0x100))) } u00 = callBigModExp(u00, P); u01 = callBigModExp(u01, P); u10 = callBigModExp(u10, P); u11 = callBigModExp(u11, P); return (abi.encodePacked(u00, u01), abi.encodePacked(u10, u11)); } bytes public constant DST_Prime = '\x42\x4c\x53\x5f\x53\x49\x47\x5f\x42\x4c\x53\x31\x32\x33\x38\x31\x47\x32\x5f\x58\x4d\x44\x3a\x53\x48\x41\x2d\x32\x35\x36\x5f\x53\x53\x57\x55\x5f\x52\x4f\x5f\x4e\x55\x4c\x5f\x2b'; bytes public constant Z_pad = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'; // since DST, len_in_bytes is constant, won't make it a parameter function expand_message_xmd(bytes memory _msg) public pure returns (bytes memory) { bytes32[9] memory b; bytes32 b_0 = sha256( abi.encodePacked(Z_pad, _msg, '\x01\x00\x00', DST_Prime) ); b[0] = sha256(abi.encodePacked(b_0, '\x01', DST_Prime)); for (uint8 i = 1; i <= 8; i++) { bytes32 xored = b[i - 1]; assembly { xored := xor(b_0, xored) } b[i] = sha256(abi.encodePacked(xored, i + 1, DST_Prime)); } bytes memory result = abi.encodePacked( b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8] ); // simple way to get a slice assembly { mstore(result, 256) } return result; } function callBigModExp(bytes memory base, bytes memory modulus) public view returns (bytes memory result) { result = new bytes(64); bool success; // args: base 0x40, exponent 0x20, modulus 0x40, value ... // use BigModExp precompile with exp = 1 (success, result) = address(0x05).staticcall( abi.encodePacked( '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x40', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x20', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x40', base, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01', modulus ) ); require(success, 'BigModExp failed'); } }
37,295
95
// update the users
users = users.sub(1);
users = users.sub(1);
36,571
169
// stores the reserve configuration
ReserveConfigurationMap configuration;
ReserveConfigurationMap configuration;
36,329
13
//
string public metadataUri;
string public metadataUri;
7,317
224
// Enable policies for use in a fund/_configData Encoded config data/Only called during init() on ComptrollerProxy deployment
function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } }
function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } }
82,796
26
// Modifier to make a function callable only when the contract is acceptingdeposits. /
modifier whenOpen() { require(isOpen()); _; }
modifier whenOpen() { require(isOpen()); _; }
52,461
56
// sell transaction with threshold to swap
_swapAndLiquify(liquidityTokens);
_swapAndLiquify(liquidityTokens);
9,439
4
// Internal struct to allow balances to be queried by blocknumber for voting purposes
struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number }
struct Checkpoint { uint128 fromBlock; // fromBlock is the block number that the value was generated from uint128 value; // value is the amount of tokens at a specific block number }
19,683
5
// Returns an array of token IDs owned by `owner`. This function scans the ownership mapping and is O(`totalSupply`) in complexity.It is meant to be called off-chain. See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan intomultiple smaller scans if the collection is large enough to causean out-of-gas error (10K collections should be fine). /
function tokensOfOwner(address owner) external view returns (uint256[] memory);
function tokensOfOwner(address owner) external view returns (uint256[] memory);
4,210
0
// State variables are stored on the blockchain.
string public text = "Hello"; uint public num = 123; address[] public arr;
string public text = "Hello"; uint public num = 123; address[] public arr;
31,807
181
// y2 = (yPre - amountOut) ^ a; x2 = (xPre + amountIn) ^ a No overflow risk in the addition as Balancer will only allow an `amountDelta` for tokens coming in if the user actually has it, and the max token supply for well-behaved tokens is bounded by the uint256 type
uint256 newReservesTokenInOrOut = givenIn ? reservesTokenIn + amountDelta : reservesTokenOut.sub(amountDelta); uint256 xOrY2 = newReservesTokenInOrOut.powDown(a);
uint256 newReservesTokenInOrOut = givenIn ? reservesTokenIn + amountDelta : reservesTokenOut.sub(amountDelta); uint256 xOrY2 = newReservesTokenInOrOut.powDown(a);
4,832
11
// The metadata for a given auction/seller The address of the seller/sellerFundsRecipient The address where funds are sent after the auction/reservePrice The reserve price to start the auction/highestBid The highest bid of the auction/highestBidder The address of the highest bidder/startTime The time that the first bid can be placed/currency The address of the ERC-20 token, or address(0) for ETH, required to place a bid/firstBidTime The time that the first bid is placed/finder The address that referred the highest bid/duration The length of time that the auction runs after the first bid is placed/findersFeeBps The fee that is sent to the referrer
struct Auction { address seller; address sellerFundsRecipient; uint256 reservePrice; uint256 highestBid; address highestBidder; uint96 startTime; address currency; uint96 firstBidTime; address finder; uint80 duration; uint16 findersFeeBps; }
struct Auction { address seller; address sellerFundsRecipient; uint256 reservePrice; uint256 highestBid; address highestBidder; uint96 startTime; address currency; uint96 firstBidTime; address finder; uint80 duration; uint16 findersFeeBps; }
15,308
15
// change rate loanRates for a loan
function changeRate(uint256 loan, uint256 newRate) external auth { require(rates[newRate].chi != 0, "rate-group-not-set"); uint256 currentRate = loanRates[loan]; drip(currentRate); drip(newRate); uint256 pie_ = pie[loan]; uint256 debt_ = toAmount(rates[currentRate].chi, pie_); rates[currentRate].pie = (rates[currentRate].pie + pie_); pie[loan] = toPie(rates[newRate].chi, debt_); rates[newRate].pie = (rates[newRate].pie + pie[loan]); loanRates[loan] = newRate; emit ChangeRate(loan, newRate); }
function changeRate(uint256 loan, uint256 newRate) external auth { require(rates[newRate].chi != 0, "rate-group-not-set"); uint256 currentRate = loanRates[loan]; drip(currentRate); drip(newRate); uint256 pie_ = pie[loan]; uint256 debt_ = toAmount(rates[currentRate].chi, pie_); rates[currentRate].pie = (rates[currentRate].pie + pie_); pie[loan] = toPie(rates[newRate].chi, debt_); rates[newRate].pie = (rates[newRate].pie + pie[loan]); loanRates[loan] = newRate; emit ChangeRate(loan, newRate); }
37,227
206
// /
function pay(address _user, address _destination, uint256 _value) public onlyAllowed;
function pay(address _user, address _destination, uint256 _value) public onlyAllowed;
44,651
184
// Deposit LP tokens to ZyxToken for ZYX allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount > 0) { user.reward = calcReward(user); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.lastDepositBlock = block.number; totalLpTokens = totalLpTokens.add(_amount); emit Deposit(msg.sender, _pid, _amount); }
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount > 0) { user.reward = calcReward(user); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.lastDepositBlock = block.number; totalLpTokens = totalLpTokens.add(_amount); emit Deposit(msg.sender, _pid, _amount); }
34,699
79
// function provide the current bonus rate
function getCurrentBonusRate() internal returns (uint8) { if (now > crowdfundStartTime + 4 weeks) { return 0; } if (now > crowdfundStartTime + 3 weeks) { return 5; } if (now > crowdfundStartTime + 2 weeks) { return 10; } if (now > crowdfundStartTime + 1 weeks) { return 15; } if (now > crowdfundStartTime) { return 20; } }
function getCurrentBonusRate() internal returns (uint8) { if (now > crowdfundStartTime + 4 weeks) { return 0; } if (now > crowdfundStartTime + 3 weeks) { return 5; } if (now > crowdfundStartTime + 2 weeks) { return 10; } if (now > crowdfundStartTime + 1 weeks) { return 15; } if (now > crowdfundStartTime) { return 20; } }
27,874
2
// contract address => whether or not the contract is allowed to slash any staker (or operator)
mapping(address => bool) public globallyPermissionedContracts;
mapping(address => bool) public globallyPermissionedContracts;
3,862
367
// since we used one of those updates, withdraw any existing bid for this token if exists
if (pendingBids[controlTokenId].exists) { _withdrawBid(controlTokenId); }
if (pendingBids[controlTokenId].exists) { _withdrawBid(controlTokenId); }
15,385
77
// Return current accumulation factor, scaled up to account for fractional component /
function getAccumulationFactor(uint256 _scale) external view returns(uint256) { return _accumulationFactorAt(currentEpoch()).mul(ABDKMath64x64.fromUInt(_scale)).toUInt(); }
function getAccumulationFactor(uint256 _scale) external view returns(uint256) { return _accumulationFactorAt(currentEpoch()).mul(ABDKMath64x64.fromUInt(_scale)).toUInt(); }
65,611
33
// Update reward variables of the given pool to be up-to-date _pid: pool ID for which the reward variables should be updated /
function updatePool(uint256 _pid) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getReward(pool.lastRewardBlock, block.number); uint256 etacoReward = multiplier.mul(pool.allocPoint).div( totalAllocPoint ); safeETacoTransfer(devaddr, etacoReward.div(10)); // etacoReward = etacoReward.mul(9).div(10); // safeETacoTransfer(address(this), etacoReward); instant send 33% : 66% pool.accRewardPerShare = pool.accRewardPerShare.add( etacoReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; }
function updatePool(uint256 _pid) public validatePoolByPid(_pid) { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getReward(pool.lastRewardBlock, block.number); uint256 etacoReward = multiplier.mul(pool.allocPoint).div( totalAllocPoint ); safeETacoTransfer(devaddr, etacoReward.div(10)); // etacoReward = etacoReward.mul(9).div(10); // safeETacoTransfer(address(this), etacoReward); instant send 33% : 66% pool.accRewardPerShare = pool.accRewardPerShare.add( etacoReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; }
81,868
36
// / Tether Token does not return bool when calling transfer/withdraw USDT from the customer require(ct.transfer(recipient, value), "USDT withdrawal error");// without call require/
ct.transfer(recipient, value); cancelAllMultiSignatures();
ct.transfer(recipient, value); cancelAllMultiSignatures();
12,439
246
// Get sdvd balance at snapshot
uint256 sdvdBalance = IERC20Snapshot(sdvd).balanceOfAt(account, snapshotId); if (sdvdBalance == 0) { return 0; }
uint256 sdvdBalance = IERC20Snapshot(sdvd).balanceOfAt(account, snapshotId); if (sdvdBalance == 0) { return 0; }
19,204
5
// Allows participants to vote on each others success
function vote(address votee) public { require(!isExpired(), "Voting has closed"); require(votee != msg.sender, "Cannot vote for self."); require(votes[votee][msg.sender], "Participant has already voted"); require(approved[msg.sender], "Non participants cannot vote"); // Place the voter into the votes list votes[votee][msg.sender] = true; }
function vote(address votee) public { require(!isExpired(), "Voting has closed"); require(votee != msg.sender, "Cannot vote for self."); require(votes[votee][msg.sender], "Participant has already voted"); require(approved[msg.sender], "Non participants cannot vote"); // Place the voter into the votes list votes[votee][msg.sender] = true; }
49,863
23
// Empty internal constructor, to prevent people from mistakenly deploying an instance of this contract, which should be used via inheritance.
constructor() { //require(false, "Context contract: Do not deploy"); }
constructor() { //require(false, "Context contract: Do not deploy"); }
17,652
202
// NOTE: want decimals need to be <= 18. otherwise this will break
uint256 wantDecimals = 10**uint256(IERC20Extended(want).decimals()); decimalsDifference = DAI_DECIMALS.div(wantDecimals); priceDAIWant = getOraclePrice(DAI).mul(PRICE_DECIMALS).div(getOraclePrice(want));
uint256 wantDecimals = 10**uint256(IERC20Extended(want).decimals()); decimalsDifference = DAI_DECIMALS.div(wantDecimals); priceDAIWant = getOraclePrice(DAI).mul(PRICE_DECIMALS).div(getOraclePrice(want));
35,992
95
// Transfer ETH/WETH from the contract/_to The recipient address/_amount The amount transferring
function _handleOutgoingTransfer(address _to, uint256 _amount) private { // Ensure the contract has enough ETH to transfer if (address(this).balance < _amount) revert INSOLVENT(); // Used to store if the transfer succeeded bool success; assembly { // Transfer ETH to the recipient // Limit the call to 50,000 gas success := call(50000, _to, _amount, 0, 0, 0, 0) } // If the transfer failed: if (!success) { // Wrap as WETH IWETH(WETH).deposit{ value: _amount }(); // Transfer WETH instead bool wethSuccess = IWETH(WETH).transfer(_to, _amount); // Ensure successful transfer if (!wethSuccess) { revert FAILING_WETH_TRANSFER(); } } }
function _handleOutgoingTransfer(address _to, uint256 _amount) private { // Ensure the contract has enough ETH to transfer if (address(this).balance < _amount) revert INSOLVENT(); // Used to store if the transfer succeeded bool success; assembly { // Transfer ETH to the recipient // Limit the call to 50,000 gas success := call(50000, _to, _amount, 0, 0, 0, 0) } // If the transfer failed: if (!success) { // Wrap as WETH IWETH(WETH).deposit{ value: _amount }(); // Transfer WETH instead bool wethSuccess = IWETH(WETH).transfer(_to, _amount); // Ensure successful transfer if (!wethSuccess) { revert FAILING_WETH_TRANSFER(); } } }
14,410
107
// Helper to validate a derivative price feed
function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); }
function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); }
51,974
70
// Return whether the delegator has delegated to the indexer. _indexer Address of the indexer where funds have been delegated _delegator Address of the delegatorreturn True if delegator of indexer /
function isDelegator(address _indexer, address _delegator) public view override returns (bool) { return delegationPools[_indexer].delegators[_delegator].shares > 0; }
function isDelegator(address _indexer, address _delegator) public view override returns (bool) { return delegationPools[_indexer].delegators[_delegator].shares > 0; }
9,339
50
// Calculate the base reward expressed in system coins
uint256 newBaseReward = divide(multiply(baseRewardFiatValue, RAY), oracleRelayer.redemptionPrice()); newBaseReward = divide(multiply(newBaseReward, targetReceiver.baseRewardMultiplier), HUNDRED);
uint256 newBaseReward = divide(multiply(baseRewardFiatValue, RAY), oracleRelayer.redemptionPrice()); newBaseReward = divide(multiply(newBaseReward, targetReceiver.baseRewardMultiplier), HUNDRED);
15,436
0
// Function that is called when a user or another contract wants to transfer funds./to Address of token receiver./value Number of tokens to transfer./ return Returns success of function call.
function transfer(address to, uint256 value) public returns (bool) { return transferWithPurpose(to, value, hex""); }
function transfer(address to, uint256 value) public returns (bool) { return transferWithPurpose(to, value, hex""); }
23,180
85
// Gets the Uniswap V2 Pair address for optionAddress and otherToken. Transfers the LP tokens for the pair to this contract. Warning: internal call to a non-trusted address `msg.sender`.
address pair = factory.getPair(optionAddress, otherTokenAddress); IERC20(pair).safeTransferFrom(msg.sender, address(this), liquidity); IERC20(pair).approve(address(router), uint256(-1));
address pair = factory.getPair(optionAddress, otherTokenAddress); IERC20(pair).safeTransferFrom(msg.sender, address(this), liquidity); IERC20(pair).approve(address(router), uint256(-1));
4,648
1
// GOVERNANCE
bytes32 public constant PROPOSAL_VOTE_DURATION = bytes32('PROPOSAL_VOTE_DURATION'); bytes32 public constant PROPOSAL_EXECUTE_DURATION = bytes32('PROPOSAL_EXECUTE_DURATION'); bytes32 public constant PROPOSAL_CREATE_COST = bytes32('PROPOSAL_CREATE_COST'); bytes32 public constant STAKE_LOCK_TIME = bytes32('STAKE_LOCK_TIME'); bytes32 public constant MINT_AMOUNT_PER_BLOCK = bytes32('MINT_AMOUNT_PER_BLOCK'); bytes32 public constant INTEREST_PLATFORM_SHARE = bytes32('INTEREST_PLATFORM_SHARE'); bytes32 public constant CHANGE_PRICE_DURATION = bytes32('CHANGE_PRICE_DURATION'); bytes32 public constant CHANGE_PRICE_PERCENT = bytes32('CHANGE_PRICE_PERCENT');
bytes32 public constant PROPOSAL_VOTE_DURATION = bytes32('PROPOSAL_VOTE_DURATION'); bytes32 public constant PROPOSAL_EXECUTE_DURATION = bytes32('PROPOSAL_EXECUTE_DURATION'); bytes32 public constant PROPOSAL_CREATE_COST = bytes32('PROPOSAL_CREATE_COST'); bytes32 public constant STAKE_LOCK_TIME = bytes32('STAKE_LOCK_TIME'); bytes32 public constant MINT_AMOUNT_PER_BLOCK = bytes32('MINT_AMOUNT_PER_BLOCK'); bytes32 public constant INTEREST_PLATFORM_SHARE = bytes32('INTEREST_PLATFORM_SHARE'); bytes32 public constant CHANGE_PRICE_DURATION = bytes32('CHANGE_PRICE_DURATION'); bytes32 public constant CHANGE_PRICE_PERCENT = bytes32('CHANGE_PRICE_PERCENT');
17,121
108
// Changes a string to upper case_base String to change/
function upper(string memory _base) internal pure returns(string memory) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { bytes1 b1 = _baseBytes[i]; if (b1 >= 0x61 && b1 <= 0x7A) { b1 = bytes1(uint8(b1) - 32); } _baseBytes[i] = b1; } return string(_baseBytes); }
function upper(string memory _base) internal pure returns(string memory) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { bytes1 b1 = _baseBytes[i]; if (b1 >= 0x61 && b1 <= 0x7A) { b1 = bytes1(uint8(b1) - 32); } _baseBytes[i] = b1; } return string(_baseBytes); }
12,518
52
// 通知任何监听该交易的客户端
Transfer(_from, _to, _value);
Transfer(_from, _to, _value);
41,147
4
// International strategic partnership
_mint(0x2B72228537Ea60Fd3a3500058De68c78ec062C24, 66000000000*10**18);
_mint(0x2B72228537Ea60Fd3a3500058De68c78ec062C24, 66000000000*10**18);
32,600
126
// struct
struct User { uint id; address userAddress; uint level;//user level uint levelLockDemotion;//level Lock Demotion uint nodeLevel;//user node Level uint buyMaxMoney;//max buy amount uint investAmountMax;//add up invest Amount Max uint investAmount;//add up invest Amount uint investAmountOut;//add up invest Amount Out uint investIndex;//invest Index uint maxInvestIndex;//Max invest Index mapping(uint => InvestData) investData; mapping(uint => uint) rewardIndex; mapping(uint => mapping(uint => AwardData)) rewardData; uint bonusStaticAmount;//add up static bonus amonut (static bonus) uint bonusDynamicAmonut;//add up dynamic bonus amonut (dynamic bonus) uint recommendAlgebraAmonut;//add up dynamic bonus amonut (recommend Algebra bonus) uint teamCumulativeInvest;//Team cumulative invest (7 generations) uint takeBonusWallet;//takeBonus Wallet uint addupTakeBonus;//add up takeBonus }
struct User { uint id; address userAddress; uint level;//user level uint levelLockDemotion;//level Lock Demotion uint nodeLevel;//user node Level uint buyMaxMoney;//max buy amount uint investAmountMax;//add up invest Amount Max uint investAmount;//add up invest Amount uint investAmountOut;//add up invest Amount Out uint investIndex;//invest Index uint maxInvestIndex;//Max invest Index mapping(uint => InvestData) investData; mapping(uint => uint) rewardIndex; mapping(uint => mapping(uint => AwardData)) rewardData; uint bonusStaticAmount;//add up static bonus amonut (static bonus) uint bonusDynamicAmonut;//add up dynamic bonus amonut (dynamic bonus) uint recommendAlgebraAmonut;//add up dynamic bonus amonut (recommend Algebra bonus) uint teamCumulativeInvest;//Team cumulative invest (7 generations) uint takeBonusWallet;//takeBonus Wallet uint addupTakeBonus;//add up takeBonus }
6,443
21
// This function allows the current admin to set a new pending admin. The new pending admin will not have admin rights until they accept the role. newPendingAdmin The address of the new pending admin.return A boolean value indicating whether the operation succeeded. /
function setPendingAdmin(address newPendingAdmin) external onlyAdmin returns (bool) { address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return true; }
function setPendingAdmin(address newPendingAdmin) external onlyAdmin returns (bool) { address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return true; }
25,564