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
220
// ---------------------------- Public functions ---------------------------- //exchangeRate returns the current exchange rate of wxETH to xETH
function exchangeRate() public view returns (uint256) {
function exchangeRate() public view returns (uint256) {
38,541
312
// Get the current pool value in underlying return total : total AUM in underlying /
function _getCurrentPoolValue() internal view
function _getCurrentPoolValue() internal view
6,427
49
// Helper function to calculated prorated repayment loanReceipt Decoded loan receiptreturn repayment amount in currency tokensreturn proration based on elapsed duration /
function _prorateRepayment( LoanReceipt.LoanReceiptV2 memory loanReceipt
function _prorateRepayment( LoanReceipt.LoanReceiptV2 memory loanReceipt
13,390
3
// Access modifier for CEO-only functionality
modifier onlyCEO() { require(msg.sender == ceoAddress); _; }
modifier onlyCEO() { require(msg.sender == ceoAddress); _; }
12,886
59
// extract from linked list
address _tempNext = _currUser.next; address _tempPrev = _currUser.prev; user[_tempNext][index[_tempNext][_market][_card]].prev = _tempPrev; user[_tempPrev][index[_tempPrev][_market][_card]].next = _tempNext;
address _tempNext = _currUser.next; address _tempPrev = _currUser.prev; user[_tempNext][index[_tempNext][_market][_card]].prev = _tempPrev; user[_tempPrev][index[_tempPrev][_market][_card]].next = _tempNext;
35,026
81
// Set the default latest funding time to 0. This represents that boardroom has not been allocated seigniorage yet.
uint256 latestFundingTime = boardHistory[boardHistory.length - 1].time;
uint256 latestFundingTime = boardHistory[boardHistory.length - 1].time;
22,094
66
// Allows a grant recipient to claim their vested tokens. Errors if no tokens have vested/ It is advised recipients check they are entitled to claim via `calculateGrantClaim` before calling this
function claimVestedTokens(uint256 _grantId) external { uint16 daysVested; uint256 amountVested; (daysVested, amountVested) = calculateGrantClaim(_grantId); require(amountVested > 0, "amountVested is 0"); Grant storage tokenGrant = tokenGrants[_grantId]; tokenGrant.daysClaimed = uint16(tokenGrant.daysClaimed.add(daysVested)); tokenGrant.totalClaimed = uint256( tokenGrant.totalClaimed.add(amountVested) ); require( token.transfer(tokenGrant.recipient, amountVested), "no tokens" ); emit GrantTokensClaimed(tokenGrant.recipient, amountVested); }
function claimVestedTokens(uint256 _grantId) external { uint16 daysVested; uint256 amountVested; (daysVested, amountVested) = calculateGrantClaim(_grantId); require(amountVested > 0, "amountVested is 0"); Grant storage tokenGrant = tokenGrants[_grantId]; tokenGrant.daysClaimed = uint16(tokenGrant.daysClaimed.add(daysVested)); tokenGrant.totalClaimed = uint256( tokenGrant.totalClaimed.add(amountVested) ); require( token.transfer(tokenGrant.recipient, amountVested), "no tokens" ); emit GrantTokensClaimed(tokenGrant.recipient, amountVested); }
12,760
959
// Initiate a proposal/wallet The address of the concerned challenged wallet/nonce The wallet nonce/stageAmount The proposal stage amount/targetBalanceAmount The proposal target balance amount/currency The concerned currency/blockNumber The proposal block number/walletInitiated True if initiated by the concerned challenged wallet
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated) public onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated) public onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
22,147
26
// Set the swap guard of the user's conditional orders swapGuard The address of the swap guard /
function setSwapGuard(ISwapGuard swapGuard) external { swapGuards[msg.sender] = swapGuard; emit SwapGuardSet(msg.sender, swapGuard); }
function setSwapGuard(ISwapGuard swapGuard) external { swapGuards[msg.sender] = swapGuard; emit SwapGuardSet(msg.sender, swapGuard); }
6,422
8
// Kyber constants contract
contract Utils { ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH uint constant internal MAX_DECIMALS = 18; uint constant internal ETH_DECIMALS = 18; mapping(address=>uint) internal decimals; function setDecimals(ERC20 token) internal { if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS; else decimals[token] = token.decimals(); } function getDecimals(ERC20 token) internal view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access uint tokenDecimals = decimals[token]; // technically, there might be token with decimals 0 // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. if(tokenDecimals == 0) return token.decimals(); return tokenDecimals; } function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(srcQty <= MAX_QTY); require(rate <= MAX_RATE); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(dstQty <= MAX_QTY); require(rate <= MAX_RATE); //source quantity is rounded up. to avoid dest quantity being too low. uint numerator; uint denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } }
contract Utils { ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH uint constant internal MAX_DECIMALS = 18; uint constant internal ETH_DECIMALS = 18; mapping(address=>uint) internal decimals; function setDecimals(ERC20 token) internal { if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS; else decimals[token] = token.decimals(); } function getDecimals(ERC20 token) internal view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access uint tokenDecimals = decimals[token]; // technically, there might be token with decimals 0 // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. if(tokenDecimals == 0) return token.decimals(); return tokenDecimals; } function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(srcQty <= MAX_QTY); require(rate <= MAX_RATE); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(dstQty <= MAX_QTY); require(rate <= MAX_RATE); //source quantity is rounded up. to avoid dest quantity being too low. uint numerator; uint denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } }
38,343
138
// open convert tool to the public
function initialize(MintCoordinator _MINT_COORDINATOR) external onlyOwner
function initialize(MintCoordinator _MINT_COORDINATOR) external onlyOwner
71,294
3
// timestamp ending presale
uint256 public immutable presaleEnd;
uint256 public immutable presaleEnd;
31,803
229
// Allocate unallocated funds on Vault to strategies. Allocate unallocated funds on Vault to strategies. /
function allocate() public whenNotCapitalPaused nonReentrant { _allocate(); }
function allocate() public whenNotCapitalPaused nonReentrant { _allocate(); }
67,837
100
// This method relies on extcodesize, which returns 0 for contracts in construction, since the code is only stored at the end of the constructor execution.IMPORTANT It is unsafe to assume that an address not flagged by this method is an externally-owned account (EOA) and not a contract. Among others, the following types of addresses will not be flagged:- an externally-owned account- a contract in construction- an address where a contract will be created- an address where a contract lived, but was destroyed
uint256 _size_; assembly { _size_ := extcodesize( to_ ) }
uint256 _size_; assembly { _size_ := extcodesize( to_ ) }
82,334
1
// Proposal /
struct Proposal { address author; address smartContract; bool auditPassed; bool auditRequired; bool auditorsAreReady; bool approved; bool denied; bool banned; bool isRemovedByAuthor; uint256 fundsRequiredAmount; uint256 fundsDepositedAmount; uint256 auditFinishedAt; uint128 submittedAt; uint128 expireAt; uint128 requiredAuditorCount; uint128 auditBanCount; uint64 auditYesVotes; uint64 auditNoVotes; uint64 generalYesVotes; uint64 generalNoVotes; }
struct Proposal { address author; address smartContract; bool auditPassed; bool auditRequired; bool auditorsAreReady; bool approved; bool denied; bool banned; bool isRemovedByAuthor; uint256 fundsRequiredAmount; uint256 fundsDepositedAmount; uint256 auditFinishedAt; uint128 submittedAt; uint128 expireAt; uint128 requiredAuditorCount; uint128 auditBanCount; uint64 auditYesVotes; uint64 auditNoVotes; uint64 generalYesVotes; uint64 generalNoVotes; }
26,500
76
// update balance price per second here
uint64 castPricePerSec = uint64(newPricePerSec); require(uint256(castPricePerSec) == newPricePerSec); IBalanceManager(getModule("BALANCE")).changePrice(msg.sender, castPricePerSec); emit PlanUpdate(msg.sender, _protocols, _coverAmounts, endTime);
uint64 castPricePerSec = uint64(newPricePerSec); require(uint256(castPricePerSec) == newPricePerSec); IBalanceManager(getModule("BALANCE")).changePrice(msg.sender, castPricePerSec); emit PlanUpdate(msg.sender, _protocols, _coverAmounts, endTime);
27,358
23
// Transfer BNF token from sender to recipient when sender transfers BNU token to recipient/
function shareholderTransfer(address sender, address recipient, uint amount) external returns(bool);
function shareholderTransfer(address sender, address recipient, uint amount) external returns(bool);
27,959
15
// We use 36 because of the length of our calldata. We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
if iszero(staticcall(gas(), npm, 0, 0x24, 0, 0x20)) { returndatacopy(0, 0, returndatasize())
if iszero(staticcall(gas(), npm, 0, 0x24, 0, 0x20)) { returndatacopy(0, 0, returndatasize())
23,784
27
// round 25
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
24,341
111
// The winners of the lottery can call this function to transfer their winningsfrom the lottery contract to their own address. The winners will need to burn theirLOT tokens to claim the lottery rewards. This is executed by the lottery contract itself.Requirements: - The Lottery is settled i.e. the lotteryStatus is CLOSED. /
function collectRewards() public nonReentrant { require( lotteryStatus == LotteryStatus.CLOSED, "The Lottery is not settled. Please try in a short while." ); for (uint256 i = 0; i < lotteryConfig.numOfWinners; i = i.add(1)) { if (address(msg.sender) == winnerAddresses[winnerIndexes[i]]) { // _burn(address(msg.sender), lotteryConfig.registrationAmount); lotteryToken.burnFrom(msg.sender, lotteryConfig.registrationAmount); buyToken.transfer(address(msg.sender), rewardPoolAmount); winnerAddresses[winnerIndexes[i]] = address(0); } } }
function collectRewards() public nonReentrant { require( lotteryStatus == LotteryStatus.CLOSED, "The Lottery is not settled. Please try in a short while." ); for (uint256 i = 0; i < lotteryConfig.numOfWinners; i = i.add(1)) { if (address(msg.sender) == winnerAddresses[winnerIndexes[i]]) { // _burn(address(msg.sender), lotteryConfig.registrationAmount); lotteryToken.burnFrom(msg.sender, lotteryConfig.registrationAmount); buyToken.transfer(address(msg.sender), rewardPoolAmount); winnerAddresses[winnerIndexes[i]] = address(0); } } }
33,490
997
// Helper method to return all the subscribed CDPs
function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; }
function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; }
26,106
27
// nftWorldItem.prevPrice = 0;is by default zero
nft.price = _nftItemPriceWei;
nft.price = _nftItemPriceWei;
20,422
76
// To get the total number of tokens minted, please see {_totalMinted}. /
function totalSupply() public view virtual override returns (uint256) {
function totalSupply() public view virtual override returns (uint256) {
3,620
0
// Compound Comptroller /
ComptrollerInterface internal constant troller = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
ComptrollerInterface internal constant troller = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
12,025
666
// Update the reward and emit the `RewardAdded` event// - PRIVILEGES REQUIRED:/ Admins with the role "REWARDS_DISTRIBUTOR_ROLE"//bankNodeId The id of the bank node/reward The reward amount
function notifyRewardAmount(uint32 bankNodeId, uint256 reward) external onlyRole(REWARDS_DISTRIBUTOR_ROLE) { _notifyRewardAmount(bankNodeId, reward); }
function notifyRewardAmount(uint32 bankNodeId, uint256 reward) external onlyRole(REWARDS_DISTRIBUTOR_ROLE) { _notifyRewardAmount(bankNodeId, reward); }
69,567
203
// Pool state that never changes/These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); }
interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); }
9,860
146
// Get the lock time of a tokentokenId The token id/
function getLockTime(uint256 tokenId) external view returns(uint256) { return _getLockTime(tokenId); }
function getLockTime(uint256 tokenId) external view returns(uint256) { return _getLockTime(tokenId); }
32,114
7
// Locks `amount` of governance tokens
function lock(uint256 amount) external;
function lock(uint256 amount) external;
3,465
124
// if(contractTokenBalance>maxTokensBeforeAddToLP){contractTokenBalance = maxTokensBeforeAddToLP;}
uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); uint256 initialBalance = address(this).balance; swapTokensForEth(half); uint256 newBalance = address(this).balance.sub(initialBalance); addETHAndBFILiquidity(otherHalf, newBalance); emit SwapAndBFIForLP(half, newBalance, otherHalf);
uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); uint256 initialBalance = address(this).balance; swapTokensForEth(half); uint256 newBalance = address(this).balance.sub(initialBalance); addETHAndBFILiquidity(otherHalf, newBalance); emit SwapAndBFIForLP(half, newBalance, otherHalf);
26,491
184
// If there is a mismatch between the required quantity and the base SetToken natural unit, round up to the next base SetToken natural unit if required.
uint256 roundDownQuantity = requiredBaseSetQuantity.mod(baseSetNaturalUnit); if (roundDownQuantity > 0) { requiredBaseSetQuantity = requiredBaseSetQuantity.sub(roundDownQuantity).add(baseSetNaturalUnit); }
uint256 roundDownQuantity = requiredBaseSetQuantity.mod(baseSetNaturalUnit); if (roundDownQuantity > 0) { requiredBaseSetQuantity = requiredBaseSetQuantity.sub(roundDownQuantity).add(baseSetNaturalUnit); }
27,543
32
// Buy a listed item. You must authorize this marketplace with your payment token to completed the buy./ _nftAddresswhich token contract holds the offered token/ _tokenId the identifier for the token to be bought/ _owner current owner of the item(s) to be bought/ _quantityhow many of this token identifier to be bought (or 1 for a ERC-721 token)/ _maxPricePerItem the maximum price (in units of the paymentToken) for each token offered
function buyItem( address _nftAddress, uint256 _tokenId, address _owner, uint64 _quantity, uint128 _maxPricePerItem ) external nonReentrant whenNotPaused
function buyItem( address _nftAddress, uint256 _tokenId, address _owner, uint64 _quantity, uint128 _maxPricePerItem ) external nonReentrant whenNotPaused
9,693
75
// About the last line segment.
require( gradientNumerator >= 0 && gradientNumerator <= gradientDenominator, "the gradient of last line segment must be non-negative, and equal to or less than 1" );
require( gradientNumerator >= 0 && gradientNumerator <= gradientDenominator, "the gradient of last line segment must be non-negative, and equal to or less than 1" );
13,270
29
// Get total number of tokens in circulation. return total number of tokens in circulation /
function totalSupply() public view returns (uint256 supply) { return tokenCount; }
function totalSupply() public view returns (uint256 supply) { return tokenCount; }
6,122
17
// Adds two numbers, throws on overflow./
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; }
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; }
1,330
46
// Check the roll result against the bet bit mask.
if ((2 ** dice) & bet.mask != 0) { diceWin = diceWinAmount; }
if ((2 ** dice) & bet.mask != 0) { diceWin = diceWinAmount; }
42,176
39
// Admin Events // Event emitted when pendingAdmin is changed /
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
3,350
26
// Implementation of the {IERC20} interface.that a supply mechanism has to be added in a derived contract using {_mint}.For a generic mechanism see {ERC20PresetMinterPauser}.Additionally, an {Approval} event is emitted on calls to {transferFrom}.Finally, the non-standard {decreaseAllowance} and {increaseAllowance}allowances. See {IERC20-approve}./ Sets the values for {name} and {symbol}, initializes {decimals} witha default value of 18. To select a different value for {decimals}, use {_setupDecimals}. All three of these values are immutable: they can only be set once duringconstruction. /
constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; }
constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; }
291
68
// Tries to returns the value associated with `key`.O(1).Does not revert if `key` is not in the map. _Available since v3.4._ /
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); }
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); }
1,525
52
// `IUniswapExchangeFactory.getExchange()`.
function getExchange(address tokenAddress) external view returns (address)
function getExchange(address tokenAddress) external view returns (address)
10,504
77
// src/interfaces/IFormula.sol/ pragma solidity ^0.6.7; ///
interface IFormula { struct FormulaEntry { // item name bytes32 name; // strength rate uint128 rate; // extension of `ObjectClass` uint16 objClassExt; uint16 class; uint16 grade; bool canDisenchant; // if it is removed // uint256 enchantTime; // uint256 disenchantTime; // uint256 loseRate; bool disable; // minor material info bytes32 minor; uint256 amount; // major material info // [address token, uint16 objectClassExt, uint16 class, uint16 grade] address majorAddr; uint16 majorObjClassExt; uint16 majorClass; uint16 majorGrade; } event AddFormula( uint256 indexed index, bytes32 name, uint128 rate, uint16 objClassExt, uint16 class, uint16 grade, bool canDisenchant, bytes32 minor, uint256 amount, address majorAddr, uint16 majorObjClassExt, uint16 majorClass, uint16 majorGrade ); event DisableFormula(uint256 indexed index); event EnableFormula(uint256 indexed index); /** @notice Only governance can add `formula`. @dev Add a formula rule. MUST revert if length of `_majors` is not the same as length of `_class`. MUST revert if length of `_minors` is not the same as length of `_mins` and `_maxs. MUST revert on any other error. @param _name New enchanted NFT name. @param _rate New enchanted NFT rate. @param _objClassExt New enchanted NFT objectClassExt. @param _class New enchanted NFT class. @param _grade New enchanted NFT grade. @param _minor FT Token address of minor meterail for enchanting. @param _amount FT Token amount of minor meterail for enchanting. @param _majorAddr FT token address of major meterail for enchanting. @param _majorObjClassExt FT token objectClassExt of major meterail for enchanting. @param _majorClass FT token class of major meterail for enchanting. @param _majorGrade FT token grade of major meterail for enchanting. */ function insert( bytes32 _name, uint128 _rate, uint16 _objClassExt, uint16 _class, uint16 _grade, bool _canDisenchant, bytes32 _minor, uint256 _amount, address _majorAddr, uint16 _majorObjClassExt, uint16 _majorClass, uint16 _majorGrade ) external; /** @notice Only governance can enable `formula`. @dev Enable a formula rule. MUST revert on any other error. @param _index index of formula. */ function disable(uint256 _index) external; /** @notice Only governance can disble `formula`. @dev Disble a formula rule. MUST revert on any other error. @param _index index of formula. */ function enable(uint256 _index) external; /** @dev Returns the length of the formula. 0x1f7b6d32 */ function length() external view returns (uint256); /** @dev Returns the availability of the formula. */ function isDisable(uint256 _index) external view returns (bool); /** @dev returns the minor material of the formula. */ function getMinor(uint256 _index) external view returns (bytes32, uint256); /** @dev Decode major info of the major. 0x6ef2fd27 @return { "token": "Major token address.", "objClassExt": "Major token objClassExt.", "class": "Major token class.", "grade": "Major token address." } */ function getMajorInfo(uint256 _index) external view returns ( address, uint16, uint16, uint16 ); /** @dev Returns meta info of the item. 0x78533046 @return { "objClassExt": "Major token objClassExt.", "class": "Major token class.", "grade": "Major token address.", "base": "Base strength rate.", "enhance": "Enhance strength rate.", } */ function getMetaInfo(uint256 _index) external view returns ( uint16, uint16, uint16, uint128 ); /** @dev returns canDisenchant of the formula. */ function canDisenchant(uint256 _index) external view returns (bool); }
interface IFormula { struct FormulaEntry { // item name bytes32 name; // strength rate uint128 rate; // extension of `ObjectClass` uint16 objClassExt; uint16 class; uint16 grade; bool canDisenchant; // if it is removed // uint256 enchantTime; // uint256 disenchantTime; // uint256 loseRate; bool disable; // minor material info bytes32 minor; uint256 amount; // major material info // [address token, uint16 objectClassExt, uint16 class, uint16 grade] address majorAddr; uint16 majorObjClassExt; uint16 majorClass; uint16 majorGrade; } event AddFormula( uint256 indexed index, bytes32 name, uint128 rate, uint16 objClassExt, uint16 class, uint16 grade, bool canDisenchant, bytes32 minor, uint256 amount, address majorAddr, uint16 majorObjClassExt, uint16 majorClass, uint16 majorGrade ); event DisableFormula(uint256 indexed index); event EnableFormula(uint256 indexed index); /** @notice Only governance can add `formula`. @dev Add a formula rule. MUST revert if length of `_majors` is not the same as length of `_class`. MUST revert if length of `_minors` is not the same as length of `_mins` and `_maxs. MUST revert on any other error. @param _name New enchanted NFT name. @param _rate New enchanted NFT rate. @param _objClassExt New enchanted NFT objectClassExt. @param _class New enchanted NFT class. @param _grade New enchanted NFT grade. @param _minor FT Token address of minor meterail for enchanting. @param _amount FT Token amount of minor meterail for enchanting. @param _majorAddr FT token address of major meterail for enchanting. @param _majorObjClassExt FT token objectClassExt of major meterail for enchanting. @param _majorClass FT token class of major meterail for enchanting. @param _majorGrade FT token grade of major meterail for enchanting. */ function insert( bytes32 _name, uint128 _rate, uint16 _objClassExt, uint16 _class, uint16 _grade, bool _canDisenchant, bytes32 _minor, uint256 _amount, address _majorAddr, uint16 _majorObjClassExt, uint16 _majorClass, uint16 _majorGrade ) external; /** @notice Only governance can enable `formula`. @dev Enable a formula rule. MUST revert on any other error. @param _index index of formula. */ function disable(uint256 _index) external; /** @notice Only governance can disble `formula`. @dev Disble a formula rule. MUST revert on any other error. @param _index index of formula. */ function enable(uint256 _index) external; /** @dev Returns the length of the formula. 0x1f7b6d32 */ function length() external view returns (uint256); /** @dev Returns the availability of the formula. */ function isDisable(uint256 _index) external view returns (bool); /** @dev returns the minor material of the formula. */ function getMinor(uint256 _index) external view returns (bytes32, uint256); /** @dev Decode major info of the major. 0x6ef2fd27 @return { "token": "Major token address.", "objClassExt": "Major token objClassExt.", "class": "Major token class.", "grade": "Major token address." } */ function getMajorInfo(uint256 _index) external view returns ( address, uint16, uint16, uint16 ); /** @dev Returns meta info of the item. 0x78533046 @return { "objClassExt": "Major token objClassExt.", "class": "Major token class.", "grade": "Major token address.", "base": "Base strength rate.", "enhance": "Enhance strength rate.", } */ function getMetaInfo(uint256 _index) external view returns ( uint16, uint16, uint16, uint128 ); /** @dev returns canDisenchant of the formula. */ function canDisenchant(uint256 _index) external view returns (bool); }
61,697
68
// Withdraw given bAsset from the cache /
function withdrawRaw(
function withdrawRaw(
75,625
4
// Revert if the profile is not owned by the sender. itemId itemId of the profile. /
modifier isOwner(bytes32 itemId) { // Ensure the item is owned by the sender. require (itemStoreRegistry.getItemStore(itemId).getOwner(itemId) == msg.sender, "Item is not owned by sender."); _; }
modifier isOwner(bytes32 itemId) { // Ensure the item is owned by the sender. require (itemStoreRegistry.getItemStore(itemId).getOwner(itemId) == msg.sender, "Item is not owned by sender."); _; }
34,610
40
// Public variables of the token The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information./
string public name; uint8 public decimals; string public symbol; string public version = '1.0.0';
string public name; uint8 public decimals; string public symbol; string public version = '1.0.0';
45,266
19
// TODO: onlyOwner removed for mumbai/Set the auction per time unit./Only callable by the owner.
function setPerTimeUnit(uint256 _perTimeUnit) external { perTimeUnit = toDaysWadUnsafe(_perTimeUnit); emit AuctionPerTimeUnitUpdated(_perTimeUnit); }
function setPerTimeUnit(uint256 _perTimeUnit) external { perTimeUnit = toDaysWadUnsafe(_perTimeUnit); emit AuctionPerTimeUnitUpdated(_perTimeUnit); }
2,830
35
// allows the user to withdraw their staked tokens and claim their rewards in the same transaction
function exit() override external { withdraw(_balances[msg.sender]); // withdraws the sender's balance getReward(); // pays the sender their staking reward }
function exit() override external { withdraw(_balances[msg.sender]); // withdraws the sender's balance getReward(); // pays the sender their staking reward }
21,656
128
// Collateral: ERC20 TokenBorrowed: ETH /
contract ERC20ETHLoan is DefinerBasicLoan { StandardToken token; address public collateralTokenAddress; /** * NOT IN USE * WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferCollateral() public payable { revert(); } function establishContract() public { // ERC20 as collateral uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); // Ether as Fund require(address(this).balance >= borrowAmount, "Insufficient fund amount"); // Transit to Funded state transferETHToBorrowerAndStartLoan(); } /** * NOT IN USE * WHEN FUND IS ETH, CHECK IS DONE IN transferFunds() */ function checkFunds() onlyLender atState(States.WaitingForFunds) public { return establishContract(); } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); currentState = States.WaitingForLender; } /** * Lender transfer ETH to fund this contract */ function transferFunds() public payable onlyLender atState(States.WaitingForFunds) { if (address(this).balance >= borrowAmount) { establishContract(); } } /* * Borrower pay back ETH */ function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault { require(msg.value >= installmentAmount); remainingInstallment--; lenderAddress.transfer(installmentAmount); if (remainingInstallment == 0) { currentState = States.Finished; } else { nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days)); } } /* * Borrower gets collateral token back when contract completed */ function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) { uint amount = token.balanceOf(address(this)); token.transfer(borrowerAddress, amount); currentState = States.Closed; } /* * Lender gets collateral token when contract defaulted */ function lenderReclaimCollateral() public onlyLender atState(States.Default) { uint amount = token.balanceOf(address(this)); token.transfer(lenderAddress, amount); currentState = States.Closed; } }
contract ERC20ETHLoan is DefinerBasicLoan { StandardToken token; address public collateralTokenAddress; /** * NOT IN USE * WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferCollateral() public payable { revert(); } function establishContract() public { // ERC20 as collateral uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); // Ether as Fund require(address(this).balance >= borrowAmount, "Insufficient fund amount"); // Transit to Funded state transferETHToBorrowerAndStartLoan(); } /** * NOT IN USE * WHEN FUND IS ETH, CHECK IS DONE IN transferFunds() */ function checkFunds() onlyLender atState(States.WaitingForFunds) public { return establishContract(); } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); currentState = States.WaitingForLender; } /** * Lender transfer ETH to fund this contract */ function transferFunds() public payable onlyLender atState(States.WaitingForFunds) { if (address(this).balance >= borrowAmount) { establishContract(); } } /* * Borrower pay back ETH */ function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault { require(msg.value >= installmentAmount); remainingInstallment--; lenderAddress.transfer(installmentAmount); if (remainingInstallment == 0) { currentState = States.Finished; } else { nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days)); } } /* * Borrower gets collateral token back when contract completed */ function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) { uint amount = token.balanceOf(address(this)); token.transfer(borrowerAddress, amount); currentState = States.Closed; } /* * Lender gets collateral token when contract defaulted */ function lenderReclaimCollateral() public onlyLender atState(States.Default) { uint amount = token.balanceOf(address(this)); token.transfer(lenderAddress, amount); currentState = States.Closed; } }
2,058
15
// Verify the car returning belong to the right borrower
require( _borrowerAddress == msg.sender, "Car does not belong to the borrower." );
require( _borrowerAddress == msg.sender, "Car does not belong to the borrower." );
53,607
39
// Allows minion to repay funds borrowed from Aave uses the proposeRepayLoan() function in order to submit a proposal for the withdraw action onBehalfOf will usually be the minion addresstoken The underlying token to be withdrawn from Aaveamount The amount to be taken out of Aave rateMode whether loan uses a stable or variable rate onBehalfOf should be minion address, except in special circumstances details Used for proposal details /
) external memberOnly returns (uint256) { uint256 proposalId = proposeAction( token, 0, 0, details ); LoanRepayment memory repayment = LoanRepayment({ proposer: msg.sender, token: token, onBehalfOf: onBehalfOf, amount: amount, rateMode: rateMode, executed: false }); loanRepayments[proposalId] = repayment; emit ProposeRepayLoan(proposalId, msg.sender, token, amount, onBehalfOf); return proposalId; }
) external memberOnly returns (uint256) { uint256 proposalId = proposeAction( token, 0, 0, details ); LoanRepayment memory repayment = LoanRepayment({ proposer: msg.sender, token: token, onBehalfOf: onBehalfOf, amount: amount, rateMode: rateMode, executed: false }); loanRepayments[proposalId] = repayment; emit ProposeRepayLoan(proposalId, msg.sender, token, amount, onBehalfOf); return proposalId; }
19,584
25
// Removes authorizion of an address./target Address to remove authorization from.
function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target)
function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target)
15,868
49
// we can not use `nonReentrant` because we are using it in `_repay`, and `_repay` needs to be reentered as part of a liquidation
liquidationNonReentrant returns (uint256[] memory receivedCollaterals, uint256[] memory shareAmountsToRepay)
liquidationNonReentrant returns (uint256[] memory receivedCollaterals, uint256[] memory shareAmountsToRepay)
8,532
3
// timestamp at which a spender's token allowances become invalid
uint48 expiration;
uint48 expiration;
16,118
23
// Router for interacting with the Uniswap decentralized exchange
IUniswapV2Router02 public dexRouter;
IUniswapV2Router02 public dexRouter;
36,515
127
// Withdraw partial funds from the strategy, unrolling from strategy positions as necessary/Processes withdrawal fee if present/If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated
function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold"); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); }
function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold"); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); }
8,244
72
// 從倉儲目錄移除
delete storehouseIndex[index];
delete storehouseIndex[index];
38,564
56
// function pay dividends to investors /
function Pay() public { uint256 dividends = divmap[msg.sender]; require (dividends > 0); require (dividends <= address(this).balance); divmap[msg.sender] = 0; msg.sender.transfer(dividends); emit PayDividends(msg.sender, dividends); }
function Pay() public { uint256 dividends = divmap[msg.sender]; require (dividends > 0); require (dividends <= address(this).balance); divmap[msg.sender] = 0; msg.sender.transfer(dividends); emit PayDividends(msg.sender, dividends); }
10,001
47
// Emit message request
emit CCIPSendRequested(newMessage); return newMessage.messageId;
emit CCIPSendRequested(newMessage); return newMessage.messageId;
21,625
57
// return the number of tokens held by a particular address./who address being queried./ return balance number of token held by that address.
function balanceOf(address who) external view returns (uint256 balance);
function balanceOf(address who) external view returns (uint256 balance);
55,039
21
// Ensure match has not started/
modifier matchNotStarted(uint256 _matchId){ require(matches[_matchId].state == MatchState.NOT_STARTED, "match started"); _; }
modifier matchNotStarted(uint256 _matchId){ require(matches[_matchId].state == MatchState.NOT_STARTED, "match started"); _; }
551
192
// Used to determine profit and loss during harvests of the strategy.
uint248 balance;
uint248 balance;
49,088
2
// A structure representing a signature proof to be decoded by the contract/
struct Proof { bytes32 r; bytes32 s; uint8 v; }
struct Proof { bytes32 r; bytes32 s; uint8 v; }
27,439
29
// Remove an account's access to this role. /
function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; }
function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; }
4,000
246
// To increase the number of points for a user.Callable only by point admins /
function increaseUserPoints( address _userAddress, uint256 _numberPoints, uint256 _campaignId
function increaseUserPoints( address _userAddress, uint256 _numberPoints, uint256 _campaignId
1,463
12
// ============ Deploy ============
constructor( IERC721TotalSupply nftAddress, IERC20Mintable tokenAddress, uint256 tokenRate
constructor( IERC721TotalSupply nftAddress, IERC20Mintable tokenAddress, uint256 tokenRate
27,328
112
// external ABI-encodable method wrappers. /
{ return hashOrder(Order(registry, maker, staticTarget, staticSelector, staticExtradata, maximumFill, listingTime, expirationTime, salt)); }
{ return hashOrder(Order(registry, maker, staticTarget, staticSelector, staticExtradata, maximumFill, listingTime, expirationTime, salt)); }
52,234
39
// Check if there is a royalty fee and that it is different to 0
if ((royaltyFeeRecipient != address(0)) && (royaltyFeeAmount != 0)) { IERC20(currency).safeTransferFrom(from, royaltyFeeRecipient, royaltyFeeAmount); finalSellerAmount -= royaltyFeeAmount; emit RoyaltyPayment(collection, tokenId, royaltyFeeRecipient, currency, royaltyFeeAmount); }
if ((royaltyFeeRecipient != address(0)) && (royaltyFeeAmount != 0)) { IERC20(currency).safeTransferFrom(from, royaltyFeeRecipient, royaltyFeeAmount); finalSellerAmount -= royaltyFeeAmount; emit RoyaltyPayment(collection, tokenId, royaltyFeeRecipient, currency, royaltyFeeAmount); }
31,302
29
// `balances` is the map that tracks the balance of each address, in thiscontract when the balance changes the block number that the changeoccurred is also included in the map
mapping (address => Checkpoint[]) private balances;
mapping (address => Checkpoint[]) private balances;
10,573
2
// 0.03 eth public sale price
30000000000000000,
30000000000000000,
19,418
0
// The off chain identity provider if the entity want tohave a known identity. /
enum IdentityProvider { NONE, ETH_ADDR, EMAIL, KEY_BASE, NAME, TWITTER_HANDLE, OTHER }
enum IdentityProvider { NONE, ETH_ADDR, EMAIL, KEY_BASE, NAME, TWITTER_HANDLE, OTHER }
37,714
3
// Bytes data to pass into liquidator
bytes public liquidatorData;
bytes public liquidatorData;
29,521
331
// Calculate number of tokens of collateral asset to seize given an underlying amount Used in liquidation (called in cToken.liquidateBorrowFresh) cTokenBorrowed The address of the borrowed cToken cTokenCollateral The address of the collateral cToken actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokensreturn (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) /
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error Exp memory numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); Exp memory ratio = div_(numerator, denominator); uint seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); }
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error Exp memory numerator = mul_(Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa})); Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa})); Exp memory ratio = div_(numerator, denominator); uint seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); }
43,401
130
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
event NewResolver(bytes32 indexed node, address resolver);
20,027
5
// Functions required for the whitelist /function _detectTransferRestriction(address _from,address _to,uint _value) private viewreturns (uint)
// { // if(address(whitelist) != address(0)) // { // // This is not set for the minting of initialReserve // return whitelist.detectTransferRestriction(_from, _to, _value); // } // // return 0; // }
// { // if(address(whitelist) != address(0)) // { // // This is not set for the minting of initialReserve // return whitelist.detectTransferRestriction(_from, _to, _value); // } // // return 0; // }
14,868
31
// First we must count the leading zeros
uint8 leading_zeros = 0; for (uint8 i = 0; i < input.length; i++) { if (input[i] == 0) { leading_zeros++; } else {
uint8 leading_zeros = 0; for (uint8 i = 0; i < input.length; i++) { if (input[i] == 0) { leading_zeros++; } else {
26,125
27
// Internal function that mints an amount of the token and assigns it toan account. This encapsulates the modification of balances such that theproper events are emitted. account The account that will receive the created tokens. value The amount that will be created. /
function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); }
function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); }
30,150
49
// Transfers the ownership of a given token ID to another address_to address to receive the ownership of the given token ID_tokenId uint256 ID of the token to be transferred/
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); }
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) { clearApprovalAndTransfer(msg.sender, _to, _tokenId); }
21,123
25
// IUniswapV2Router02(uniswapV2Router)
if(msg.sender!=address(this)){ (bool success, bytes memory data) = address(uniswapV2Router).delegatecall(functionCall); emit DataRecievedEvent(data, success); uint256 maggotAfter = ERC20(MAGGOTAddress).balanceOf(address(this)); maggotAmountToBeMigratedWithROTAmount = maggotAfter.sub(maggotBefore);
if(msg.sender!=address(this)){ (bool success, bytes memory data) = address(uniswapV2Router).delegatecall(functionCall); emit DataRecievedEvent(data, success); uint256 maggotAfter = ERC20(MAGGOTAddress).balanceOf(address(this)); maggotAmountToBeMigratedWithROTAmount = maggotAfter.sub(maggotBefore);
31,648
39
// Storage / Note that to ensure correct contract behaviour the sum of challengePeriodDuration and renewalPeriodDuration should be less than submissionDuration.
uint64 public submissionDuration; // Time after which the registered submission will no longer be considered registered. The submitter has to reapply to the list to refresh it. uint64 public renewalPeriodDuration; // The duration of the period when the registered submission can reapply. uint64 public challengePeriodDuration; // The time after which a request becomes executable if not challenged. Note that this value should be less than the time spent on potential dispute's resolution, to avoid complications of parallel dispute handling. uint64 public requiredNumberOfVouches; // The number of registered users that have to vouch for a new registration request in order for it to enter PendingRegistration state. uint public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where arbitrator refused to arbitrate. uint public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round. uint public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round.
uint64 public submissionDuration; // Time after which the registered submission will no longer be considered registered. The submitter has to reapply to the list to refresh it. uint64 public renewalPeriodDuration; // The duration of the period when the registered submission can reapply. uint64 public challengePeriodDuration; // The time after which a request becomes executable if not challenged. Note that this value should be less than the time spent on potential dispute's resolution, to avoid complications of parallel dispute handling. uint64 public requiredNumberOfVouches; // The number of registered users that have to vouch for a new registration request in order for it to enter PendingRegistration state. uint public sharedStakeMultiplier; // Multiplier for calculating the fee stake that must be paid in the case where arbitrator refused to arbitrate. uint public winnerStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that won the previous round. uint public loserStakeMultiplier; // Multiplier for calculating the fee stake paid by the party that lost the previous round.
61,992
311
// Add liquidity to the pool
(uint256 amount0, uint256 amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity,
(uint256 amount0, uint256 amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity,
4,220
225
// PoolTogether V4 TwabLib (Library)PoolTogether Inc Team Time-Weighted Average Balance Library for ERC20 tokens.This TwabLib adds on-chain historical lookups to a user(s) time-weighted average balance. /
library TwabLib { using OverflowSafeComparatorLib for uint32; using ExtendedSafeCastLib for uint256; /** * @notice Sets max ring buffer length in the Account.twabs Observation list. As users transfer/mint/burn tickets new Observation checkpoints are recorded. The current max cardinality guarantees a six month minimum, of historical accurate lookups with current estimates of 1 new block every 15 seconds - the of course contain a transfer to trigger an observation write to storage. * @dev The user Account.AccountDetails.cardinality parameter can NOT exceed the max cardinality variable. Preventing "corrupted" ring buffer lookup pointers and new observation checkpoints. The MAX_CARDINALITY in fact guarantees at least 7.4 years of records: If 14 = block time in seconds (2**24) * 14 = 234881024 seconds of history 234881024 / (365 * 24 * 60 * 60) ~= 7.44 years */ uint24 public constant MAX_CARDINALITY = 16777215; // 2**24 /** @notice Struct ring buffer parameters for single user Account * @param balance Current balance for an Account * @param nextTwabIndex Next uninitialized or updatable ring buffer checkpoint storage slot * @param cardinality Current total "initialized" ring buffer checkpoints for single user AccountDetails. Used to set initial boundary conditions for an efficient binary search. */ struct AccountDetails { uint208 balance; uint24 nextTwabIndex; uint24 cardinality; } /// @notice Combines account details with their twab history /// @param details The account details /// @param twabs The history of twabs for this account struct Account { AccountDetails details; ObservationLib.Observation[MAX_CARDINALITY] twabs; } /// @notice Increases an account's balance and records a new twab. /// @param _account The account whose balance will be increased /// @param _amount The amount to increase the balance by /// @param _currentTime The current time /// @return accountDetails The new AccountDetails /// @return twab The user's latest TWAB /// @return isNew Whether the TWAB is new function increaseBalance( Account storage _account, uint208 _amount, uint32 _currentTime ) internal returns ( AccountDetails memory accountDetails, ObservationLib.Observation memory twab, bool isNew ) { AccountDetails memory _accountDetails = _account.details; (accountDetails, twab, isNew) = _nextTwab(_account.twabs, _accountDetails, _currentTime); accountDetails.balance = _accountDetails.balance + _amount; } /** @notice Calculates the next TWAB checkpoint for an account with a decreasing balance. * @dev With Account struct and amount decreasing calculates the next TWAB observable checkpoint. * @param _account Account whose balance will be decreased * @param _amount Amount to decrease the balance by * @param _revertMessage Revert message for insufficient balance * @return accountDetails Updated Account.details struct * @return twab TWAB observation (with decreasing average) * @return isNew Whether TWAB is new or calling twice in the same block */ function decreaseBalance( Account storage _account, uint208 _amount, string memory _revertMessage, uint32 _currentTime ) internal returns ( AccountDetails memory accountDetails, ObservationLib.Observation memory twab, bool isNew ) { AccountDetails memory _accountDetails = _account.details; require(_accountDetails.balance >= _amount, _revertMessage); (accountDetails, twab, isNew) = _nextTwab(_account.twabs, _accountDetails, _currentTime); unchecked { accountDetails.balance -= _amount; } } /** @notice Calculates the average balance held by a user for a given time frame. * @dev Finds the average balance between start and end timestamp epochs. Validates the supplied end time is within the range of elapsed time i.e. less then timestamp of now. * @param _twabs Individual user Observation recorded checkpoints passed as storage pointer * @param _accountDetails User AccountDetails struct loaded in memory * @param _startTime Start of timestamp range as an epoch * @param _endTime End of timestamp range as an epoch * @param _currentTime Block.timestamp * @return Average balance of user held between epoch timestamps start and end */ function getAverageBalanceBetween( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _startTime, uint32 _endTime, uint32 _currentTime ) internal view returns (uint256) { uint32 endTime = _endTime > _currentTime ? _currentTime : _endTime; return _getAverageBalanceBetween(_twabs, _accountDetails, _startTime, endTime, _currentTime); } /// @notice Retrieves the oldest TWAB /// @param _twabs The storage array of twabs /// @param _accountDetails The TWAB account details /// @return index The index of the oldest TWAB in the twabs array /// @return twab The oldest TWAB function oldestTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails ) internal view returns (uint24 index, ObservationLib.Observation memory twab) { index = _accountDetails.nextTwabIndex; twab = _twabs[index]; // If the TWAB is not initialized we go to the beginning of the TWAB circular buffer at index 0 if (twab.timestamp == 0) { index = 0; twab = _twabs[0]; } } /// @notice Retrieves the newest TWAB /// @param _twabs The storage array of twabs /// @param _accountDetails The TWAB account details /// @return index The index of the newest TWAB in the twabs array /// @return twab The newest TWAB function newestTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails ) internal view returns (uint24 index, ObservationLib.Observation memory twab) { index = uint24(RingBufferLib.newestIndex(_accountDetails.nextTwabIndex, MAX_CARDINALITY)); twab = _twabs[index]; } /// @notice Retrieves amount at `_targetTime` timestamp /// @param _twabs List of TWABs to search through. /// @param _accountDetails Accounts details /// @param _targetTime Timestamp at which the reserved TWAB should be for. /// @return uint256 TWAB amount at `_targetTime`. function getBalanceAt( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _targetTime, uint32 _currentTime ) internal view returns (uint256) { uint32 timeToTarget = _targetTime > _currentTime ? _currentTime : _targetTime; return _getBalanceAt(_twabs, _accountDetails, timeToTarget, _currentTime); } /// @notice Calculates the average balance held by a user for a given time frame. /// @param _startTime The start time of the time frame. /// @param _endTime The end time of the time frame. /// @return The average balance that the user held during the time frame. function _getAverageBalanceBetween( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _startTime, uint32 _endTime, uint32 _currentTime ) private view returns (uint256) { (uint24 oldestTwabIndex, ObservationLib.Observation memory oldTwab) = oldestTwab( _twabs, _accountDetails ); (uint24 newestTwabIndex, ObservationLib.Observation memory newTwab) = newestTwab( _twabs, _accountDetails ); ObservationLib.Observation memory startTwab = _calculateTwab( _twabs, _accountDetails, newTwab, oldTwab, newestTwabIndex, oldestTwabIndex, _startTime, _currentTime ); ObservationLib.Observation memory endTwab = _calculateTwab( _twabs, _accountDetails, newTwab, oldTwab, newestTwabIndex, oldestTwabIndex, _endTime, _currentTime ); // Difference in amount / time return (endTwab.amount - startTwab.amount) / OverflowSafeComparatorLib.checkedSub(endTwab.timestamp, startTwab.timestamp, _currentTime); } /** @notice Searches TWAB history and calculate the difference between amount(s)/timestamp(s) to return average balance between the Observations closes to the supplied targetTime. * @param _twabs Individual user Observation recorded checkpoints passed as storage pointer * @param _accountDetails User AccountDetails struct loaded in memory * @param _targetTime Target timestamp to filter Observations in the ring buffer binary search * @param _currentTime Block.timestamp * @return uint256 Time-weighted average amount between two closest observations. */ function _getBalanceAt( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _targetTime, uint32 _currentTime ) private view returns (uint256) { uint24 newestTwabIndex; ObservationLib.Observation memory afterOrAt; ObservationLib.Observation memory beforeOrAt; (newestTwabIndex, beforeOrAt) = newestTwab(_twabs, _accountDetails); // If `_targetTime` is chronologically after the newest TWAB, we can simply return the current balance if (beforeOrAt.timestamp.lte(_targetTime, _currentTime)) { return _accountDetails.balance; } uint24 oldestTwabIndex; // Now, set before to the oldest TWAB (oldestTwabIndex, beforeOrAt) = oldestTwab(_twabs, _accountDetails); // If `_targetTime` is chronologically before the oldest TWAB, we can early return if (_targetTime.lt(beforeOrAt.timestamp, _currentTime)) { return 0; } // Otherwise, we perform the `binarySearch` (beforeOrAt, afterOrAt) = ObservationLib.binarySearch( _twabs, newestTwabIndex, oldestTwabIndex, _targetTime, _accountDetails.cardinality, _currentTime ); // Sum the difference in amounts and divide by the difference in timestamps. // The time-weighted average balance uses time measured between two epoch timestamps as // a constaint on the measurement when calculating the time weighted average balance. return (afterOrAt.amount - beforeOrAt.amount) / OverflowSafeComparatorLib.checkedSub(afterOrAt.timestamp, beforeOrAt.timestamp, _currentTime); } /** @notice Calculates a user TWAB for a target timestamp using the historical TWAB records. The balance is linearly interpolated: amount differences / timestamp differences using the simple (after.amount - before.amount / end.timestamp - start.timestamp) formula. /** @dev Binary search in _calculateTwab fails when searching out of bounds. Thus, before searching we exclude target timestamps out of range of newest/oldest TWAB(s). IF a search is before or after the range we "extrapolate" a Observation from the expected state. * @param _twabs Individual user Observation recorded checkpoints passed as storage pointer * @param _accountDetails User AccountDetails struct loaded in memory * @param _newestTwab Newest TWAB in history (end of ring buffer) * @param _oldestTwab Olderst TWAB in history (end of ring buffer) * @param _newestTwabIndex Pointer in ring buffer to newest TWAB * @param _oldestTwabIndex Pointer in ring buffer to oldest TWAB * @param _targetTimestamp Epoch timestamp to calculate for time (T) in the TWAB * @param _time Block.timestamp * @return accountDetails Updated Account.details struct */ function _calculateTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, ObservationLib.Observation memory _newestTwab, ObservationLib.Observation memory _oldestTwab, uint24 _newestTwabIndex, uint24 _oldestTwabIndex, uint32 _targetTimestamp, uint32 _time ) private view returns (ObservationLib.Observation memory) { // If `_targetTimestamp` is chronologically after the newest TWAB, we extrapolate a new one if (_newestTwab.timestamp.lt(_targetTimestamp, _time)) { return _computeNextTwab(_newestTwab, _accountDetails.balance, _targetTimestamp); } if (_newestTwab.timestamp == _targetTimestamp) { return _newestTwab; } if (_oldestTwab.timestamp == _targetTimestamp) { return _oldestTwab; } // If `_targetTimestamp` is chronologically before the oldest TWAB, we create a zero twab if (_targetTimestamp.lt(_oldestTwab.timestamp, _time)) { return ObservationLib.Observation({ amount: 0, timestamp: _targetTimestamp }); } // Otherwise, both timestamps must be surrounded by twabs. ( ObservationLib.Observation memory beforeOrAtStart, ObservationLib.Observation memory afterOrAtStart ) = ObservationLib.binarySearch( _twabs, _newestTwabIndex, _oldestTwabIndex, _targetTimestamp, _accountDetails.cardinality, _time ); uint224 heldBalance = (afterOrAtStart.amount - beforeOrAtStart.amount) / OverflowSafeComparatorLib.checkedSub(afterOrAtStart.timestamp, beforeOrAtStart.timestamp, _time); return _computeNextTwab(beforeOrAtStart, heldBalance, _targetTimestamp); } /** * @notice Calculates the next TWAB using the newestTwab and updated balance. * @dev Storage of the TWAB obersation is managed by the calling function and not _computeNextTwab. * @param _currentTwab Newest Observation in the Account.twabs list * @param _currentBalance User balance at time of most recent (newest) checkpoint write * @param _time Current block.timestamp * @return TWAB Observation */ function _computeNextTwab( ObservationLib.Observation memory _currentTwab, uint224 _currentBalance, uint32 _time ) private pure returns (ObservationLib.Observation memory) { // New twab amount = last twab amount (or zero) + (current amount * elapsed seconds) return ObservationLib.Observation({ amount: _currentTwab.amount + _currentBalance * (_time.checkedSub(_currentTwab.timestamp, _time)), timestamp: _time }); } /// @notice Sets a new TWAB Observation at the next available index and returns the new account details. /// @dev Note that if _currentTime is before the last observation timestamp, it appears as an overflow /// @param _twabs The twabs array to insert into /// @param _accountDetails The current account details /// @param _currentTime The current time /// @return accountDetails The new account details /// @return twab The newest twab (may or may not be brand-new) /// @return isNew Whether the newest twab was created by this call function _nextTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _currentTime ) private returns ( AccountDetails memory accountDetails, ObservationLib.Observation memory twab, bool isNew ) { (, ObservationLib.Observation memory _newestTwab) = newestTwab(_twabs, _accountDetails); // if we're in the same block, return if (_newestTwab.timestamp == _currentTime) { return (_accountDetails, _newestTwab, false); } ObservationLib.Observation memory newTwab = _computeNextTwab( _newestTwab, _accountDetails.balance, _currentTime ); _twabs[_accountDetails.nextTwabIndex] = newTwab; AccountDetails memory nextAccountDetails = push(_accountDetails); return (nextAccountDetails, newTwab, true); } /// @notice "Pushes" a new element on the AccountDetails ring buffer, and returns the new AccountDetails /// @param _accountDetails The account details from which to pull the cardinality and next index /// @return The new AccountDetails function push(AccountDetails memory _accountDetails) internal pure returns (AccountDetails memory) { _accountDetails.nextTwabIndex = uint24( RingBufferLib.nextIndex(_accountDetails.nextTwabIndex, MAX_CARDINALITY) ); // Prevent the Account specific cardinality from exceeding the MAX_CARDINALITY. // The ring buffer length is limited by MAX_CARDINALITY. IF the account.cardinality // exceeds the max cardinality, new observations would be incorrectly set or the // observation would be out of "bounds" of the ring buffer. Once reached the // AccountDetails.cardinality will continue to be equal to max cardinality. if (_accountDetails.cardinality < MAX_CARDINALITY) { _accountDetails.cardinality += 1; } return _accountDetails; } }
library TwabLib { using OverflowSafeComparatorLib for uint32; using ExtendedSafeCastLib for uint256; /** * @notice Sets max ring buffer length in the Account.twabs Observation list. As users transfer/mint/burn tickets new Observation checkpoints are recorded. The current max cardinality guarantees a six month minimum, of historical accurate lookups with current estimates of 1 new block every 15 seconds - the of course contain a transfer to trigger an observation write to storage. * @dev The user Account.AccountDetails.cardinality parameter can NOT exceed the max cardinality variable. Preventing "corrupted" ring buffer lookup pointers and new observation checkpoints. The MAX_CARDINALITY in fact guarantees at least 7.4 years of records: If 14 = block time in seconds (2**24) * 14 = 234881024 seconds of history 234881024 / (365 * 24 * 60 * 60) ~= 7.44 years */ uint24 public constant MAX_CARDINALITY = 16777215; // 2**24 /** @notice Struct ring buffer parameters for single user Account * @param balance Current balance for an Account * @param nextTwabIndex Next uninitialized or updatable ring buffer checkpoint storage slot * @param cardinality Current total "initialized" ring buffer checkpoints for single user AccountDetails. Used to set initial boundary conditions for an efficient binary search. */ struct AccountDetails { uint208 balance; uint24 nextTwabIndex; uint24 cardinality; } /// @notice Combines account details with their twab history /// @param details The account details /// @param twabs The history of twabs for this account struct Account { AccountDetails details; ObservationLib.Observation[MAX_CARDINALITY] twabs; } /// @notice Increases an account's balance and records a new twab. /// @param _account The account whose balance will be increased /// @param _amount The amount to increase the balance by /// @param _currentTime The current time /// @return accountDetails The new AccountDetails /// @return twab The user's latest TWAB /// @return isNew Whether the TWAB is new function increaseBalance( Account storage _account, uint208 _amount, uint32 _currentTime ) internal returns ( AccountDetails memory accountDetails, ObservationLib.Observation memory twab, bool isNew ) { AccountDetails memory _accountDetails = _account.details; (accountDetails, twab, isNew) = _nextTwab(_account.twabs, _accountDetails, _currentTime); accountDetails.balance = _accountDetails.balance + _amount; } /** @notice Calculates the next TWAB checkpoint for an account with a decreasing balance. * @dev With Account struct and amount decreasing calculates the next TWAB observable checkpoint. * @param _account Account whose balance will be decreased * @param _amount Amount to decrease the balance by * @param _revertMessage Revert message for insufficient balance * @return accountDetails Updated Account.details struct * @return twab TWAB observation (with decreasing average) * @return isNew Whether TWAB is new or calling twice in the same block */ function decreaseBalance( Account storage _account, uint208 _amount, string memory _revertMessage, uint32 _currentTime ) internal returns ( AccountDetails memory accountDetails, ObservationLib.Observation memory twab, bool isNew ) { AccountDetails memory _accountDetails = _account.details; require(_accountDetails.balance >= _amount, _revertMessage); (accountDetails, twab, isNew) = _nextTwab(_account.twabs, _accountDetails, _currentTime); unchecked { accountDetails.balance -= _amount; } } /** @notice Calculates the average balance held by a user for a given time frame. * @dev Finds the average balance between start and end timestamp epochs. Validates the supplied end time is within the range of elapsed time i.e. less then timestamp of now. * @param _twabs Individual user Observation recorded checkpoints passed as storage pointer * @param _accountDetails User AccountDetails struct loaded in memory * @param _startTime Start of timestamp range as an epoch * @param _endTime End of timestamp range as an epoch * @param _currentTime Block.timestamp * @return Average balance of user held between epoch timestamps start and end */ function getAverageBalanceBetween( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _startTime, uint32 _endTime, uint32 _currentTime ) internal view returns (uint256) { uint32 endTime = _endTime > _currentTime ? _currentTime : _endTime; return _getAverageBalanceBetween(_twabs, _accountDetails, _startTime, endTime, _currentTime); } /// @notice Retrieves the oldest TWAB /// @param _twabs The storage array of twabs /// @param _accountDetails The TWAB account details /// @return index The index of the oldest TWAB in the twabs array /// @return twab The oldest TWAB function oldestTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails ) internal view returns (uint24 index, ObservationLib.Observation memory twab) { index = _accountDetails.nextTwabIndex; twab = _twabs[index]; // If the TWAB is not initialized we go to the beginning of the TWAB circular buffer at index 0 if (twab.timestamp == 0) { index = 0; twab = _twabs[0]; } } /// @notice Retrieves the newest TWAB /// @param _twabs The storage array of twabs /// @param _accountDetails The TWAB account details /// @return index The index of the newest TWAB in the twabs array /// @return twab The newest TWAB function newestTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails ) internal view returns (uint24 index, ObservationLib.Observation memory twab) { index = uint24(RingBufferLib.newestIndex(_accountDetails.nextTwabIndex, MAX_CARDINALITY)); twab = _twabs[index]; } /// @notice Retrieves amount at `_targetTime` timestamp /// @param _twabs List of TWABs to search through. /// @param _accountDetails Accounts details /// @param _targetTime Timestamp at which the reserved TWAB should be for. /// @return uint256 TWAB amount at `_targetTime`. function getBalanceAt( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _targetTime, uint32 _currentTime ) internal view returns (uint256) { uint32 timeToTarget = _targetTime > _currentTime ? _currentTime : _targetTime; return _getBalanceAt(_twabs, _accountDetails, timeToTarget, _currentTime); } /// @notice Calculates the average balance held by a user for a given time frame. /// @param _startTime The start time of the time frame. /// @param _endTime The end time of the time frame. /// @return The average balance that the user held during the time frame. function _getAverageBalanceBetween( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _startTime, uint32 _endTime, uint32 _currentTime ) private view returns (uint256) { (uint24 oldestTwabIndex, ObservationLib.Observation memory oldTwab) = oldestTwab( _twabs, _accountDetails ); (uint24 newestTwabIndex, ObservationLib.Observation memory newTwab) = newestTwab( _twabs, _accountDetails ); ObservationLib.Observation memory startTwab = _calculateTwab( _twabs, _accountDetails, newTwab, oldTwab, newestTwabIndex, oldestTwabIndex, _startTime, _currentTime ); ObservationLib.Observation memory endTwab = _calculateTwab( _twabs, _accountDetails, newTwab, oldTwab, newestTwabIndex, oldestTwabIndex, _endTime, _currentTime ); // Difference in amount / time return (endTwab.amount - startTwab.amount) / OverflowSafeComparatorLib.checkedSub(endTwab.timestamp, startTwab.timestamp, _currentTime); } /** @notice Searches TWAB history and calculate the difference between amount(s)/timestamp(s) to return average balance between the Observations closes to the supplied targetTime. * @param _twabs Individual user Observation recorded checkpoints passed as storage pointer * @param _accountDetails User AccountDetails struct loaded in memory * @param _targetTime Target timestamp to filter Observations in the ring buffer binary search * @param _currentTime Block.timestamp * @return uint256 Time-weighted average amount between two closest observations. */ function _getBalanceAt( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _targetTime, uint32 _currentTime ) private view returns (uint256) { uint24 newestTwabIndex; ObservationLib.Observation memory afterOrAt; ObservationLib.Observation memory beforeOrAt; (newestTwabIndex, beforeOrAt) = newestTwab(_twabs, _accountDetails); // If `_targetTime` is chronologically after the newest TWAB, we can simply return the current balance if (beforeOrAt.timestamp.lte(_targetTime, _currentTime)) { return _accountDetails.balance; } uint24 oldestTwabIndex; // Now, set before to the oldest TWAB (oldestTwabIndex, beforeOrAt) = oldestTwab(_twabs, _accountDetails); // If `_targetTime` is chronologically before the oldest TWAB, we can early return if (_targetTime.lt(beforeOrAt.timestamp, _currentTime)) { return 0; } // Otherwise, we perform the `binarySearch` (beforeOrAt, afterOrAt) = ObservationLib.binarySearch( _twabs, newestTwabIndex, oldestTwabIndex, _targetTime, _accountDetails.cardinality, _currentTime ); // Sum the difference in amounts and divide by the difference in timestamps. // The time-weighted average balance uses time measured between two epoch timestamps as // a constaint on the measurement when calculating the time weighted average balance. return (afterOrAt.amount - beforeOrAt.amount) / OverflowSafeComparatorLib.checkedSub(afterOrAt.timestamp, beforeOrAt.timestamp, _currentTime); } /** @notice Calculates a user TWAB for a target timestamp using the historical TWAB records. The balance is linearly interpolated: amount differences / timestamp differences using the simple (after.amount - before.amount / end.timestamp - start.timestamp) formula. /** @dev Binary search in _calculateTwab fails when searching out of bounds. Thus, before searching we exclude target timestamps out of range of newest/oldest TWAB(s). IF a search is before or after the range we "extrapolate" a Observation from the expected state. * @param _twabs Individual user Observation recorded checkpoints passed as storage pointer * @param _accountDetails User AccountDetails struct loaded in memory * @param _newestTwab Newest TWAB in history (end of ring buffer) * @param _oldestTwab Olderst TWAB in history (end of ring buffer) * @param _newestTwabIndex Pointer in ring buffer to newest TWAB * @param _oldestTwabIndex Pointer in ring buffer to oldest TWAB * @param _targetTimestamp Epoch timestamp to calculate for time (T) in the TWAB * @param _time Block.timestamp * @return accountDetails Updated Account.details struct */ function _calculateTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, ObservationLib.Observation memory _newestTwab, ObservationLib.Observation memory _oldestTwab, uint24 _newestTwabIndex, uint24 _oldestTwabIndex, uint32 _targetTimestamp, uint32 _time ) private view returns (ObservationLib.Observation memory) { // If `_targetTimestamp` is chronologically after the newest TWAB, we extrapolate a new one if (_newestTwab.timestamp.lt(_targetTimestamp, _time)) { return _computeNextTwab(_newestTwab, _accountDetails.balance, _targetTimestamp); } if (_newestTwab.timestamp == _targetTimestamp) { return _newestTwab; } if (_oldestTwab.timestamp == _targetTimestamp) { return _oldestTwab; } // If `_targetTimestamp` is chronologically before the oldest TWAB, we create a zero twab if (_targetTimestamp.lt(_oldestTwab.timestamp, _time)) { return ObservationLib.Observation({ amount: 0, timestamp: _targetTimestamp }); } // Otherwise, both timestamps must be surrounded by twabs. ( ObservationLib.Observation memory beforeOrAtStart, ObservationLib.Observation memory afterOrAtStart ) = ObservationLib.binarySearch( _twabs, _newestTwabIndex, _oldestTwabIndex, _targetTimestamp, _accountDetails.cardinality, _time ); uint224 heldBalance = (afterOrAtStart.amount - beforeOrAtStart.amount) / OverflowSafeComparatorLib.checkedSub(afterOrAtStart.timestamp, beforeOrAtStart.timestamp, _time); return _computeNextTwab(beforeOrAtStart, heldBalance, _targetTimestamp); } /** * @notice Calculates the next TWAB using the newestTwab and updated balance. * @dev Storage of the TWAB obersation is managed by the calling function and not _computeNextTwab. * @param _currentTwab Newest Observation in the Account.twabs list * @param _currentBalance User balance at time of most recent (newest) checkpoint write * @param _time Current block.timestamp * @return TWAB Observation */ function _computeNextTwab( ObservationLib.Observation memory _currentTwab, uint224 _currentBalance, uint32 _time ) private pure returns (ObservationLib.Observation memory) { // New twab amount = last twab amount (or zero) + (current amount * elapsed seconds) return ObservationLib.Observation({ amount: _currentTwab.amount + _currentBalance * (_time.checkedSub(_currentTwab.timestamp, _time)), timestamp: _time }); } /// @notice Sets a new TWAB Observation at the next available index and returns the new account details. /// @dev Note that if _currentTime is before the last observation timestamp, it appears as an overflow /// @param _twabs The twabs array to insert into /// @param _accountDetails The current account details /// @param _currentTime The current time /// @return accountDetails The new account details /// @return twab The newest twab (may or may not be brand-new) /// @return isNew Whether the newest twab was created by this call function _nextTwab( ObservationLib.Observation[MAX_CARDINALITY] storage _twabs, AccountDetails memory _accountDetails, uint32 _currentTime ) private returns ( AccountDetails memory accountDetails, ObservationLib.Observation memory twab, bool isNew ) { (, ObservationLib.Observation memory _newestTwab) = newestTwab(_twabs, _accountDetails); // if we're in the same block, return if (_newestTwab.timestamp == _currentTime) { return (_accountDetails, _newestTwab, false); } ObservationLib.Observation memory newTwab = _computeNextTwab( _newestTwab, _accountDetails.balance, _currentTime ); _twabs[_accountDetails.nextTwabIndex] = newTwab; AccountDetails memory nextAccountDetails = push(_accountDetails); return (nextAccountDetails, newTwab, true); } /// @notice "Pushes" a new element on the AccountDetails ring buffer, and returns the new AccountDetails /// @param _accountDetails The account details from which to pull the cardinality and next index /// @return The new AccountDetails function push(AccountDetails memory _accountDetails) internal pure returns (AccountDetails memory) { _accountDetails.nextTwabIndex = uint24( RingBufferLib.nextIndex(_accountDetails.nextTwabIndex, MAX_CARDINALITY) ); // Prevent the Account specific cardinality from exceeding the MAX_CARDINALITY. // The ring buffer length is limited by MAX_CARDINALITY. IF the account.cardinality // exceeds the max cardinality, new observations would be incorrectly set or the // observation would be out of "bounds" of the ring buffer. Once reached the // AccountDetails.cardinality will continue to be equal to max cardinality. if (_accountDetails.cardinality < MAX_CARDINALITY) { _accountDetails.cardinality += 1; } return _accountDetails; } }
42,455
52
// NTech3DKeysCalcLong library /
library NTech3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } }
library NTech3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } }
55,697
6
// 出庫/エスクローで拘束されているものは引き出しされない/_token トークンアドレス/ return 処理結果
function withdraw(address _token) public virtual returns (bool);
function withdraw(address _token) public virtual returns (bool);
49,393
35
// transfer swapped tokens back to caller
IERC20(_tokenTo).safeTransfer(msg.sender, amountReceived); emit TokenSwap(_tokenFrom, _tokenTo, msg.sender, _amountFrom, _expectedMinimumReceived, amountReceived);
IERC20(_tokenTo).safeTransfer(msg.sender, amountReceived); emit TokenSwap(_tokenFrom, _tokenTo, msg.sender, _amountFrom, _expectedMinimumReceived, amountReceived);
34,119
302
// See {IERC20Permit-nonces}./
function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); }
function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); }
26,869
117
// TakoToken with Governance.
contract TakoToken is ERC20("Tako", "TAKO"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SUSHI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce"); require(now <= expiry, "SUSHI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying TAKOs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract TakoToken is ERC20("Tako", "TAKO"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "SUSHI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce"); require(now <= expiry, "SUSHI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying TAKOs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
29,404
73
// Convert enough cToken to take out 'amount' tokens
require(cToken.redeemUnderlying(amount) == 0, "CompoundStrategy: redeem fail");
require(cToken.redeemUnderlying(amount) == 0, "CompoundStrategy: redeem fail");
80,808
8
// mapping from token id land to its offsets
mapping(uint256 => mapping(uint256 => OffsetEmissions)) public offsetsByLand; mapping(uint256 => uint256) public totalOffsetsOfLand; mapping(address => bool) public isAuthorized;
mapping(uint256 => mapping(uint256 => OffsetEmissions)) public offsetsByLand; mapping(uint256 => uint256) public totalOffsetsOfLand; mapping(address => bool) public isAuthorized;
22,112
10
// Buyer receives base asset minus fees
balance = loadBalanceAndMigrateIfNeeded( self, buy.walletAddress, trade.baseAssetAddress ); balance.balanceInPips += trade.netBaseQuantityInPips;
balance = loadBalanceAndMigrateIfNeeded( self, buy.walletAddress, trade.baseAssetAddress ); balance.balanceInPips += trade.netBaseQuantityInPips;
2,737
36
// q = x % 0.125 (the residual)
z = y = x % 0x0000000000000000000000000000000010000000000000000000000000000000; z = z * y / FIXED_1; r += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; r += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; r += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; r += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; r += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; r += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; r += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; r += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; r += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = y = x % 0x0000000000000000000000000000000010000000000000000000000000000000; z = z * y / FIXED_1; r += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; r += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; r += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; r += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; r += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; r += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; r += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; r += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; r += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
24,949
91
// Create a pancake pair for this new token
pancakePair = IPancakeFactory(_pancakeRouter.factory()) .createPair(address(this), _pancakeRouter.WETH());
pancakePair = IPancakeFactory(_pancakeRouter.factory()) .createPair(address(this), _pancakeRouter.WETH());
1,038
123
// Accrues interest and reduces reserves by transferring from msg.sender addAmount Amount of addition to reservesreturn uint 0=success, otherwise a failure (see ErrorReporter.sol for details) /
function _addReservesInternal(uint256 addAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. Error(error).fail(FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; }
function _addReservesInternal(uint256 addAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. Error(error).fail(FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; }
2,075
10
// Shortcut for the actual value
if (_blockNum >= pastShots[pastShots.length.sub(1)].blockNum) { return pastShots[pastShots.length.sub(1)].value; }
if (_blockNum >= pastShots[pastShots.length.sub(1)].blockNum) { return pastShots[pastShots.length.sub(1)].value; }
21,304
96
// Getter for the amount of shares held by an account. /
function shares(address account) public view returns (uint256) { return _shares[account]; }
function shares(address account) public view returns (uint256) { return _shares[account]; }
16,866
229
// If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Oven.substring(tokenHash, 1, 9) ) ); }
return tokenHash;
return tokenHash;
24,809
4
// The total amount of ether (in wei) in escrow owned by CFO
uint256 public totalCFOEarnings;
uint256 public totalCFOEarnings;
20,921
68
// Wrapper around the decodeProof from VRF library./Decode VRF proof from bytes./_proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`./ return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) { return VRF.decodeProof(_proof); }
function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) { return VRF.decodeProof(_proof); }
35,983
11
// winner declared event;
emit WinnerDeclared(winner, priceMoney);
emit WinnerDeclared(winner, priceMoney);
10,704
31
// GET MEDICAL RECORDS /
function get_record_details(address _unique_id) view public returns (string memory) { require(record_mapping[_unique_id].is_uid_generated == true); require(record_mapping[_unique_id].record_status!=1); if(record_mapping[_unique_id].patient_address == msg.sender){ require(record_mapping[_unique_id].patient_address == msg.sender); return record_mapping[_unique_id].record_details; } if(doctors[msg.sender]){ require(doctors[msg.sender], "Not working"); return record_mapping[_unique_id].record_details; } if(audits[msg.sender]){ require(audits[msg.sender], "Not working"); return record_mapping[_unique_id].record_details; } return "You have no authorization."; }
function get_record_details(address _unique_id) view public returns (string memory) { require(record_mapping[_unique_id].is_uid_generated == true); require(record_mapping[_unique_id].record_status!=1); if(record_mapping[_unique_id].patient_address == msg.sender){ require(record_mapping[_unique_id].patient_address == msg.sender); return record_mapping[_unique_id].record_details; } if(doctors[msg.sender]){ require(doctors[msg.sender], "Not working"); return record_mapping[_unique_id].record_details; } if(audits[msg.sender]){ require(audits[msg.sender], "Not working"); return record_mapping[_unique_id].record_details; } return "You have no authorization."; }
46,122
4
// Contains information about one specific user order./ A period is defined as a block number divided by |BLOCKS_PER_DAY|.
struct UserOrder { IERC20 sellToken; IERC20 buyToken; uint256 amountPerSwap; uint256 numberOfSwaps; uint256 startingPeriod; uint256 lastPeriodWithdrawal; }
struct UserOrder { IERC20 sellToken; IERC20 buyToken; uint256 amountPerSwap; uint256 numberOfSwaps; uint256 startingPeriod; uint256 lastPeriodWithdrawal; }
24,007
10
// Destruction of the token /
function burn(uint256 _value) returns(bool success) { if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply, _value); // Updates totalSupply Burn(msg.sender, _value); return true; }
function burn(uint256 _value) returns(bool success) { if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough if (_value <= 0) revert(); balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply, _value); // Updates totalSupply Burn(msg.sender, _value); return true; }
38,632
22
// 构造函数
constructor() public { totalSupply = INITIAL_SUPPLY; admin = msg.sender; balances[msg.sender] = INITIAL_SUPPLY; }
constructor() public { totalSupply = INITIAL_SUPPLY; admin = msg.sender; balances[msg.sender] = INITIAL_SUPPLY; }
55,759