Unnamed: 0
int64
0
7.36k
comments
stringlengths
3
35.2k
code_string
stringlengths
1
527k
code
stringlengths
1
527k
__index_level_0__
int64
0
88.6k
16
// we need special dummy bridge to skip 0 position in array
Bridge memory bridge = Bridge({ bridgeStatus : BridgeStatus.Disabled, // don't allow to use this bridge bridgeType : BridgeType.Lockable, // bridge type doesn't matter fromToken : IERC20Mintable(0), // zero tokens which are not exist toToken : IERC20Mintable(0), fromChain : 0x00, // zero chains which are not exist too toChain : 0x00 });
Bridge memory bridge = Bridge({ bridgeStatus : BridgeStatus.Disabled, // don't allow to use this bridge bridgeType : BridgeType.Lockable, // bridge type doesn't matter fromToken : IERC20Mintable(0), // zero tokens which are not exist toToken : IERC20Mintable(0), fromChain : 0x00, // zero chains which are not exist too toChain : 0x00 });
29,665
43
// add a new approver only admin can perform this function
function addApprover(address newApprover) external onlyAdmin { require(!approvers[newApprover]); approvers[newApprover] = true; approverArr.push(newApprover); }
function addApprover(address newApprover) external onlyAdmin { require(!approvers[newApprover]); approvers[newApprover] = true; approverArr.push(newApprover); }
26,805
67
// Checks if rounding error > 0.1%./numerator Numerator./denominator Denominator./target Value to multiply with numerator/denominator./ return Rounding error is present.
function isRoundingError(uint numerator, uint denominator, uint target) public constant returns (bool)
function isRoundingError(uint numerator, uint denominator, uint target) public constant returns (bool)
40,511
124
// Minimum IVs for stats.0: ATK1: DEF 2: AGL3: LUK 4: HP.
uint32[5] minIVForStats;
uint32[5] minIVForStats;
38,532
0
// Core
address public timelock_address;
address public timelock_address;
4,169
194
// Sale must NOT be enabled
require(!sale, "Sale already in progress"); require(presale,"Presale must be active"); require(quantity != 0, "Requested quantity cannot be zero"); require(quantity * pricePer <= msg.value, "Not enough ether sent"); require(super.totalSupply() + quantity <= maxPreMint, "Purchase would exceed max tokens for presale"); require(minted[msg.sender] + quantity <= maxWallet, "Purchase would exceed max tokens per wallet"); require(!Address.isContract(msg.sender), "Contracts are not allowed to mint"); for (uint256 i = 0; i < quantity; i++) { _safeMint(to, _tokenIdCounter.current()); _tokenIdCounter.increment();
require(!sale, "Sale already in progress"); require(presale,"Presale must be active"); require(quantity != 0, "Requested quantity cannot be zero"); require(quantity * pricePer <= msg.value, "Not enough ether sent"); require(super.totalSupply() + quantity <= maxPreMint, "Purchase would exceed max tokens for presale"); require(minted[msg.sender] + quantity <= maxWallet, "Purchase would exceed max tokens per wallet"); require(!Address.isContract(msg.sender), "Contracts are not allowed to mint"); for (uint256 i = 0; i < quantity; i++) { _safeMint(to, _tokenIdCounter.current()); _tokenIdCounter.increment();
9,605
1
// Initialize curve parameters _curveA Constabt A of a curve _curveB Constant B of a curve /
function initialize(uint256 _curveA, uint256 _curveB) public initializer { _setCurveParams(_curveA, _curveB); }
function initialize(uint256 _curveA, uint256 _curveB) public initializer { _setCurveParams(_curveA, _curveB); }
22,773
60
// Call other view functions in handler logic contract. (delegatecall does not work for view functions)data The encoded value of the function and argument return The result of the call/
function handlerViewProxy(bytes memory data) external returns (bool, bytes memory)
function handlerViewProxy(bytes memory data) external returns (bool, bytes memory)
49,516
15
// Total number of tokens in circulation
uint256 public totalSupply = 100_000_000e18; ILocker public locker; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; mapping(address => address) public delegates;
uint256 public totalSupply = 100_000_000e18; ILocker public locker; mapping(address => mapping(address => uint96)) internal allowances; mapping(address => uint96) internal balances; mapping(address => address) public delegates;
11,574
280
// Option One: All the tokens sell at the ICO price.
tokensToSellAtICOPrice = _tokens;
tokensToSellAtICOPrice = _tokens;
24,419
13
// 實際總額為此 contract 的 balance 與已經提領數量的總和
uint totalMined = this.balance + totalWithdrew;
uint totalMined = this.balance + totalWithdrew;
12,936
77
// Allow FlipperMom to access to the RENBTC-A Flipper
FlipAbstract(MCD_FLIP_RENBTC_A).rely(FLIPPER_MOM);
FlipAbstract(MCD_FLIP_RENBTC_A).rely(FLIPPER_MOM);
35,079
42
// Called by the DAO Agent to set the minimum APR/_minApr Minimum APR
function setMinApr(uint256 _minApr) external override onlyAgentApp()
function setMinApr(uint256 _minApr) external override onlyAgentApp()
16,295
8
// require amount greter than 0
require(balance > 0, "staking balance cannot be 0");
require(balance > 0, "staking balance cannot be 0");
14,979
133
// solhint-disable-next-line function-max-lines, code-complexity
function rebalanceAndAddLiquidityETH( IGUniPool pool, uint256 amount0In, uint256 amount1In, bool zeroForOne, uint256 swapAmount, uint160 swapThreshold, uint256 amount0Min, uint256 amount1Min, address receiver
function rebalanceAndAddLiquidityETH( IGUniPool pool, uint256 amount0In, uint256 amount1In, bool zeroForOne, uint256 swapAmount, uint160 swapThreshold, uint256 amount0Min, uint256 amount1Min, address receiver
38,882
152
// _exchangeIdx The private data exchange index/_encryptedDataKey The data symmetric key XORed with the exchange key
function acceptPrivateDataExchange(uint256 _exchangeIdx, bytes32 _encryptedDataKey) external payable { require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index"); PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx]; require(msg.sender == exchange.passportOwner, "only passport owner allowed"); require(PrivateDataExchangeState.Proposed == exchange.state, "exchange must be in proposed state"); require(msg.value >= exchange.dataRequesterValue, "need to stake at least data requester amount"); require(_nowSeconds() < exchange.stateExpired, "exchange state expired"); exchange.passportOwnerValue = msg.value; exchange.encryptedDataKey = _encryptedDataKey; exchange.state = PrivateDataExchangeState.Accepted; exchange.stateExpired = _nowSeconds() + privateDataExchangeAcceptTimeout; emit PrivateDataExchangeAccepted(_exchangeIdx, exchange.dataRequester, msg.sender); }
function acceptPrivateDataExchange(uint256 _exchangeIdx, bytes32 _encryptedDataKey) external payable { require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index"); PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx]; require(msg.sender == exchange.passportOwner, "only passport owner allowed"); require(PrivateDataExchangeState.Proposed == exchange.state, "exchange must be in proposed state"); require(msg.value >= exchange.dataRequesterValue, "need to stake at least data requester amount"); require(_nowSeconds() < exchange.stateExpired, "exchange state expired"); exchange.passportOwnerValue = msg.value; exchange.encryptedDataKey = _encryptedDataKey; exchange.state = PrivateDataExchangeState.Accepted; exchange.stateExpired = _nowSeconds() + privateDataExchangeAcceptTimeout; emit PrivateDataExchangeAccepted(_exchangeIdx, exchange.dataRequester, msg.sender); }
81,998
4
// Generic call for crosschain views with no parameters and returning an Uint256./
function crosschainViewUint256(uint256 sidechainId, address addr, bytes memory encodedFunctionCall) internal view returns (uint256) { bytes memory dataBytes = abi.encode(sidechainId, addr, encodedFunctionCall); uint256 dataBytesRawLength = calculateRawLength(dataBytes); uint256[1] memory result; uint256 resultLength = LENGTH_OF_UINT256; address a = PRECOMPILE_SUBORDINATE_VIEW; assembly { if iszero(staticcall(not(0), a, dataBytes, dataBytesRawLength, result, resultLength)) { revert(0, 0) } } return result[0]; }
function crosschainViewUint256(uint256 sidechainId, address addr, bytes memory encodedFunctionCall) internal view returns (uint256) { bytes memory dataBytes = abi.encode(sidechainId, addr, encodedFunctionCall); uint256 dataBytesRawLength = calculateRawLength(dataBytes); uint256[1] memory result; uint256 resultLength = LENGTH_OF_UINT256; address a = PRECOMPILE_SUBORDINATE_VIEW; assembly { if iszero(staticcall(not(0), a, dataBytes, dataBytesRawLength, result, resultLength)) { revert(0, 0) } } return result[0]; }
48,306
132
// method that returns BIOP amount sold by curve/
function continuousSupply() public override view returns (uint) { return soldAmount; }
function continuousSupply() public override view returns (uint) { return soldAmount; }
19,332
3
// Ties the adventure erc721 _afterTokenTransfer hook to more granular transfer validation logic
function _afterTokenTransfer( address from, address to, uint256 firstTokenId,
function _afterTokenTransfer( address from, address to, uint256 firstTokenId,
7,580
5
// Rescales a fraction to prevent overflows during addition if either/the numerator or the denominator are > 2127./numerator The numerator./denominator The denominator./ return scaledNumerator The rescaled numerator./ return scaledDenominator The rescaled denominator.
function normalize(uint256 numerator, uint256 denominator) internal pure returns (uint256 scaledNumerator, uint256 scaledDenominator)
function normalize(uint256 numerator, uint256 denominator) internal pure returns (uint256 scaledNumerator, uint256 scaledDenominator)
13,210
31
// decide whether to continue or terminate
if (_hasMultiplePools) { _payer = address(this); // at this point, the caller has paid _bytesPath = _bytesPath.skipToken(); } else {
if (_hasMultiplePools) { _payer = address(this); // at this point, the caller has paid _bytesPath = _bytesPath.skipToken(); } else {
16,485
14
// Increment the current id for the next puzzle.
currentId += 1; emit PuzzleCreated(currentId - 1, uniqueId); return currentId - 1;
currentId += 1; emit PuzzleCreated(currentId - 1, uniqueId); return currentId - 1;
34,325
100
// Events // SGN constructor Need to deploy Staking contract first before deploying SGN contract _staking address of Staking Contract /
constructor(Staking _staking) { staking = _staking; }
constructor(Staking _staking) { staking = _staking; }
42,597
566
// Stakes tokens into a pool.//_poolIdthe pool to deposit tokens into./_depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _deposit(_poolId, _depositAmount); }
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _deposit(_poolId, _depositAmount); }
53,704
13
// `usr` operator access was revoked. usr The user address. /
event Nope(address indexed usr);
event Nope(address indexed usr);
47,341
145
// View rewards for a given ticket, providing a bracket, and lottery id Computations are mostly offchain. This is used to verify a ticket! _lotteryId: lottery id _ticketId: ticket id _bracket: bracket for the ticketId to verify the claim and calculate rewards /
function viewRewardsForTicketId( uint256 _lotteryId, uint256 _ticketId, uint32 _bracket
function viewRewardsForTicketId( uint256 _lotteryId, uint256 _ticketId, uint32 _bracket
10,133
10
// Emitted when a module is registered/module The address of the module
event ModuleRegistered(address indexed module);
event ModuleRegistered(address indexed module);
26,889
2
// Total amount of vouched tokens
uint256 private _totalVouched;
uint256 private _totalVouched;
53,274
1
// Sales Control Variables
bool internal sale; bool public publicSale; bool public preSale; uint256 internal uriChange; //2FA Variable to keep count so as to ensure the baseURI can only be updated once// uint256 internal freeMinted;
bool internal sale; bool public publicSale; bool public preSale; uint256 internal uriChange; //2FA Variable to keep count so as to ensure the baseURI can only be updated once// uint256 internal freeMinted;
25,671
170
// cant exceed wl mint limits
uint _wlMaxAmount = config.wlMaxAmount; require( quantity <= _wlMaxAmount, "can not mint this many" );
uint _wlMaxAmount = config.wlMaxAmount; require( quantity <= _wlMaxAmount, "can not mint this many" );
48,723
17
// function setCooldown(uint16 index, uint32 newCooldown) public onlyOwner
{ cooldowns[index] = newCooldown; }*/
{ cooldowns[index] = newCooldown; }*/
11,517
63
// uint d = activedtime - sysday;
if(allprize[p][0] > allprize[p][1]){ uint dd = gettoday(); if(!my[user].hascountprice[dd]){ ps = (allprize[p][0] - allprize[p][1])/leveldata[p]; }
if(allprize[p][0] > allprize[p][1]){ uint dd = gettoday(); if(!my[user].hascountprice[dd]){ ps = (allprize[p][0] - allprize[p][1])/leveldata[p]; }
8,604
1
// Interface for contracts using VRF randomness PURPOSEReggie the Random Oracle (not his real job) wants to provide randomness to Vera the verifier in such a way that Vera can be sure he's not making his output up to suit himself. Reggie provides Vera a public key to which he knows the secret key. Each time Vera provides a seed to Reggie, he gives back a value which is computed completely deterministically from the seed and the secret key.Reggie provides a proof by which Vera can verify that the output was correctly computed once Reggie tells it to her, but without
* @dev contract VRFConsumer { * @dev constructor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator) public { * @dev <initialization with other arguments goes here> * @dev } * @dev }
* @dev contract VRFConsumer { * @dev constructor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator) public { * @dev <initialization with other arguments goes here> * @dev } * @dev }
34,543
8
// `mint` but with `minter`, `fee`, `nonce`, and `sig` as extra parameters.`fee` is a mint fee amount in Gluwacoin, which the minter will pay for the mint.`sig` is a signature created by signing the mint information with the minter’s private key.Anyone can initiate the mint for the minter by calling the Etherless Mint functionwith the mint information and the signature.The caller will have to pay the gas for calling the function. Transfers `amount` + `fee` of base tokens from the minter to the contract using `transferFrom`.Creates `amount` + `fee` of tokens to the minter and transfers `fee` tokens to the caller.
* See {ERC20-_mint} and {ERC20-allowance}. * * Requirements: * * - the minter must have base tokens of at least `amount` + `fee`. * - the contract must have allowance for receiver's base tokens of at least `amount` + `fee`. */ function mint(address minter, uint256 amount, uint256 fee, uint256 nonce, bytes calldata sig) external { _useWrapperNonce(minter, nonce); bytes32 hash = keccak256(abi.encodePacked(GluwacoinModel.SigDomain.Mint, block.chainid, address(this), minter, amount, fee, nonce)); Validate.validateSignature(hash, minter, sig); __mint(minter, amount); address wrapper = getRoleMember(WRAPPER_ROLE, 0); _transfer(minter, wrapper, fee); }
* See {ERC20-_mint} and {ERC20-allowance}. * * Requirements: * * - the minter must have base tokens of at least `amount` + `fee`. * - the contract must have allowance for receiver's base tokens of at least `amount` + `fee`. */ function mint(address minter, uint256 amount, uint256 fee, uint256 nonce, bytes calldata sig) external { _useWrapperNonce(minter, nonce); bytes32 hash = keccak256(abi.encodePacked(GluwacoinModel.SigDomain.Mint, block.chainid, address(this), minter, amount, fee, nonce)); Validate.validateSignature(hash, minter, sig); __mint(minter, amount); address wrapper = getRoleMember(WRAPPER_ROLE, 0); _transfer(minter, wrapper, fee); }
52,855
11
// returns the product of multiplying _x by _y, reverts if the calculation overflows_x factor 1_y factor 2 return product/
function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y); return z; }
function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y); return z; }
54,254
91
// Normalize the currency.
uint256 _value; if (_data.amount.currency == pricingCurrency) _value = _data.amount.value; else if (prices != IJBPrices(address(0))) _value = PRBMath.mulDiv( _data.amount.value, 10**pricingDecimals, prices.priceFor(_data.amount.currency, pricingCurrency, _data.amount.decimals) ); else return;
uint256 _value; if (_data.amount.currency == pricingCurrency) _value = _data.amount.value; else if (prices != IJBPrices(address(0))) _value = PRBMath.mulDiv( _data.amount.value, 10**pricingDecimals, prices.priceFor(_data.amount.currency, pricingCurrency, _data.amount.decimals) ); else return;
25,329
10
// Index of the next NFT reserved for team members.
uint256 internal teamPointer = 0;
uint256 internal teamPointer = 0;
4,775
19
// Appends a byte array to the end of the buffer. Resizes if doing sowould exceed the capacity of the buffer._buf The buffer to append to._data The data to append. return The original buffer./
function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; }
function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; }
24,046
17
// Deposits tokens in proportion to the Optimizer's current ticks. amount0Desired Max amount of token0 to deposit amount1Desired Max amount of token1 to deposit to address that plp should be transferedreturn shares mintedreturn amount0 Amount of token0 depositedreturn amount1 Amount of token1 deposited /
function deposit(uint256 amount0Desired, uint256 amount1Desired, address to) external returns (uint256 shares, uint256 amount0,uint256 amount1);
function deposit(uint256 amount0Desired, uint256 amount1Desired, address to) external returns (uint256 shares, uint256 amount0,uint256 amount1);
6,638
38
// Disable a chain bridge /
function disableBridge(uint16 chainId) external onlyOwner { _bridgeChains[chainId] = false; }
function disableBridge(uint16 chainId) external onlyOwner { _bridgeChains[chainId] = false; }
27,900
85
// - checks version to determine if a block has merge mining information
function isMergeMined(bytes memory _rawBytes, uint pos) private pure returns (bool) { return bytesToUint32Flipped(_rawBytes, pos) & VERSION_AUXPOW != 0; }
function isMergeMined(bytes memory _rawBytes, uint pos) private pure returns (bool) { return bytesToUint32Flipped(_rawBytes, pos) & VERSION_AUXPOW != 0; }
48,667
49
// Underlying
UnderlyingInfo underlyingInfo;
UnderlyingInfo underlyingInfo;
36,057
108
// Pay back to user
uint256 originalAmount = _lendingAmounts[index][msg.sender]; _usdtContract.transfer(msg.sender, originalAmount); _redeemed[index][msg.sender] = true; emit Redeem(msg.sender, originalAmount, index);
uint256 originalAmount = _lendingAmounts[index][msg.sender]; _usdtContract.transfer(msg.sender, originalAmount); _redeemed[index][msg.sender] = true; emit Redeem(msg.sender, originalAmount, index);
35,245
338
// Calculate protocol's fees
uint256 earnedProtocolFees0 = collect0.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); uint256 earnedProtocolFees1 = collect1.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); protocolFees0 = protocolFees0.add(earnedProtocolFees0); protocolFees1 = protocolFees1.add(earnedProtocolFees1); totalFees0 = totalFees0.add(collect0); totalFees1 = totalFees1.add(collect1); emit CollectFees(collect0, collect1, totalFees0, totalFees1);
uint256 earnedProtocolFees0 = collect0.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); uint256 earnedProtocolFees1 = collect1.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); protocolFees0 = protocolFees0.add(earnedProtocolFees0); protocolFees1 = protocolFees1.add(earnedProtocolFees1); totalFees0 = totalFees0.add(collect0); totalFees1 = totalFees1.add(collect1); emit CollectFees(collect0, collect1, totalFees0, totalFees1);
2,860
126
// estimates margin exposure for simulated position/loanToken address of the loan token/collateralToken address of collateral token/loanTokenSent amout of loan token sent/collateralTokenSent amount of collateral token sent/interestRate yearly interest rate/newPrincipal principal amount of the loan/ return estimated margin exposure amount
function getEstimatedMarginExposure( address loanToken, address collateralToken, uint256 loanTokenSent, uint256 collateralTokenSent, uint256 interestRate, uint256 newPrincipal ) external view returns (uint256);
function getEstimatedMarginExposure( address loanToken, address collateralToken, uint256 loanTokenSent, uint256 collateralTokenSent, uint256 interestRate, uint256 newPrincipal ) external view returns (uint256);
64,337
29
// solhint-disable no-unused-vars
function onERC721BatchReceived( address, // operator, address, // from, uint256[] calldata, // ids, bytes calldata // data
function onERC721BatchReceived( address, // operator, address, // from, uint256[] calldata, // ids, bytes calldata // data
25,795
13
// Emitted when a new SASHIMI speed is calculated for a market
event SashimiSpeedUpdated(SLToken indexed slToken, uint newSpeed);
event SashimiSpeedUpdated(SLToken indexed slToken, uint newSpeed);
7,475
242
// onlyOwner will prevent this contract from initializing, since it's owner is going to be 0x0 address
function initialize( uint256 _validatorId, address _stakingLogger, address _stakeManager
function initialize( uint256 _validatorId, address _stakingLogger, address _stakeManager
12,589
17
// Dev
ambassadors_[0x524Fe720F321F57645BBA5d1815b03C26D20Fb16] = true;
ambassadors_[0x524Fe720F321F57645BBA5d1815b03C26D20Fb16] = true;
44,536
28
// Withdraw ether from this contract, callable by shareholder /
function withdrawShareholder() external { require(msg.sender == shareholderAddress, "Only Shareholder"); uint256 balance = address(this).balance; uint256 availableToWithdraw = ((balance + withdrawnByOwner + withdrawnByShareholder) * SHAREHOLDER_PERCENTAGE / 100) - withdrawnByShareholder; require(availableToWithdraw > 0, "Nothing to withdraw"); withdrawnByShareholder += availableToWithdraw; payable(msg.sender).transfer(availableToWithdraw); }
function withdrawShareholder() external { require(msg.sender == shareholderAddress, "Only Shareholder"); uint256 balance = address(this).balance; uint256 availableToWithdraw = ((balance + withdrawnByOwner + withdrawnByShareholder) * SHAREHOLDER_PERCENTAGE / 100) - withdrawnByShareholder; require(availableToWithdraw > 0, "Nothing to withdraw"); withdrawnByShareholder += availableToWithdraw; payable(msg.sender).transfer(availableToWithdraw); }
25,626
33
// Return the log in base 10, rounded down, of a positive value.Returns 0 if given 0. /
function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10**64) { value /= 10**64; result += 64; } if (value >= 10**32) { value /= 10**32; result += 32; } if (value >= 10**16) { value /= 10**16; result += 16; } if (value >= 10**8) { value /= 10**8; result += 8; } if (value >= 10**4) { value /= 10**4; result += 4; } if (value >= 10**2) { value /= 10**2; result += 2; } if (value >= 10**1) { result += 1; } } return result; }
function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10**64) { value /= 10**64; result += 64; } if (value >= 10**32) { value /= 10**32; result += 32; } if (value >= 10**16) { value /= 10**16; result += 16; } if (value >= 10**8) { value /= 10**8; result += 8; } if (value >= 10**4) { value /= 10**4; result += 4; } if (value >= 10**2) { value /= 10**2; result += 2; } if (value >= 10**1) { result += 1; } } return result; }
13,269
79
// Override to extend the way in which ether is converted to tokens. weiAmount Value in wei to be converted into tokensreturn Number of tokens that can be purchased with the specified _weiAmount /
function _getRYNmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); }
function _getRYNmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); }
5,732
7
// Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. /
function revokeRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
4,675
3
// Sets the creator information for a specific token id. Requirements: - `creator` cannot be a zero address. /
function _setTokenCreator( uint256 tokenId, address creator
function _setTokenCreator( uint256 tokenId, address creator
41,003
9
// "Order(address trader,address broker,address perpetual,uint256 amount,uint256 price,bytes32 data)" hash these 6 field to get a hash address will be extended to 32 bytes.
let start := sub(order, 32) let tmp := mload(start) mstore(start, orderType)
let start := sub(order, 32) let tmp := mload(start) mstore(start, orderType)
38,333
1
// Defines needed variables
uint public ticketPrice; uint public roundDuration; // saved in seconds uint public nextWinnerPickedTime;
uint public ticketPrice; uint public roundDuration; // saved in seconds uint public nextWinnerPickedTime;
32,952
79
// Total amount of project's token sold: must be updated every time tokens has been sold
uint256 public totalSold;
uint256 public totalSold;
41,489
29
// constructor
function VirtualGift()
function VirtualGift()
54,496
0
// DAI Address: 0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD ADAI Address: 0x58AD4cB396411B691A9AAb6F74545b2C5217FE6a Lending Pool: 0x580D4Fdc4BF8f9b5ae2fb9225D584fED4AD5375c Lending Pool Core: 0x95D1189Ed88B380E319dF73fF00E479fcc4CFa45
tokenAddress = 0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD; aTokenAddress = 0x58AD4cB396411B691A9AAb6F74545b2C5217FE6a; lendingPoolAddress = 0x580D4Fdc4BF8f9b5ae2fb9225D584fED4AD5375c; lendingPoolCoreAddress = 0x95D1189Ed88B380E319dF73fF00E479fcc4CFa45;
tokenAddress = 0xFf795577d9AC8bD7D90Ee22b6C1703490b6512FD; aTokenAddress = 0x58AD4cB396411B691A9AAb6F74545b2C5217FE6a; lendingPoolAddress = 0x580D4Fdc4BF8f9b5ae2fb9225D584fED4AD5375c; lendingPoolCoreAddress = 0x95D1189Ed88B380E319dF73fF00E479fcc4CFa45;
28,396
62
// Get balance locked up to the current moment of time _who address Address owns lockedup amountsreturn uint256 Balance locked up to the current moment of time/
function balanceLockedUp(address _who) public view returns (uint256) { uint256 _balanceLockedUp = 0; for (uint256 i = 0; i < lockedup[_who].length; i++) { if (lockedup[_who][i].release > block.timestamp) // solium-disable-line security/no-block-members _balanceLockedUp = _balanceLockedUp.add(lockedup[_who][i].amount); } return _balanceLockedUp; }
function balanceLockedUp(address _who) public view returns (uint256) { uint256 _balanceLockedUp = 0; for (uint256 i = 0; i < lockedup[_who].length; i++) { if (lockedup[_who][i].release > block.timestamp) // solium-disable-line security/no-block-members _balanceLockedUp = _balanceLockedUp.add(lockedup[_who][i].amount); } return _balanceLockedUp; }
13,996
16
// Returns the number of vesting schedules associated to a beneficiary.return the number of vesting schedules /
function getVestingSchedulesCountByBeneficiary(address _beneficiary) external view returns(uint256) { return holdersVestingCount[_beneficiary]; }
function getVestingSchedulesCountByBeneficiary(address _beneficiary) external view returns(uint256) { return holdersVestingCount[_beneficiary]; }
31,763
2
// calculate total collateral balance for the nft
(vars.totalCollateralInETH, vars.totalCollateralInReserve) = calculateNftCollateralData( reserveAddress, reserveData, nftAddress, nftData, reserveOracle, nftOracle );
(vars.totalCollateralInETH, vars.totalCollateralInReserve) = calculateNftCollateralData( reserveAddress, reserveData, nftAddress, nftData, reserveOracle, nftOracle );
13,622
212
// Don't assign to the parameter
uint remainingToAllocate = xdrAmount;
uint remainingToAllocate = xdrAmount;
33,204
51
// Returns - 0: affiliateId, 1: affiliateName
function getAffiliateInfo(uint256 _samuraiId) public view returns(uint256, bytes32) { uint256 affiliateId = idToAffiliateId[_samuraiId]; Samurai memory affiliate = idToSamurai[affiliateId]; return (affiliateId, affiliate.name); }
function getAffiliateInfo(uint256 _samuraiId) public view returns(uint256, bytes32) { uint256 affiliateId = idToAffiliateId[_samuraiId]; Samurai memory affiliate = idToSamurai[affiliateId]; return (affiliateId, affiliate.name); }
26,084
92
// derivative's token builder strategy address
function tokenBuilder() external view returns (address); function feeLogger() external view returns (address);
function tokenBuilder() external view returns (address); function feeLogger() external view returns (address);
18,459
268
// Time in blocks an indexer needs to wait to change delegation parameters
uint32 public delegationParametersCooldown;
uint32 public delegationParametersCooldown;
84,335
14
// require(address(this).balance == 0);
selfdestruct(msg.sender);
selfdestruct(msg.sender);
83,305
400
// Removes a key-value pair from a map. O(1). Returns true if the key was removed from the map, that is if it was present. /
function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } }
function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } }
28,695
23
// Mark loan as repaid before doing any external transfers to follow the Checks-Effects-Interactions design pattern.
loanRepaidOrLiquidated[_loanId] = true;
loanRepaidOrLiquidated[_loanId] = true;
23,027
30
// Cancel a release request_id The ID of the escrow account to be unmarked /
function cancelRelease(uint _id) external onlyCustodian whenUnfrozen { Lock storage lock = locks[_id]; require( lock.owner == address(0), "IM:CreditCardEscrow: escrow account is not custodial, call release directly" ); require( lock.releaseTimestamp != 0, "IM:CreditCardEscrow: must be marked for release" ); require( lock.releaseTimestamp > block.timestamp, "IM:CreditCardEscrow: release period must not have expired" ); lock.releaseTimestamp = 0; lock.releaseTo = address(0); emit ReleaseCancelled(_id); }
function cancelRelease(uint _id) external onlyCustodian whenUnfrozen { Lock storage lock = locks[_id]; require( lock.owner == address(0), "IM:CreditCardEscrow: escrow account is not custodial, call release directly" ); require( lock.releaseTimestamp != 0, "IM:CreditCardEscrow: must be marked for release" ); require( lock.releaseTimestamp > block.timestamp, "IM:CreditCardEscrow: release period must not have expired" ); lock.releaseTimestamp = 0; lock.releaseTo = address(0); emit ReleaseCancelled(_id); }
15,808
18
// getting pubkey hash
bytes32 pubkeyHash = BN254.hashG1Point(pk); require(pubkeyHash != ZERO_PK_HASH, "BLSRegistry._registerOperator: Cannot register with 0x0 public key"); require( pubkeyCompendium.pubkeyHashToOperator(pubkeyHash) == operator, "BLSRegistry._registerOperator: operator does not own pubkey" );
bytes32 pubkeyHash = BN254.hashG1Point(pk); require(pubkeyHash != ZERO_PK_HASH, "BLSRegistry._registerOperator: Cannot register with 0x0 public key"); require( pubkeyCompendium.pubkeyHashToOperator(pubkeyHash) == operator, "BLSRegistry._registerOperator: operator does not own pubkey" );
34,185
16
// Emitted when an admin adds a symbol to a previously registered and confirmed tokenvia `addTokenSymbol` /
event TokenSymbolAdded(IERC20 assetAddress, string assetSymbol);
event TokenSymbolAdded(IERC20 assetAddress, string assetSymbol);
26,769
40
// Withdraw staked ApeCoin from the MAYC pool.If withdraw is total staked amount, performs an automatic claim. _nfts Array of MAYC NFT's with staked amounts /
function withdrawSelfMAYC(SingleNft[] calldata _nfts) external { _withdrawNft(MAYC_POOL_ID, _nfts, msg.sender); }
function withdrawSelfMAYC(SingleNft[] calldata _nfts) external { _withdrawNft(MAYC_POOL_ID, _nfts, msg.sender); }
22,492
135
// ERC721 /
function name() public pure returns (string) { return "Ethwuxia.pro"; }
function name() public pure returns (string) { return "Ethwuxia.pro"; }
34,200
40
// Guarantees that _tokenId is a valid Token. _tokenId ID of the NFT to validate. /
modifier validNFToken(uint256 _tokenId) { require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _; }
modifier validNFToken(uint256 _tokenId) { require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _; }
33,386
18
// Check if the caller is the owner of the DID
require(_owner == msg.sender, "confirmCredential, caller does not control DID");
require(_owner == msg.sender, "confirmCredential, caller does not control DID");
47,332
124
// _requireBidderBalance(msg.sender, _price);
if (auction.bidder != address(0x0)) { require(usdtToken.transfer(auction.bidder, auction.price), "Refund USDT to previous bidder failed" ); }
if (auction.bidder != address(0x0)) { require(usdtToken.transfer(auction.bidder, auction.price), "Refund USDT to previous bidder failed" ); }
37,762
19
// auditee can request an audit using this function and sets reward per bug and bug risk. contract needs a deposit of multiples of the total reward. /
function RequestAudit(bytes32 _contracthash, string memory _link, uint256[4] memory _rewards) public payable returns (bool success) { uint256[] memory emptyarray; address[] memory emptyaddress; uint256 totalRewards = _rewards[0].add(_rewards[1]).add(_rewards[2]).add(_rewards[3]); //calculate fee 0.3% and deduct form deposit uint256 deposit_multiplier = msg.value.div(totalRewards); uint256 total = totalRewards.mul(deposit_multiplier); uint256 fee = total.div(1000).mul(3); uint256 amount = msg.value.sub(fee); //Check if rewards are multiple of each other and msg.value require(audits[_contracthash].owner == address(0), "request audit: audit is non empty"); require(msg.value != 0, "request audit: no reward added"); require(amount.mod(totalRewards) == 0, "request audit: msg.value not equal to rewards"); require(_rewards[0].mod(_rewards[1]) == 0, "request audit: critical reward is not multiple of high reward"); require(_rewards[1].mod(_rewards[2]) == 0, "request audit: high reward is not multiple of medium reward"); require(_rewards[2].mod(_rewards[3]) == 0, "request audit: critical medium is not multiple of low reward"); totalRewardAvailable = totalRewardAvailable.add(amount); audits[_contracthash] = Audit({owner: msg.sender, link: _link, balance: amount, rewards: _rewards, reportIndex: 0, reports: emptyarray, validated: emptyaddress, closed: false }); index_audit[indexTotal] = _contracthash; audit_index[_contracthash] = indexTotal; //Set audit as pending total_pending[indexTotal] = indexPending; pending_total[indexPending] = indexTotal; indexTotal = indexTotal.add(1); indexPending = indexPending.add(1); dev.transfer(fee); emit AuditRequest(_contracthash, totalRewards, msg.sender); return true; }
function RequestAudit(bytes32 _contracthash, string memory _link, uint256[4] memory _rewards) public payable returns (bool success) { uint256[] memory emptyarray; address[] memory emptyaddress; uint256 totalRewards = _rewards[0].add(_rewards[1]).add(_rewards[2]).add(_rewards[3]); //calculate fee 0.3% and deduct form deposit uint256 deposit_multiplier = msg.value.div(totalRewards); uint256 total = totalRewards.mul(deposit_multiplier); uint256 fee = total.div(1000).mul(3); uint256 amount = msg.value.sub(fee); //Check if rewards are multiple of each other and msg.value require(audits[_contracthash].owner == address(0), "request audit: audit is non empty"); require(msg.value != 0, "request audit: no reward added"); require(amount.mod(totalRewards) == 0, "request audit: msg.value not equal to rewards"); require(_rewards[0].mod(_rewards[1]) == 0, "request audit: critical reward is not multiple of high reward"); require(_rewards[1].mod(_rewards[2]) == 0, "request audit: high reward is not multiple of medium reward"); require(_rewards[2].mod(_rewards[3]) == 0, "request audit: critical medium is not multiple of low reward"); totalRewardAvailable = totalRewardAvailable.add(amount); audits[_contracthash] = Audit({owner: msg.sender, link: _link, balance: amount, rewards: _rewards, reportIndex: 0, reports: emptyarray, validated: emptyaddress, closed: false }); index_audit[indexTotal] = _contracthash; audit_index[_contracthash] = indexTotal; //Set audit as pending total_pending[indexTotal] = indexPending; pending_total[indexPending] = indexTotal; indexTotal = indexTotal.add(1); indexPending = indexPending.add(1); dev.transfer(fee); emit AuditRequest(_contracthash, totalRewards, msg.sender); return true; }
49,186
169
// Check if a particular address is allowlisted.
function isOnAllowList(address addr) external view returns (bool) { return _allowList[addr]; }
function isOnAllowList(address addr) external view returns (bool) { return _allowList[addr]; }
29,257
22
// Existing owner transfers permissions to new owner.It transfers authority to the person who was not the owner.Approval from the committee is required. /
function transferOwnership(address _newOwner) onlyOwner committeeApproved public { require( _newOwner != address(0x0) ); // callisto recommendation require( owner[_newOwner] == false ); owner[msg.sender] = false; owner[_newOwner] = true; emit TransferOwnership(msg.sender, _newOwner); }
function transferOwnership(address _newOwner) onlyOwner committeeApproved public { require( _newOwner != address(0x0) ); // callisto recommendation require( owner[_newOwner] == false ); owner[msg.sender] = false; owner[_newOwner] = true; emit TransferOwnership(msg.sender, _newOwner); }
25,309
103
// Someone takes tokens from collateral via a spell caller.
event TakeCollateral(uint positionId, address caller, address token, uint id, uint amount);
event TakeCollateral(uint positionId, address caller, address token, uint id, uint amount);
40,237
13
// Calculate the claimable amount based off the total of reward (used in the merkle tree) since the beginning for the user, minus the total claimed so far
claimable = _amount - claimed[_token][_account];
claimable = _amount - claimed[_token][_account];
1,721
222
// Cancels a pending withdraw query (in an event of Oracle failing to answer) _queryId - ID of request to cancel
function cancel( bytes32 _queryId ) public onlyOwner
function cancel( bytes32 _queryId ) public onlyOwner
1,297
660
// Require that upgrades have not been frozen
require(!upgradesFrozen, "Upgrades have been frozen [DriipSettlementState.sol:413]");
require(!upgradesFrozen, "Upgrades have been frozen [DriipSettlementState.sol:413]");
11,636
37
// Base contract which allows children to implement an emergency stop mechanism. /
contract Pausable is Ownable { bool private _paused; event Paused(); event Unpaused(); /** * @dev Constructor */ constructor () internal { _paused = false; } /** * @return Returns true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Paused"); _; } /** * @dev Sets paused state. * * Can only be called by the current owner. */ function setPaused(bool value) external onlyOwner { _paused = value; if (_paused) { emit Paused(); } else { emit Unpaused(); } } }
contract Pausable is Ownable { bool private _paused; event Paused(); event Unpaused(); /** * @dev Constructor */ constructor () internal { _paused = false; } /** * @return Returns true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Paused"); _; } /** * @dev Sets paused state. * * Can only be called by the current owner. */ function setPaused(bool value) external onlyOwner { _paused = value; if (_paused) { emit Paused(); } else { emit Unpaused(); } } }
11,819
62
// Internal transfer altcoin function/
function _transferCoin( address _owner, address _contract, uint256 _returnAmount
function _transferCoin( address _owner, address _contract, uint256 _returnAmount
36,969
77
// details for the given aggregator round _roundId target aggregator round (NOT OCR round). Must fit in uint32return roundId _roundIdreturn answer median of report from given _roundIdreturn startedAt timestamp of block in which report from given _roundId was transmittedreturn updatedAt timestamp of block in which report from given _roundId was transmittedreturn answeredInRound _roundId /
function getRoundData(uint80 _roundId) public override view virtual returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt,
function getRoundData(uint80 _roundId) public override view virtual returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt,
28,290
15
// 查询是否附议
function queryVoting(uint pId, address voterAddr) public view returns (uint){ //提案是否存在 if (proposals[pId].initialized == false) revert("proposal not exist"); //返回投票时间 return proposals[pId].voters[voterAddr].voteTimeStamp; }
function queryVoting(uint pId, address voterAddr) public view returns (uint){ //提案是否存在 if (proposals[pId].initialized == false) revert("proposal not exist"); //返回投票时间 return proposals[pId].voters[voterAddr].voteTimeStamp; }
7,224
10
// get ticket info/ticketId id of the ticket to look up/ return owner ticket owner/ return price price, that has been locked for ticket/ return validUntil expiration date for ticket/ return value transfer value
function getTicketInfo(uint256 ticketId) public view returns( address owner, uint256 price, uint256 issued, uint256 value);
function getTicketInfo(uint256 ticketId) public view returns( address owner, uint256 price, uint256 issued, uint256 value);
47,635
51
// Overflow control
uint256( 0)) :address( uint160 (uint256( _b)>>96))
uint256( 0)) :address( uint160 (uint256( _b)>>96))
40,852
21
// Read and consume a certain amount of bytes from the buffer./buffer An instance of `Buffer`./length How many bytes to read and consume from the buffer./ return output A `bytes memory` containing the first `length` bytes from the buffer, counting from the cursor position.
function read(Buffer memory buffer, uint length) internal pure withinRange(buffer.cursor + length, buffer.data.length + 1) returns (bytes memory output)
function read(Buffer memory buffer, uint length) internal pure withinRange(buffer.cursor + length, buffer.data.length + 1) returns (bytes memory output)
13,991
4
// Emitted when lender claims collateral from a bucket. claimerRecipient that claimed collateral. indexIndex at which collateral was claimed. amount The amount of collateral (`WAD` precision for `ERC20` pools, number of `NFT` tokens for `ERC721` pools) transferred to the claimer. lpRedeemed Amount of `LP` exchanged for quote token (`WAD` precision). /
event RemoveCollateral(
event RemoveCollateral(
39,805
29
// Checks whether the contract is enabled /
modifier contractIsEnabled { require(contractEnabled == 1, "CrosschainLoans/contract-not-enabled"); _; }
modifier contractIsEnabled { require(contractEnabled == 1, "CrosschainLoans/contract-not-enabled"); _; }
30,013
145
// Emitted when an admin updates third presale price
event NewPresalePrice3(uint256 oldPrice, uint256 newPrice);
event NewPresalePrice3(uint256 oldPrice, uint256 newPrice);
20,809
11
// exploit
if(r>0){ r--; fundraiser.withdrawAllMyCoins(); }
if(r>0){ r--; fundraiser.withdrawAllMyCoins(); }
4,361
18
// /
contract BMath is BConst, BNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 swapFee ) internal pure returns (uint256 spotPrice) { uint256 numer = bdiv(tokenBalanceIn, tokenWeightIn); uint256 denom = bdiv(tokenBalanceOut, tokenWeightOut); uint256 ratio = bdiv(numer, denom); uint256 scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountIn, uint256 swapFee ) internal pure returns (uint256 tokenAmountOut) { uint256 weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint256 adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint256 y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint256 foo = bpow(y, weightRatio); uint256 bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) internal pure returns (uint256 tokenAmountIn) { uint256 weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint256 diff = bsub(tokenBalanceOut, tokenAmountOut); uint256 y = bdiv(tokenBalanceOut, diff); uint256 foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) internal pure returns (uint256 poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint256 tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint256 newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint256 tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint256 poolRatio = bpow(tokenInRatio, normalizedWeight); uint256 newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleInGivenPoolOut // // tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ // // pS = poolSupply || --------- | ^ | --------- || * bI - bI // // pAo = poolAmountOut \\ pS / \(wI / tW)// // // bI = balanceIn tAi = -------------------------------------------- // // wI = weightIn / wI \ // // tW = totalWeight | 1 - ---- | * sF // // sF = swapFee \ tW / // **********************************************************************************************/ function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) internal pure returns (uint256 tokenAmountIn) { uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint256 newPoolSupply = badd(poolSupply, poolAmountOut); uint256 poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint256 boo = bdiv(BONE, normalizedWeight); uint256 tokenInRatio = bpow(poolRatio, boo); uint256 newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint256 tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint256 zar = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar)); return tokenAmountIn; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountIn, uint256 swapFee ) internal pure returns (uint256 tokenAmountOut) { uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint256 poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE)); uint256 newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint256 poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint256 tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint256 newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint256 tokenAmountOutBeforeSwapFee = bsub( tokenBalanceOut, newTokenBalanceOut ); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } /********************************************************************************************** // calcPoolInGivenSingleOut // // pAi = poolAmountIn // / tAo \\ / wO \ \ // // bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ // // tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | // // ps = poolSupply \\ -----------------------------------/ / // // wO = tokenWeightOut pAi = \\ bO / / // // tW = totalWeight ------------------------------------------------------------- // // sF = swapFee ( 1 - eF ) // // eF = exitFee // **********************************************************************************************/ function calcPoolInGivenSingleOut( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountOut, uint256 swapFee ) internal pure returns (uint256 poolAmountIn) { // charge swap fee on the output token side uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight); //uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ; uint256 zoo = bsub(BONE, normalizedWeight); uint256 zar = bmul(zoo, swapFee); uint256 tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar)); uint256 newTokenBalanceOut = bsub( tokenBalanceOut, tokenAmountOutBeforeSwapFee ); uint256 tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); //uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply; uint256 poolRatio = bpow(tokenOutRatio, normalizedWeight); uint256 newPoolSupply = bmul(poolRatio, poolSupply); uint256 poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply); // charge exit fee on the pool token side // pAi = pAiAfterExitFee/(1-exitFee) poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE)); return poolAmountIn; } }
contract BMath is BConst, BNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 swapFee ) internal pure returns (uint256 spotPrice) { uint256 numer = bdiv(tokenBalanceIn, tokenWeightIn); uint256 denom = bdiv(tokenBalanceOut, tokenWeightOut); uint256 ratio = bdiv(numer, denom); uint256 scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountIn, uint256 swapFee ) internal pure returns (uint256 tokenAmountOut) { uint256 weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint256 adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint256 y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint256 foo = bpow(y, weightRatio); uint256 bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 tokenAmountOut, uint256 swapFee ) internal pure returns (uint256 tokenAmountIn) { uint256 weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint256 diff = bsub(tokenBalanceOut, tokenAmountOut); uint256 y = bdiv(tokenBalanceOut, diff); uint256 foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountIn, uint256 swapFee ) internal pure returns (uint256 poolAmountOut) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint256 tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); uint256 newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint256 tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint256 poolRatio = bpow(tokenInRatio, normalizedWeight); uint256 newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return poolAmountOut; } /********************************************************************************************** // calcSingleInGivenPoolOut // // tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ // // pS = poolSupply || --------- | ^ | --------- || * bI - bI // // pAo = poolAmountOut \\ pS / \(wI / tW)// // // bI = balanceIn tAi = -------------------------------------------- // // wI = weightIn / wI \ // // tW = totalWeight | 1 - ---- | * sF // // sF = swapFee \ tW / // **********************************************************************************************/ function calcSingleInGivenPoolOut( uint256 tokenBalanceIn, uint256 tokenWeightIn, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountOut, uint256 swapFee ) internal pure returns (uint256 tokenAmountIn) { uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint256 newPoolSupply = badd(poolSupply, poolAmountOut); uint256 poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint256 boo = bdiv(BONE, normalizedWeight); uint256 tokenInRatio = bpow(poolRatio, boo); uint256 newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint256 tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint256 zar = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar)); return tokenAmountIn; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 poolAmountIn, uint256 swapFee ) internal pure returns (uint256 tokenAmountOut) { uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint256 poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE)); uint256 newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint256 poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint256 tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint256 newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint256 tokenAmountOutBeforeSwapFee = bsub( tokenBalanceOut, newTokenBalanceOut ); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } /********************************************************************************************** // calcPoolInGivenSingleOut // // pAi = poolAmountIn // / tAo \\ / wO \ \ // // bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ // // tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | // // ps = poolSupply \\ -----------------------------------/ / // // wO = tokenWeightOut pAi = \\ bO / / // // tW = totalWeight ------------------------------------------------------------- // // sF = swapFee ( 1 - eF ) // // eF = exitFee // **********************************************************************************************/ function calcPoolInGivenSingleOut( uint256 tokenBalanceOut, uint256 tokenWeightOut, uint256 poolSupply, uint256 totalWeight, uint256 tokenAmountOut, uint256 swapFee ) internal pure returns (uint256 poolAmountIn) { // charge swap fee on the output token side uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight); //uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ; uint256 zoo = bsub(BONE, normalizedWeight); uint256 zar = bmul(zoo, swapFee); uint256 tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar)); uint256 newTokenBalanceOut = bsub( tokenBalanceOut, tokenAmountOutBeforeSwapFee ); uint256 tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); //uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply; uint256 poolRatio = bpow(tokenOutRatio, normalizedWeight); uint256 newPoolSupply = bmul(poolRatio, poolSupply); uint256 poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply); // charge exit fee on the pool token side // pAi = pAiAfterExitFee/(1-exitFee) poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE)); return poolAmountIn; } }
15,695
14
// Returns the symbol of the token. /
function symbol() external view returns(string memory);
function symbol() external view returns(string memory);
25,497
1
// array of results
struct ResultStruct { ResultInfo[] results; uint count; }
struct ResultStruct { ResultInfo[] results; uint count; }
20,013
23
// There is minimum and maximum bets.
uint public constant MIN_BET = 0.01 ether;
uint public constant MIN_BET = 0.01 ether;
37,658
2
// The liquidity parameters, such as:- tokenX: The address of token X- tokenY: The address of token Y- binStep: The bin step of the pair- amountX: The amount to send of token X- amountY: The amount to send of token Y- amountXMin: The min amount of token X added to liquidity- amountYMin: The min amount of token Y added to liquidity- activeIdDesired: The active id that user wants to add liquidity from- idSlippage: The number of id that are allowed to slip- deltaIds: The list of delta ids to add liquidity (`deltaId = activeId - desiredId`)- distributionX: The distribution of tokenX
struct LiquidityParameters { IERC20 tokenX; IERC20 tokenY; uint256 binStep; uint256 amountX; uint256 amountY; uint256 amountXMin; uint256 amountYMin; uint256 activeIdDesired; uint256 idSlippage; int256[] deltaIds; uint256[] distributionX; uint256[] distributionY; address to; address refundTo; uint256 deadline; }
struct LiquidityParameters { IERC20 tokenX; IERC20 tokenY; uint256 binStep; uint256 amountX; uint256 amountY; uint256 amountXMin; uint256 amountYMin; uint256 activeIdDesired; uint256 idSlippage; int256[] deltaIds; uint256[] distributionX; uint256[] distributionY; address to; address refundTo; uint256 deadline; }
15,521