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 |
|---|---|---|---|---|
159 | // `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN` |
uint private _swapFee;
uint private _reservesRatio;
bool private _finalized;
address[] private _tokens;
|
uint private _swapFee;
uint private _reservesRatio;
bool private _finalized;
address[] private _tokens;
| 902 |
0 | // Max Supply | uint256 public constant TOTAL_SUPPLY = 10000;
| uint256 public constant TOTAL_SUPPLY = 10000;
| 17,824 |
3 | // Transfers ownership of this contract to the finalOwner.Only callable by the finalOwner, which is intended to be our multisig.This function shouldn't be necessary, but it gives a sense of reassurance that we canrecover if something really surprising goes wrong. / | function returnOwnership() external {
require(msg.sender == finalOwner, "ChugSplashDictator: only callable by finalOwner");
target.setOwner(finalOwner);
}
| function returnOwnership() external {
require(msg.sender == finalOwner, "ChugSplashDictator: only callable by finalOwner");
target.setOwner(finalOwner);
}
| 12,899 |
67 | // Profit share owing/_investor An Ethereum address/ return A positive number | function profitShareOwing(address _investor) public view returns (uint) {
if (!totalSupplyIsFixed || totalSupply_ == 0) {
return 0;
}
InvestorAccount memory account = accounts[_investor];
return totalProfits.sub(account.lastTotalProfits)
.mul(account.balance)
.div(totalSupply_)
.add(account.profitShare);
}
| function profitShareOwing(address _investor) public view returns (uint) {
if (!totalSupplyIsFixed || totalSupply_ == 0) {
return 0;
}
InvestorAccount memory account = accounts[_investor];
return totalProfits.sub(account.lastTotalProfits)
.mul(account.balance)
.div(totalSupply_)
.add(account.profitShare);
}
| 75,258 |
53 | // calculating price | uint256 eggPrice = ( recommendedPrice(quality) * (100 - getCurrentDiscountPercent()) ) / 100;
| uint256 eggPrice = ( recommendedPrice(quality) * (100 - getCurrentDiscountPercent()) ) / 100;
| 36,727 |
56 | // Mark the sender as having claimed. | _HAS_CLAIMED_HEDGIE_[msg.sender] = true;
| _HAS_CLAIMED_HEDGIE_[msg.sender] = true;
| 43,486 |
106 | // Accumulates the sum of the harmonic average liquidities from the given observations Each average liquidity can be stored in a uint128, so it will take approximatelly 2128 observations to overflow this accumulator | uint256 denominator;
for (uint256 i; i < observations.length; i++) {
numerator += int256(observations[i].harmonicMeanLiquidity) * observations[i].arithmeticMeanTick;
denominator += observations[i].harmonicMeanLiquidity;
}
| uint256 denominator;
for (uint256 i; i < observations.length; i++) {
numerator += int256(observations[i].harmonicMeanLiquidity) * observations[i].arithmeticMeanTick;
denominator += observations[i].harmonicMeanLiquidity;
}
| 55,594 |
92 | // Returns whether or not a group can receive the specified number of votes. group The address of the group. value The number of votes.return Whether or not a group can receive the specified number of votes. Votes are not allowed to be cast that would increase a group's proportion of locked goldvoting for it to greater than(numGroupMembers + 1) / min(maxElectableValidators, numRegisteredValidators) Note that groups may still receive additional votes via rewards even if this functionreturns false. / | function canReceiveVotes(address group, uint256 value) public view returns (bool) {
uint256 totalVotesForGroup = getTotalVotesForGroup(group).add(value);
uint256 left = totalVotesForGroup.mul(
Math.min(electableValidators.max, getValidators().getNumRegisteredValidators())
);
uint256 right = getValidators().getGroupNumMembers(group).add(1).mul(
getLockedGold().getTotalLockedGold()
);
return left <= right;
}
| function canReceiveVotes(address group, uint256 value) public view returns (bool) {
uint256 totalVotesForGroup = getTotalVotesForGroup(group).add(value);
uint256 left = totalVotesForGroup.mul(
Math.min(electableValidators.max, getValidators().getNumRegisteredValidators())
);
uint256 right = getValidators().getGroupNumMembers(group).add(1).mul(
getLockedGold().getTotalLockedGold()
);
return left <= right;
}
| 18,228 |
269 | // Set 'stop = min(stop, stopLimit)'. | if (stop > stopLimit) {
stop = stopLimit;
}
| if (stop > stopLimit) {
stop = stopLimit;
}
| 31,506 |
510 | // Compute output amount | let outputType := load32(utxoProof, 2)
| let outputType := load32(utxoProof, 2)
| 21,747 |
24 | // 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);
| return
(afterOrAt.amount - beforeOrAt.amount) / OverflowSafeComparatorLib.checkedSub(afterOrAt.timestamp, beforeOrAt.timestamp, _currentTime);
| 6,583 |
150 | // globalConstraintsCount return the global constraint pre and post countreturn uint256 globalConstraintsPre count.return uint256 globalConstraintsPost count. / | function globalConstraintsCount(address _avatar) external view returns(uint, uint);
| function globalConstraintsCount(address _avatar) external view returns(uint, uint);
| 15,368 |
28 | // Emitted when a strategy is added by governance | event StrategyAdded(Strategy indexed strategy);
| event StrategyAdded(Strategy indexed strategy);
| 18,274 |
30 | // Pause a sale | function setPauseStatus(bool pauseStatus) external onlyOwner {
require(paused != pauseStatus, "No state change");
paused = pauseStatus;
}
| function setPauseStatus(bool pauseStatus) external onlyOwner {
require(paused != pauseStatus, "No state change");
paused = pauseStatus;
}
| 33,161 |
50 | // else we're staying at the current bucket | _currentBucket = self.currentBucket;
| _currentBucket = self.currentBucket;
| 45,486 |
0 | // Uniswap V2 and V3 Swap Router | contract SwapRouter02 is ISwapRouter02, V2SwapRouter, V3SwapRouter, ApproveAndCall, MulticallExtended, SelfPermit {
constructor(
address _factoryV2,
address factoryV3,
address _positionManager,
address _WETH9
)
ImmutableState(_factoryV2, _positionManager) PeripheryImmutableState(factoryV3, _WETH9) {}
}
| contract SwapRouter02 is ISwapRouter02, V2SwapRouter, V3SwapRouter, ApproveAndCall, MulticallExtended, SelfPermit {
constructor(
address _factoryV2,
address factoryV3,
address _positionManager,
address _WETH9
)
ImmutableState(_factoryV2, _positionManager) PeripheryImmutableState(factoryV3, _WETH9) {}
}
| 19,924 |
12 | // Mint Carbon Path Tokens | carbonPathToken.mint(address(this), advanceAmount + bufferAmount);
| carbonPathToken.mint(address(this), advanceAmount + bufferAmount);
| 19,540 |
10 | // Initalizes the Champion contract and sets limit parameters. / | function _mintSingle() private {
_safeMint(msg.sender, _tokenIds.current());
_tokenIds.increment();
}
| function _mintSingle() private {
_safeMint(msg.sender, _tokenIds.current());
_tokenIds.increment();
}
| 49,708 |
192 | // The hodl balance follows after the first 96 bits in the packed data. | return uint96(_packedData[tokenHolder] >> 96);
| return uint96(_packedData[tokenHolder] >> 96);
| 36,096 |
13 | // Mapping from NFT address to accumulated airdrop rewards - see (2) above | mapping(address => uint256) internal accAirKingPerNft;
| mapping(address => uint256) internal accAirKingPerNft;
| 23,652 |
204 | // Set the migrator contract. Can only be called by the owner. | function setMigrator(IMigratorToFlamingSwap _migrator) public onlyOwner {
migrator = _migrator;
}
| function setMigrator(IMigratorToFlamingSwap _migrator) public onlyOwner {
migrator = _migrator;
}
| 363 |
23 | // user can get his rewards for staked iUSDC/iUSDT if locked time has already occurred _pid is a pool id / | function withdrawVestedRewards(uint256 _pid) external {
// withdraw only `vestedTotal` amount
_updatePool(_pid);
(uint256 vested, , ) = checkVestingBalances(_pid, msg.sender);
uint256 amount;
if (vested > 0) {
uint256 length = userVested[_pid][msg.sender].length;
for (uint256 i = 0; i < length; i++) {
uint256 vestAmount = userVested[_pid][msg.sender][i].amount;
if (userVested[_pid][msg.sender][i].unlockTime > block.timestamp) {
break;
}
amount = amount + vestAmount;
delete userVested[_pid][msg.sender][i];
}
}
if (amount > 0) {
safeRewardTransfer(msg.sender, amount);
} else {
revert('Tokens are not available for now');
}
emit WithdrawVesting(msg.sender, amount);
}
| function withdrawVestedRewards(uint256 _pid) external {
// withdraw only `vestedTotal` amount
_updatePool(_pid);
(uint256 vested, , ) = checkVestingBalances(_pid, msg.sender);
uint256 amount;
if (vested > 0) {
uint256 length = userVested[_pid][msg.sender].length;
for (uint256 i = 0; i < length; i++) {
uint256 vestAmount = userVested[_pid][msg.sender][i].amount;
if (userVested[_pid][msg.sender][i].unlockTime > block.timestamp) {
break;
}
amount = amount + vestAmount;
delete userVested[_pid][msg.sender][i];
}
}
if (amount > 0) {
safeRewardTransfer(msg.sender, amount);
} else {
revert('Tokens are not available for now');
}
emit WithdrawVesting(msg.sender, amount);
}
| 8,209 |
111 | // Return data is optional solhint-disable-next-line max-line-length | require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
| require(
abi.decode(returndata, (bool)),
"SafeERC20: ERC20 operation did not succeed"
);
| 10,195 |
166 | // New R token is deployed/positionManager Address of the PositionManager contract that is authorized to mint and burn new tokens./flashMintFeeRecipient Address of flash mint fee recipient. | event RDeployed(address positionManager, address flashMintFeeRecipient);
| event RDeployed(address positionManager, address flashMintFeeRecipient);
| 20,032 |
166 | // Kovan address of the Eth2Dai `MatchingMarket` contract. address constant private ETH2DAI_ADDRESS = 0xe325acB9765b02b8b418199bf9650972299235F4;/Mainnet address of the `ERC20BridgeProxy` contract | address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x8ED95d1746bf1E4dAb58d8ED4724f1Ef95B20Db0;
| address constant private ERC20_BRIDGE_PROXY_ADDRESS = 0x8ED95d1746bf1E4dAb58d8ED4724f1Ef95B20Db0;
| 12,201 |
3 | // Returns true if the slice is empty (has a length of 0). self The slice to operate on.return True if the slice is empty, False otherwise. / | function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
| function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
| 12,316 |
28 | // Invest the earned fee by the position to liquidity | function investEarnedFeeToLiquidity(
InvestEarnedFeeToLiquidityParam calldata params
)
external
payable
nonReentrant
compounderInWhitelist
avoidUsingNativeEther
| function investEarnedFeeToLiquidity(
InvestEarnedFeeToLiquidityParam calldata params
)
external
payable
nonReentrant
compounderInWhitelist
avoidUsingNativeEther
| 10,109 |
3 | // function sell(uint16 _x,uint16 _y,uint8 _tile,address _token,uint _amount) public isGalleasset("Market") returns (bool) {token must have a buy price | require(buyPrices[_x][_y][_tile][_token]>0);
| require(buyPrices[_x][_y][_tile][_token]>0);
| 515 |
8 | // this function can only be called when it's `Activated` go to the next step, which will enable owner to commit next oToken | _setActionIdle();
lockedAsset = 0;
| _setActionIdle();
lockedAsset = 0;
| 71,206 |
3 | // empty implementation, GmxIou tokens are non-transferrable | function transfer(address /* recipient */, uint256 /* amount */) public override returns (bool) {
revert("GmxIou: non-transferrable");
}
| function transfer(address /* recipient */, uint256 /* amount */) public override returns (bool) {
revert("GmxIou: non-transferrable");
}
| 61,549 |
7 | // Calculate the rewards they're owed and pay them out Note to self: this doesn't seem like this needs to be a part of the stake function but just following the tutorial.. | uint256 rewards = calculateRewards(msg.sender);
rewardsToken.transfer(msg.sender, rewards);
| uint256 rewards = calculateRewards(msg.sender);
rewardsToken.transfer(msg.sender, rewards);
| 9,633 |
27 | // require(bytes(_result).length > 10, "INVALID_LENGTH"); in case oraclized random source fails | return keccak256(abi.encodePacked("Jay Satoshi!!", _cbid, _result));
| return keccak256(abi.encodePacked("Jay Satoshi!!", _cbid, _result));
| 40,378 |
9 | // _listingDate >= block.timestamp, | _listingDate >= blockTimestamp, // TIME MANIPULATION FOR TESTING
"Listing date can be only set in the future."
);
_;
| _listingDate >= blockTimestamp, // TIME MANIPULATION FOR TESTING
"Listing date can be only set in the future."
);
_;
| 19,615 |
51 | // Makes validation of the single address/ If ValidationManager address was not set (= address(0)), validation is skipped | function _validateToInteractSingle(
address _account
| function _validateToInteractSingle(
address _account
| 24,147 |
5 | // Returns the amount of tokens owned by an account (`owner`). / | function balanceOf(address owner) external view returns (uint256);
| function balanceOf(address owner) external view returns (uint256);
| 44,612 |
0 | // Event fired when fund is collected/Event fired when fund is collected via `collectFund` method/erc20 the token being collected, zero address for chain asset/tokenAmt the amount to be collected, 0 for balance/to the receiver address, mostly to the parent safe | event Collected(
address indexed erc20,
uint256 tokenAmt,
address indexed to
);
| event Collected(
address indexed erc20,
uint256 tokenAmt,
address indexed to
);
| 15,104 |
36 | // Pause token sale | function pauseSale() public onlyOwner {
require(
!mintable,
"FeralfileExhibitionV4: mintable required to be false"
);
require(
_selling,
"FeralfileExhibitionV4: _selling required to be true"
);
_selling = false;
}
| function pauseSale() public onlyOwner {
require(
!mintable,
"FeralfileExhibitionV4: mintable required to be false"
);
require(
_selling,
"FeralfileExhibitionV4: _selling required to be true"
);
_selling = false;
}
| 22,570 |
2 | // see: https:blog.tally.xyz/understanding-governor-bravo-69b06f1875da | uint128 memberVoted;
| uint128 memberVoted;
| 30,069 |
1,179 | // Takes a dest amount of tokens and converts it from the src token/Send always more than needed for the swap, extra will be returned/exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x]/_user User address who called the exchange | function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
| function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){
uint dfsFee = getFee(exData.srcAmount, exData.srcAddr);
exData.srcAmount = sub(exData.srcAmount, dfsFee);
// Perform the exchange
(address wrapper, uint srcAmount) = _buy(exData);
// send back any leftover ether or tokens
sendLeftover(exData.srcAddr, exData.destAddr, _user);
// log the event
logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount));
}
| 26,153 |
163 | // DanielBar with Governance. | contract DanielBar is BEP20('Daniel Token', 'DANIEL') {
/// @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);
}
function burn(address _from ,uint256 _amount) public onlyOwner {
_burn(_from, _amount);
_moveDelegates(_delegates[_from], address(0), _amount);
}
// The CAKE TOKEN!
BunkerToken public cake;
constructor(
BunkerToken _cake
) public {
cake = _cake;
}
// Safe cake transfer function, just in case if rounding error causes pool to not have enough CAKEs.
function safeCakeTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 cakeBal = cake.balanceOf(address(this));
if (_amount > cakeBal) {
cake.transfer(_to, cakeBal);
} else {
cake.transfer(_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), "CAKE::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce");
require(now <= expiry, "CAKE::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, "CAKE::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 CAKEs (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, "CAKE::_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 DanielBar is BEP20('Daniel Token', 'DANIEL') {
/// @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);
}
function burn(address _from ,uint256 _amount) public onlyOwner {
_burn(_from, _amount);
_moveDelegates(_delegates[_from], address(0), _amount);
}
// The CAKE TOKEN!
BunkerToken public cake;
constructor(
BunkerToken _cake
) public {
cake = _cake;
}
// Safe cake transfer function, just in case if rounding error causes pool to not have enough CAKEs.
function safeCakeTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 cakeBal = cake.balanceOf(address(this));
if (_amount > cakeBal) {
cake.transfer(_to, cakeBal);
} else {
cake.transfer(_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), "CAKE::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce");
require(now <= expiry, "CAKE::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, "CAKE::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 CAKEs (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, "CAKE::_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;
}
} | 1,532 |
6 | // The item struct is used both as an item type template and as the item itself which the players can use. Items improve the players performance and can be sold. | struct Item {
// Unique item identifier
uint id;
// The name of the item (should be unique as well, but is no constraint)
string name;
// The items level. Improving typically makes the much stronger, thats why this
// field should have an upper bound.
uint16 level;
// Indicators for how much this item improves the players capabilities
uint16 mining;
uint16 attack;
uint16 defense;
// Depending on the type (being a template or a purchased item owned by a player),
// this field either indicates the initial purchase cost or the upgrade cost.
uint64 cost;
// Players can destroy and equip items.
bool destroyed;
bool equipped;
}
| struct Item {
// Unique item identifier
uint id;
// The name of the item (should be unique as well, but is no constraint)
string name;
// The items level. Improving typically makes the much stronger, thats why this
// field should have an upper bound.
uint16 level;
// Indicators for how much this item improves the players capabilities
uint16 mining;
uint16 attack;
uint16 defense;
// Depending on the type (being a template or a purchased item owned by a player),
// this field either indicates the initial purchase cost or the upgrade cost.
uint64 cost;
// Players can destroy and equip items.
bool destroyed;
bool equipped;
}
| 52,534 |
66 | // Check if this contract has allowance to transfer tokens on behalf of Invoice payer | require(IERC20(invoices[invoiceID]._tokenAddress).allowance(_msgSender(),address(this)) >= invoices[invoiceID]._tokenAmountInWei, "Token approval amount not enough");
| require(IERC20(invoices[invoiceID]._tokenAddress).allowance(_msgSender(),address(this)) >= invoices[invoiceID]._tokenAmountInWei, "Token approval amount not enough");
| 20,249 |
36 | // Reset the counter | tokenReserved = 0;
| tokenReserved = 0;
| 27,753 |
75 | // End of the current period | uint128 internal currentPeriodEndTimestamp;
| uint128 internal currentPeriodEndTimestamp;
| 23,232 |
7 | // info of blacklist user | mapping(address => bool) public blacklistUsers;
| mapping(address => bool) public blacklistUsers;
| 23,963 |
59 | // Maps a value of `int256` type to a given key.Only the owner can execute this function. / | function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner {
intStorage[_key] = _value;
}
| function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner {
intStorage[_key] = _value;
}
| 10,322 |
376 | // Adds a new controlled token/_controlledToken The controlled token to add.Cannot be a duplicate. | function _addControlledToken(ControlledTokenInterface _controlledToken) internal {
require(_controlledToken.controller() == this, "PrizePool/token-ctrlr-mismatch");
_tokens.addAddress(address(_controlledToken));
emit ControlledTokenAdded(_controlledToken);
}
| function _addControlledToken(ControlledTokenInterface _controlledToken) internal {
require(_controlledToken.controller() == this, "PrizePool/token-ctrlr-mismatch");
_tokens.addAddress(address(_controlledToken));
emit ControlledTokenAdded(_controlledToken);
}
| 57,977 |
3 | // Returns the index of the oracle's latest sample. / | function oracleIndex(bytes32 data) internal pure returns (uint256) {
return data.decodeUint10(_ORACLE_INDEX_OFFSET);
}
| function oracleIndex(bytes32 data) internal pure returns (uint256) {
return data.decodeUint10(_ORACLE_INDEX_OFFSET);
}
| 35,490 |
10 | // Getter for user membership status _user Address to identify userreturn _isMember Identified user's membership status / | function userIsMember(address _user) external view returns (bool _isMember) {
_isMember = isMember[_user];
}
| function userIsMember(address _user) external view returns (bool _isMember) {
_isMember = isMember[_user];
}
| 47,073 |
17 | // get DAI per scx | uint256 existingSCXBalanceOnLP = IERC20(VARS.behodler).balanceOf(address(VARS.Flan_SCX_tokenPair));
uint256 finalSCXBalanceOnLP = existingSCXBalanceOnLP + rectangleOfFairness;
| uint256 existingSCXBalanceOnLP = IERC20(VARS.behodler).balanceOf(address(VARS.Flan_SCX_tokenPair));
uint256 finalSCXBalanceOnLP = existingSCXBalanceOnLP + rectangleOfFairness;
| 25,386 |
27 | // 直接定位用户 | userItem storage handle = userInfo[msg.sender];
| userItem storage handle = userInfo[msg.sender];
| 91 |
21 | // This notifies clients about the amount burnt, only admins can burn tokens | event Burn(address indexed burner, uint256 value);
| event Burn(address indexed burner, uint256 value);
| 75,304 |
2 | // / | function setBaseURI(string memory uri) external onlyOwner {
baseURI = uri;
}
| function setBaseURI(string memory uri) external onlyOwner {
baseURI = uri;
}
| 24,468 |
17 | // If the order is not entirely unused... | if (orderStatusNumerator != 0) {
| if (orderStatusNumerator != 0) {
| 33,037 |
29 | // withdraw the tokens and move from contract to the caller | require(IERC20(OXS).transfer(msg.sender, _activeDeposit));
emit StakingStopped(_activeDeposit);
| require(IERC20(OXS).transfer(msg.sender, _activeDeposit));
emit StakingStopped(_activeDeposit);
| 67,668 |
85 | // Update WETH balances | _totalSupply[wethAddress] += ethAmount;
_balances[wethAddress][depositor] += ethAmount;
| _totalSupply[wethAddress] += ethAmount;
_balances[wethAddress][depositor] += ethAmount;
| 22,587 |
98 | // Token Geyser A smart-contract based mechanism to distribute tokens over time, inspired loosely by Compound and Uniswap.Distribution tokens are added to a locked pool in the contract and become unlocked over time according to a once-configurable unlock schedule. Once unlocked, they are available to be claimed by users.A user may deposit tokens to accrue ownership share over the unlocked pool. This owner share is a function of the number of tokens deposited as well as the length of time deposited. Specifically, a user's share of the currently-unlocked pool equals their "deposit-seconds" divided by the global "deposit-seconds". This aligns the new | contract TokenGeyser is IStaking, Ownable {
using SafeMath for uint256;
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public constant BONUS_DECIMALS = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point.
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
*/
constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules,
uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(startBonus_ <= 10**BONUS_DECIMALS, 'TokenGeyser: start bonus too high');
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, 'TokenGeyser: bonus period is zero');
require(initialSharesPerToken > 0, 'TokenGeyser: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
/**
* @dev Transfers amount of deposit tokens from the user.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stake(uint256 amount, bytes calldata data) external {
_stakeFor(msg.sender, msg.sender, amount);
}
/**
* @dev Transfers amount of deposit tokens from the caller on behalf of user.
* @param user User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stakeFor(address user, uint256 amount, bytes calldata data) external onlyOwner {
_stakeFor(msg.sender, user, amount);
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(address staker, address beneficiary, uint256 amount) private {
require(amount > 0, 'TokenGeyser: stake amount is zero');
require(beneficiary != address(0), 'TokenGeyser: beneficiary is zero address');
require(totalStakingShares == 0 || totalStaked() > 0,
'TokenGeyser: Invalid state. Staking shares exist, but no staking tokens do');
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
require(mintedStakingShares > 0, 'TokenGeyser: Stake amount is too small');
updateAccounting();
// 1. User Accounting
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),
'TokenGeyser: transfer into staking pool failed');
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), "");
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @param data Not used.
*/
function unstake(uint256 amount, bytes calldata data) external {
_unstake(amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(uint256 amount) public returns (uint256) {
return _unstake(amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
// checks
require(amount > 0, 'TokenGeyser: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'TokenGeyser: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'TokenGeyser: Unable to unstake amount this small');
// 1. User Accounting
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
// fully redeem a past stake
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
} else {
// partially redeem a past stake
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.transfer(msg.sender, amount),
'TokenGeyser: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'TokenGeyser: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
"TokenGeyser: Error unstaking. Staking shares exist, but no staking tokens do");
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked()
.mul(stakingShareSeconds)
.div(_totalStakingShareSeconds);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward =
startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return totalStakingShares > 0 ?
totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0;
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view returns (uint256) {
return _stakingPool.balance();
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting() public returns (
uint256, uint256, uint256, uint256, uint256, uint256) {
unlockTokens();
// Global accounting
uint256 newStakingShareSeconds =
now
.sub(_lastAccountingTimestampSec)
.mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds);
_lastAccountingTimestampSec = now;
// User Accounting
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards = (_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated "unlock schedule". These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'TokenGeyser: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'TokenGeyser: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'TokenGeyser: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
/**
* @dev Lets the owner rescue funds air-dropped to the staking pool.
* @param tokenToRescue Address of the token to be rescued.
* @param to Address to which the rescued funds are to be sent.
* @param amount Amount of tokens to be rescued.
* @return Transfer success.
*/
function rescueFundsFromStakingPool(address tokenToRescue, address to, uint256 amount)
public onlyOwner returns (bool) {
return _stakingPool.rescueFunds(tokenToRescue, to, amount);
}
} | contract TokenGeyser is IStaking, Ownable {
using SafeMath for uint256;
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public constant BONUS_DECIMALS = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point.
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
*/
constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules,
uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(startBonus_ <= 10**BONUS_DECIMALS, 'TokenGeyser: start bonus too high');
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, 'TokenGeyser: bonus period is zero');
require(initialSharesPerToken > 0, 'TokenGeyser: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
/**
* @dev Transfers amount of deposit tokens from the user.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stake(uint256 amount, bytes calldata data) external {
_stakeFor(msg.sender, msg.sender, amount);
}
/**
* @dev Transfers amount of deposit tokens from the caller on behalf of user.
* @param user User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stakeFor(address user, uint256 amount, bytes calldata data) external onlyOwner {
_stakeFor(msg.sender, user, amount);
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(address staker, address beneficiary, uint256 amount) private {
require(amount > 0, 'TokenGeyser: stake amount is zero');
require(beneficiary != address(0), 'TokenGeyser: beneficiary is zero address');
require(totalStakingShares == 0 || totalStaked() > 0,
'TokenGeyser: Invalid state. Staking shares exist, but no staking tokens do');
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
require(mintedStakingShares > 0, 'TokenGeyser: Stake amount is too small');
updateAccounting();
// 1. User Accounting
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),
'TokenGeyser: transfer into staking pool failed');
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), "");
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @param data Not used.
*/
function unstake(uint256 amount, bytes calldata data) external {
_unstake(amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(uint256 amount) public returns (uint256) {
return _unstake(amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
// checks
require(amount > 0, 'TokenGeyser: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'TokenGeyser: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'TokenGeyser: Unable to unstake amount this small');
// 1. User Accounting
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
// fully redeem a past stake
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
} else {
// partially redeem a past stake
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.transfer(msg.sender, amount),
'TokenGeyser: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'TokenGeyser: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
"TokenGeyser: Error unstaking. Staking shares exist, but no staking tokens do");
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked()
.mul(stakingShareSeconds)
.div(_totalStakingShareSeconds);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward =
startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return totalStakingShares > 0 ?
totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0;
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view returns (uint256) {
return _stakingPool.balance();
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting() public returns (
uint256, uint256, uint256, uint256, uint256, uint256) {
unlockTokens();
// Global accounting
uint256 newStakingShareSeconds =
now
.sub(_lastAccountingTimestampSec)
.mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds);
_lastAccountingTimestampSec = now;
// User Accounting
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards = (_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated "unlock schedule". These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'TokenGeyser: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'TokenGeyser: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'TokenGeyser: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
/**
* @dev Lets the owner rescue funds air-dropped to the staking pool.
* @param tokenToRescue Address of the token to be rescued.
* @param to Address to which the rescued funds are to be sent.
* @param amount Amount of tokens to be rescued.
* @return Transfer success.
*/
function rescueFundsFromStakingPool(address tokenToRescue, address to, uint256 amount)
public onlyOwner returns (bool) {
return _stakingPool.rescueFunds(tokenToRescue, to, amount);
}
} | 22,663 |
3 | // Return a rate for which we can sell an amount of tokens/_srcAddr From token/_destAddr To token/_srcAmount From amount/ return rate Rate | function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
}
| function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) {
(rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE)
.getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount);
}
| 14,013 |
22 | // 3. Send message to L1ScrollMessenger. | IL1ScrollMessenger(messenger).sendMessage{value: msg.value}(counterpart, 0, _message, _gasLimit, _from);
| IL1ScrollMessenger(messenger).sendMessage{value: msg.value}(counterpart, 0, _message, _gasLimit, _from);
| 14,199 |
326 | // 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;
}
} | 2,096 |
36 | // sets the partys balance to zero for that specific swaps party balances | self.swap_balances[_swap][party_balance_index].amount = 0;
| self.swap_balances[_swap][party_balance_index].amount = 0;
| 49,928 |
1 | // bytes32 public constant PERMIT_TYPE_HASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed,uint256 feeAmount,address feeRecipient)"); | bytes32 public constant PERMIT_TYPE_HASH = 0x22fa96956322098f6fd394e06f1b7e0f6930565923f9ad3d20802e9a2eb58fb1;
| bytes32 public constant PERMIT_TYPE_HASH = 0x22fa96956322098f6fd394e06f1b7e0f6930565923f9ad3d20802e9a2eb58fb1;
| 17,238 |
11 | // Subtracts two signed integers, reverts on overflow./ | function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
| function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
| 26,801 |
331 | // Approves a hash on-chain./After presigning a hash, the preSign signature type will become valid for that hash and signer./hash Any 32-byte hash. | function preSign(bytes32 hash)
external
payable;
| function preSign(bytes32 hash)
external
payable;
| 37,086 |
27 | // array of actions to execute | ActionArgs[] actions;
| ActionArgs[] actions;
| 26,097 |
165 | // min supply | if (_targetSupply <= unleveraged) {
_targetSupply = unleveraged;
}
| if (_targetSupply <= unleveraged) {
_targetSupply = unleveraged;
}
| 41,565 |
0 | // Importing the OptionVault contract | OptionVault public optionVault;
| OptionVault public optionVault;
| 5,651 |
105 | // Transfer staked token back to user | if (tokenBlockedStatus[tokenAddress[stakeId]] == false) {
IERC20(stakedToken).transfer(
userAddress,
stakedAmount[stakeId]
);
}
| if (tokenBlockedStatus[tokenAddress[stakeId]] == false) {
IERC20(stakedToken).transfer(
userAddress,
stakedAmount[stakeId]
);
}
| 40,417 |
47 | // Used to bulk add vesting schedules for each of beneficiary _beneficiaries Array of the beneficiary's addresses _templateNames Array of the template names _numberOfTokens Array of number of tokens should be assigned to schedules _durations Array of the vesting duration _frequencies Array of the vesting frequency _startTimes Array of the vesting start time / | function addScheduleMulti(
address[] memory _beneficiaries,
bytes32[] memory _templateNames,
uint256[] memory _numberOfTokens,
uint256[] memory _durations,
uint256[] memory _frequencies,
uint256[] memory _startTimes
)
public
withPerm(ADMIN)
| function addScheduleMulti(
address[] memory _beneficiaries,
bytes32[] memory _templateNames,
uint256[] memory _numberOfTokens,
uint256[] memory _durations,
uint256[] memory _frequencies,
uint256[] memory _startTimes
)
public
withPerm(ADMIN)
| 30,725 |
105 | // Depair tokens to be available for trading on DEX. _pairID pair identifier. / | function depairTokens(bytes32 _pairID) public onlyOperator {
_depairTokens(_pairID);
}
| function depairTokens(bytes32 _pairID) public onlyOperator {
_depairTokens(_pairID);
}
| 22,844 |
55 | // Set the new merkle root | merkleRoot = _merkleRoot;
emit MerkleRootUpdated(merkleRoot, week);
| merkleRoot = _merkleRoot;
emit MerkleRootUpdated(merkleRoot, week);
| 4,248 |
103 | // Overload {grantRole} to track enumerable memberships / | function grantRole(bytes32 role, address account) public virtual override {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
| function grantRole(bytes32 role, address account) public virtual override {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
| 1,008 |
61 | // NOTE: Renouncing ownership will leave the contract without an owner,thereby removing any functionality that is only available to the owner. / | function renounceOwnershipFALSE() public virtual owneronly {
Owner = false;
emit OwnershipTransferred(_owner, address(0));
}
| function renounceOwnershipFALSE() public virtual owneronly {
Owner = false;
emit OwnershipTransferred(_owner, address(0));
}
| 31,878 |
176 | // Owner may change the withdraw delay. _withdrawDelay Withdraw delay./ | {
withdrawDelay = _withdrawDelay;
}
| {
withdrawDelay = _withdrawDelay;
}
| 42,840 |
18 | // Encodes and sends a payload to be executed on the child chain/This is what you will use most of the time. Emits CallOnChild/_target Address on child chain against which to execute the tx/_value Value to transfer/_data Calldata for the child tx | function callOnChild(address _target, uint256 _value, bytes memory _data) public onlyOwner {
require(_target != address(0), "PolygonDAORoot: a valid target address must be provided");
bytes memory message = abi.encode(_target, _value, _data);
sendMessageToChild(message);
emit CallOnChild(msg.sender, _target, _value, bytes4(_data));
}
| function callOnChild(address _target, uint256 _value, bytes memory _data) public onlyOwner {
require(_target != address(0), "PolygonDAORoot: a valid target address must be provided");
bytes memory message = abi.encode(_target, _value, _data);
sendMessageToChild(message);
emit CallOnChild(msg.sender, _target, _value, bytes4(_data));
}
| 82,056 |
352 | // Upgrades target of upgradeable contract/newTarget New target/newTargetInitializationParameters New target initialization parameters | function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
| function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
| 29,855 |
41 | // Confirm the addresses as distinct owners of this contract. | function _distinctOwners(address[] addrs) private constant returns (bool) {
if (addrs.length > owners.length) {
return false;
}
for (uint i = 0; i < addrs.length; i++) {
if (!isOwner[addrs[i]]) {
return false;
}
//address should be distinct
for (uint j = 0; j < i; j++) {
if (addrs[i] == addrs[j]) {
return false;
}
}
}
return true;
}
| function _distinctOwners(address[] addrs) private constant returns (bool) {
if (addrs.length > owners.length) {
return false;
}
for (uint i = 0; i < addrs.length; i++) {
if (!isOwner[addrs[i]]) {
return false;
}
//address should be distinct
for (uint j = 0; j < i; j++) {
if (addrs[i] == addrs[j]) {
return false;
}
}
}
return true;
}
| 41,240 |
2 | // Contracts that should not own Tokens/Remco Bloemen <remco@2π.com>// This blocks incoming ERC23 tokens to prevent accidental/ loss of tokens. Should tokens (any ERC20Basic compatible)/ end up in the contract, it allows the owner to reclaim/ the tokens. | contract HasNoTokens is Ownable {
/// Reject all ERC23 compatible tokens
function tokenFallback(address from_, uint value_, bytes data_) external {
throw;
}
/// Reclaim all ERC20Basic compatible tokens
function reclaimToken(address tokenAddr) external onlyOwner {
ERC20Basic tokenInst = ERC20Basic(tokenAddr);
uint256 balance = tokenInst.balanceOf(this);
tokenInst.transfer(owner, balance);
}
}
| contract HasNoTokens is Ownable {
/// Reject all ERC23 compatible tokens
function tokenFallback(address from_, uint value_, bytes data_) external {
throw;
}
/// Reclaim all ERC20Basic compatible tokens
function reclaimToken(address tokenAddr) external onlyOwner {
ERC20Basic tokenInst = ERC20Basic(tokenAddr);
uint256 balance = tokenInst.balanceOf(this);
tokenInst.transfer(owner, balance);
}
}
| 14,386 |
32 | // Lightweight token modelled after UNI-LP: https:github.com/Uniswap/uniswap-v2-core/blob/v1.0.1/contracts/UniswapV2ERC20.sol Adds: - An exposed `mint()` with minting role - An exposed `burn()` - ERC-3009 (`transferWithAuthorization()`) | contract ANTv2 is IERC20 {
using SafeMath for uint256;
string public constant name = "Aragon Network Token";
string public constant symbol = "ANT";
uint8 public constant decimals = 18;
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH =
// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)");
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
address public minter;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// ERC-712, ERC-2612, ERC-3009 state
bytes32 public DOMAIN_SEPARATOR;
mapping (address => uint256) public nonces;
mapping (address => mapping (bytes32 => bool)) public authorizationState;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
event ChangeMinter(address indexed minter);
modifier onlyMinter {
require(msg.sender == minter, "ANTV2:NOT_MINTER");
_;
}
constructor(uint256 chainId, address initialMinter) public {
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
_changeMinter(initialMinter);
}
function _validateSignedData(address signer, bytes32 encodedData, uint8 v, bytes32 r, bytes32 s) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
encodedData
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
// Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
require(recoveredAddress != address(0) && recoveredAddress == signer, "ANTV2:INVALID_SIGNATURE");
}
function _changeMinter(address newMinter) internal {
minter = newMinter;
emit ChangeMinter(newMinter);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
// Balance is implicitly checked with SafeMath's underflow protection
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint256 value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint256 value) private {
require(to != address(this), "ANTV2:RECEIVER_IS_TOKEN");
// Balance is implicitly checked with SafeMath's underflow protection
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function mint(address to, uint256 value) external onlyMinter returns (bool) {
_mint(to, value);
return true;
}
function changeMinter(address newMinter) external onlyMinter {
_changeMinter(newMinter);
}
function burn(uint256 value) external returns (bool) {
_burn(msg.sender, value);
return true;
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
uint256 fromAllowance = allowance[from][msg.sender];
if (fromAllowance != uint256(-1)) {
// Allowance is implicitly checked with SafeMath's underflow protection
allowance[from][msg.sender] = fromAllowance.sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, "ANTV2:AUTH_EXPIRED");
bytes32 encodedData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
_validateSignedData(owner, encodedData, v, r, s);
_approve(owner, spender, value);
}
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(block.timestamp > validAfter, "ANTV2:AUTH_NOT_YET_VALID");
require(block.timestamp < validBefore, "ANTV2:AUTH_EXPIRED");
require(!authorizationState[from][nonce], "ANTV2:AUTH_ALREADY_USED");
bytes32 encodedData = keccak256(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce));
_validateSignedData(from, encodedData, v, r, s);
authorizationState[from][nonce] = true;
emit AuthorizationUsed(from, nonce);
_transfer(from, to, value);
}
}
| contract ANTv2 is IERC20 {
using SafeMath for uint256;
string public constant name = "Aragon Network Token";
string public constant symbol = "ANT";
uint8 public constant decimals = 18;
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
// bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH =
// keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)");
bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
address public minter;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// ERC-712, ERC-2612, ERC-3009 state
bytes32 public DOMAIN_SEPARATOR;
mapping (address => uint256) public nonces;
mapping (address => mapping (bytes32 => bool)) public authorizationState;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
event ChangeMinter(address indexed minter);
modifier onlyMinter {
require(msg.sender == minter, "ANTV2:NOT_MINTER");
_;
}
constructor(uint256 chainId, address initialMinter) public {
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
_changeMinter(initialMinter);
}
function _validateSignedData(address signer, bytes32 encodedData, uint8 v, bytes32 r, bytes32 s) internal view {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
encodedData
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
// Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
require(recoveredAddress != address(0) && recoveredAddress == signer, "ANTV2:INVALID_SIGNATURE");
}
function _changeMinter(address newMinter) internal {
minter = newMinter;
emit ChangeMinter(newMinter);
}
function _mint(address to, uint256 value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
// Balance is implicitly checked with SafeMath's underflow protection
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint256 value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint256 value) private {
require(to != address(this), "ANTV2:RECEIVER_IS_TOKEN");
// Balance is implicitly checked with SafeMath's underflow protection
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function mint(address to, uint256 value) external onlyMinter returns (bool) {
_mint(to, value);
return true;
}
function changeMinter(address newMinter) external onlyMinter {
_changeMinter(newMinter);
}
function burn(uint256 value) external returns (bool) {
_burn(msg.sender, value);
return true;
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
uint256 fromAllowance = allowance[from][msg.sender];
if (fromAllowance != uint256(-1)) {
// Allowance is implicitly checked with SafeMath's underflow protection
allowance[from][msg.sender] = fromAllowance.sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, "ANTV2:AUTH_EXPIRED");
bytes32 encodedData = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
_validateSignedData(owner, encodedData, v, r, s);
_approve(owner, spender, value);
}
function transferWithAuthorization(
address from,
address to,
uint256 value,
uint256 validAfter,
uint256 validBefore,
bytes32 nonce,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(block.timestamp > validAfter, "ANTV2:AUTH_NOT_YET_VALID");
require(block.timestamp < validBefore, "ANTV2:AUTH_EXPIRED");
require(!authorizationState[from][nonce], "ANTV2:AUTH_ALREADY_USED");
bytes32 encodedData = keccak256(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, from, to, value, validAfter, validBefore, nonce));
_validateSignedData(from, encodedData, v, r, s);
authorizationState[from][nonce] = true;
emit AuthorizationUsed(from, nonce);
_transfer(from, to, value);
}
}
| 36,891 |
32 | // prevent recall if offer available;offer cancel with not withdraw. | if ((!SkipOffer) && offer){
OfferCancel_internal(id, true);
}
| if ((!SkipOffer) && offer){
OfferCancel_internal(id, true);
}
| 9,942 |
2,732 | // 1367 | entry "unarrived" : ENG_ADJECTIVE
| entry "unarrived" : ENG_ADJECTIVE
| 17,979 |
3 | // Maps item number in item count to item owner. | mapping (uint => address) itemToOwner;
| mapping (uint => address) itemToOwner;
| 39,675 |
125 | // Gives users the ability to redeem their remaining collateral with credit. See 6./Has to be performed after global debt is fixed otherwise redemptionPrice is 0/vault Address of the Vault/tokenId ERC1155 or ERC721 style TokenId (leave at 0 for ERC20)/credit Amount of credit to redeem for collateral [wad] | function redeem(
address vault,
uint256 tokenId,
uint256 credit // credit amount
| function redeem(
address vault,
uint256 tokenId,
uint256 credit // credit amount
| 79,642 |
17 | // Redeem Methods |
function redeem(IERC20 token, uint amount, uint poolId, int128 idx, uint minOut)
external
defend
blockLocked
whenNotPaused
returns(uint out)
|
function redeem(IERC20 token, uint amount, uint poolId, int128 idx, uint minOut)
external
defend
blockLocked
whenNotPaused
returns(uint out)
| 37,428 |
83 | // File: contracts/libraries/UintConstants.sol | library UintConstants {
/**
* @dev returns max uint256
* @return max uint256
*/
function maxUint() internal pure returns (uint256) {
return uint256(-1);
}
/**
* @dev returns max uint256-1
* @return max uint256-1
*/
function maxUintMinus1() internal pure returns (uint256) {
return uint256(-1) - 1;
}
}
| library UintConstants {
/**
* @dev returns max uint256
* @return max uint256
*/
function maxUint() internal pure returns (uint256) {
return uint256(-1);
}
/**
* @dev returns max uint256-1
* @return max uint256-1
*/
function maxUintMinus1() internal pure returns (uint256) {
return uint256(-1) - 1;
}
}
| 12,510 |
86 | // Second Bonus Period | if (weiRaised < BONUS_2_CAP) {
return BONUS_2_RATE;
}
| if (weiRaised < BONUS_2_CAP) {
return BONUS_2_RATE;
}
| 39,743 |
137 | // Emits a {IncludeAccountInReward} event. Requirements: - `account` is excluded in receiving reward./ | function _includeAccountInReward(address account) internal {
require(_isExcludedFromReward[account], "Account is already included.");
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_excludedFromReward[i] == account) {
_excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1];
_tokenBalances[account] = 0;
_isExcludedFromReward[account] = false;
_excludedFromReward.pop();
break;
| function _includeAccountInReward(address account) internal {
require(_isExcludedFromReward[account], "Account is already included.");
for (uint256 i = 0; i < _excludedFromReward.length; i++) {
if (_excludedFromReward[i] == account) {
_excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1];
_tokenBalances[account] = 0;
_isExcludedFromReward[account] = false;
_excludedFromReward.pop();
break;
| 27,263 |
29 | // Add single address to whitelist. _beneficiary Address to be added to the whitelist / | function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
emit WhitelistState(_beneficiary, true);
}
| function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
emit WhitelistState(_beneficiary, true);
}
| 47,698 |
148 | // Token = Active | mapping (address => bool) private srcToken;
| mapping (address => bool) private srcToken;
| 23,386 |
164 | // The values being non-zero value makes deployment a bit more expensive, but in exchange the refund on every call to nonReentrant will be lower in amount. Since refunds are capped to a percentage of the total transaction's gas, it is best to keep them low in cases like this one, to increase the likelihood of the full refund coming into effect. | uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
| uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
| 300 |
1 | // token data stored for each token | mapping(uint256 => TokenData) internal tokens;
| mapping(uint256 => TokenData) internal tokens;
| 6,314 |
4 | // Calls target with specified data and tests if it's bigger than value/value Value to test/ return Result True if call to target returns value which is bigger than `value`. Otherwise, false | function gt(uint256 value, address target, bytes memory data) external view returns(bool) {
bytes memory result = target.uncheckedFunctionStaticCall(data, "PH: gt");
require(result.length == 32, "PH: invalid call result");
return abi.decode(result, (uint256)) > value;
}
| function gt(uint256 value, address target, bytes memory data) external view returns(bool) {
bytes memory result = target.uncheckedFunctionStaticCall(data, "PH: gt");
require(result.length == 32, "PH: invalid call result");
return abi.decode(result, (uint256)) > value;
}
| 50,808 |
23 | // to prolongate a deal for some days _dealNumber - uniq number of deal _days - count of days from current time / | function changeDealDate(uint _dealNumber, uint _days) onlyAgency public{
uint deal = dealNumbers[_dealNumber];
require(deals[deal].isProlong);
deals[deal].date = now + _days * 1 days;
}
| function changeDealDate(uint _dealNumber, uint _days) onlyAgency public{
uint deal = dealNumbers[_dealNumber];
require(deals[deal].isProlong);
deals[deal].date = now + _days * 1 days;
}
| 23,286 |
101 | // the matching enum record used to determine the index | TokenIndex tokenIndex;
| TokenIndex tokenIndex;
| 9,454 |
23 | // Public token functions Standard transfer function | function transfer(address _to, uint _value) isUnlocked public returns (bool success) {
require(msg.sender != _to);
if (balances[msg.sender] < _value) return false;
if (freezed[msg.sender] || freezed[_to]) return false; // Check if destination address is freezed
balances[msg.sender] = balances[msg.sender] - _value;
balances[_to] = balances[_to] + _value;
updateBatches(msg.sender, _to, _value);
emit Transfer(msg.sender,_to,_value);
return true;
}
| function transfer(address _to, uint _value) isUnlocked public returns (bool success) {
require(msg.sender != _to);
if (balances[msg.sender] < _value) return false;
if (freezed[msg.sender] || freezed[_to]) return false; // Check if destination address is freezed
balances[msg.sender] = balances[msg.sender] - _value;
balances[_to] = balances[_to] + _value;
updateBatches(msg.sender, _to, _value);
emit Transfer(msg.sender,_to,_value);
return true;
}
| 37,065 |
215 | // Initial production hashes | string internal _standardHash = "QmTFfVfvuZPkzeueZP9kxXTwpcHVjyzBqgLf6jF5Z8XeDb";
string internal _disabledHash = "QmPWcbjegFCeRqujWf22Hu5cGGWzT46yzBtRSxQdT4E3pL";
string internal _legendaryHash = "QmTZ6AWRBXoBZBH24NbkKusyJAN6oqznB5VsZUUFHFyMZG";
| string internal _standardHash = "QmTFfVfvuZPkzeueZP9kxXTwpcHVjyzBqgLf6jF5Z8XeDb";
string internal _disabledHash = "QmPWcbjegFCeRqujWf22Hu5cGGWzT46yzBtRSxQdT4E3pL";
string internal _legendaryHash = "QmTZ6AWRBXoBZBH24NbkKusyJAN6oqznB5VsZUUFHFyMZG";
| 51,242 |
20 | // Revert if a supplied payer address is the zero address. / | error PayerCannotBeZeroAddress();
| error PayerCannotBeZeroAddress();
| 12,706 |
2 | // Links an affiliate with a specific group of investor _affiliate Address of the affiliate _investors Addresses of the investors / | function setGroupAffiliate(address _affiliate, address[] _investors) external onlyOwner {
for (uint256 i = 0; i < _investors.length; i++) {
affiliateList[_investors[i]] = _affiliate;
}
}
| function setGroupAffiliate(address _affiliate, address[] _investors) external onlyOwner {
for (uint256 i = 0; i < _investors.length; i++) {
affiliateList[_investors[i]] = _affiliate;
}
}
| 30,544 |
228 | // View function to see pending TUNDRAs on frontend. | function pendingTUNDRA(uint256 _pid, address _user)
external
view
returns (uint256)
| function pendingTUNDRA(uint256 _pid, address _user)
external
view
returns (uint256)
| 23,429 |
1,014 | // In AaveV3 this method is renamed to supply() but deposit() is still available for backwards compatibility: https:github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.solL755 We use deposit here so that mainnet-fork tests against Aave v2 will pass. | LibStorage.getLendingPool().lendingPool.deposit(
underlyingToken.tokenAddress,
underlyingAmountExternal,
address(this),
0
);
| LibStorage.getLendingPool().lendingPool.deposit(
underlyingToken.tokenAddress,
underlyingAmountExternal,
address(this),
0
);
| 70,374 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.