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
26
// @inheritdoc IPrizePool
function awardBalance() external view override returns (uint256) { return _currentAwardBalance; }
function awardBalance() external view override returns (uint256) { return _currentAwardBalance; }
29,725
52
// Restore the cached values overwritten by selector, digest and signature head.
mstore(wordBeforeSignaturePtr, cachedWordBeforeSignature) mstore(selectorPtr, cachedWordOverwrittenBySelector) mstore( sub( signature, EIP1271_isValidSignature_digest_negativeOffset ), cachedWordOverwrittenByDigest )
mstore(wordBeforeSignaturePtr, cachedWordBeforeSignature) mstore(selectorPtr, cachedWordOverwrittenBySelector) mstore( sub( signature, EIP1271_isValidSignature_digest_negativeOffset ), cachedWordOverwrittenByDigest )
20,384
350
// File: contracts/CryptoAvatarz.sol
pragma solidity ^0.8.4;
pragma solidity ^0.8.4;
18,092
481
// Subtract paid out margin from p2pVault
_decreaseP2PVault(derivativeHash, payout);
_decreaseP2PVault(derivativeHash, payout);
34,464
3
// Gets the expiry time for the current sale/ return The expiry time, as a unix epoch
function getExpiryTime() external view returns (uint256) { return _expiryTime; }
function getExpiryTime() external view returns (uint256) { return _expiryTime; }
29,422
151
// Tokens can be minted only before minting finished. /
modifier canMint() { require(!_mintingFinished, "ERC20Mintable: minting is finished"); _; }
modifier canMint() { require(!_mintingFinished, "ERC20Mintable: minting is finished"); _; }
26,644
266
// remove the inverse mapping.
delete pynthToInversePynth[pynths[i]]; emit ShortablePynthRemoved(pynths[i]);
delete pynthToInversePynth[pynths[i]]; emit ShortablePynthRemoved(pynths[i]);
700
19
// Mints `tokenId`, transfers it to `creator`, sets `tokenURI` and initializes asset state. _arweaveId Arweave ID used for tokenURI _ipfsMetadataHash IPFS CID hash of metadata _creator Address of artist who created the asset _taxCollector Address of tax collector accountreturn newTokenId of the newly created token Requirements: - `admin` must be equal to `msgSender`.
* Emits a {Mint & Transfer} event. */ function mintAsset( string memory _arweaveId, string memory _ipfsMetadataHash, address _creator, address _taxCollector ) external onlyAdmin returns (uint256 newTokenId) { _tokenIds.increment(); newTokenId = _tokenIds.current(); emit Mint(block.timestamp, newTokenId, address(0), _creator); _safeMint(_creator, newTokenId, ""); _setTokenURI(newTokenId, _arweaveId); ipfsMetadataHashes[newTokenId] = _ipfsMetadataHash; taxCollectors[newTokenId] = _taxCollector; Asset storage asset = assets[newTokenId]; asset.creator = _creator; asset.foreclosureTimestamp = block.timestamp + BASE_INTERVAL; }
* Emits a {Mint & Transfer} event. */ function mintAsset( string memory _arweaveId, string memory _ipfsMetadataHash, address _creator, address _taxCollector ) external onlyAdmin returns (uint256 newTokenId) { _tokenIds.increment(); newTokenId = _tokenIds.current(); emit Mint(block.timestamp, newTokenId, address(0), _creator); _safeMint(_creator, newTokenId, ""); _setTokenURI(newTokenId, _arweaveId); ipfsMetadataHashes[newTokenId] = _ipfsMetadataHash; taxCollectors[newTokenId] = _taxCollector; Asset storage asset = assets[newTokenId]; asset.creator = _creator; asset.foreclosureTimestamp = block.timestamp + BASE_INTERVAL; }
13,689
299
// Gets the managers./ return The list of managers.
function managers() public view returns (address[] memory) { return addressesInSet(MANAGER); }
function managers() public view returns (address[] memory) { return addressesInSet(MANAGER); }
3,674
79
// Returns whether the specified token exists. tokenId uint256 ID of the token to query the existence ofreturn bool whether the token exists /
function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); }
function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); }
1,651
131
// Decode a string value from a Witnet.Result as a `string` value./_result An instance of Witnet.Result./ return The `string` decoded from the Witnet.Result.
function asString(Witnet.Result memory _result) external pure returns(string memory)
function asString(Witnet.Result memory _result) external pure returns(string memory)
82,283
24
// clear the remained coin-days
uint amountToHedgeOwner = uint(vault.hedgeValue) * 10 ** 18 / price; if (isCloseout) { amountToHedgeOwner = amountToHedgeOwner * (10 ** 18 + vault.closeoutPenalty) / 10 ** 18; }
uint amountToHedgeOwner = uint(vault.hedgeValue) * 10 ** 18 / price; if (isCloseout) { amountToHedgeOwner = amountToHedgeOwner * (10 ** 18 + vault.closeoutPenalty) / 10 ** 18; }
27,561
4
// Returns the address of the config contract.
function config() external view returns (address);
function config() external view returns (address);
38,895
31
// Checks if a specific account is marked as a "whale". This function allows you to verify whether an account is considered a "whale" in the context of this contract.The status of an account (whale or not) should be set by the contract based on the implemented logic.The function only returns the current status and doesn't change any state variables. account The address of the account to be checked.return bool Returns true if the account is a "whale", false otherwise. /
function isWhale(address account) public view returns (bool) { return _isWhale[account]; }
function isWhale(address account) public view returns (bool) { return _isWhale[account]; }
12,106
55
// Modern ERC20 Token interface
interface IERC20 { function transfer(address to, uint amount) external returns (bool); function transferFrom(address from, address to, uint amount) external returns (bool); }
interface IERC20 { function transfer(address to, uint amount) external returns (bool); function transferFrom(address from, address to, uint amount) external returns (bool); }
24,858
37
// Burn pass
_burn(msg.sender, _passId, 1);
_burn(msg.sender, _passId, 1);
1,129
9
// start of the sale
uint256 public startTime;
uint256 public startTime;
3,551
1
// Chuyển tiền cho một tài khoản khác
function transfer(address to, uint256 amount) public override returns (bool) { require(to != address(0), "Invalid address"); return super.transfer(to, amount); }
function transfer(address to, uint256 amount) public override returns (bool) { require(to != address(0), "Invalid address"); return super.transfer(to, amount); }
17,147
364
// issueId => [tokenId]
mapping (uint256 => uint256[]) public lotteryInfo;
mapping (uint256 => uint256[]) public lotteryInfo;
37,889
53
// then remove the liqudity from the pool, will get want back
uint256 usdn3crv = _getMetaPoolLpToken().balanceOf(address(this)); usdnMetaPool.remove_liquidity_one_coin(usdn3crv, 1, uint256(0)); uint256 _3crv = _getTriPoolLpToken().balanceOf(address(this)); ICurveDepositTrio(address(curvePool)).remove_liquidity_one_coin(_3crv, wantThreepoolIndex, 0); return _balanceOfWant() - _before;
uint256 usdn3crv = _getMetaPoolLpToken().balanceOf(address(this)); usdnMetaPool.remove_liquidity_one_coin(usdn3crv, 1, uint256(0)); uint256 _3crv = _getTriPoolLpToken().balanceOf(address(this)); ICurveDepositTrio(address(curvePool)).remove_liquidity_one_coin(_3crv, wantThreepoolIndex, 0); return _balanceOfWant() - _before;
70,456
47
// Get royalty recipients and amounts
(address payable[] memory recipients, uint256[] memory amounts) = RoyaltyPaymentsLogic(address(this)) .getRoyalty(_targetAuction.assetContract, _targetAuction.tokenId, _totalPayoutAmount); uint256 royaltyRecipientCount = recipients.length; if (royaltyRecipientCount != 0) { uint256 royaltyCut; address royaltyRecipient; for (uint256 i = 0; i < royaltyRecipientCount; ) {
(address payable[] memory recipients, uint256[] memory amounts) = RoyaltyPaymentsLogic(address(this)) .getRoyalty(_targetAuction.assetContract, _targetAuction.tokenId, _totalPayoutAmount); uint256 royaltyRecipientCount = recipients.length; if (royaltyRecipientCount != 0) { uint256 royaltyCut; address royaltyRecipient; for (uint256 i = 0; i < royaltyRecipientCount; ) {
15,699
283
// private sale has 50% off
if(privateSaleIsActive) { price = price.div(2); }
if(privateSaleIsActive) { price = price.div(2); }
6,222
28
// Register a future flight for insuring./
function setFlightStatus (address _airline_address, uint32 _flight_id, uint32 _departure_time, uint32 _status) internal requireIsOperational
function setFlightStatus (address _airline_address, uint32 _flight_id, uint32 _departure_time, uint32 _status) internal requireIsOperational
17,824
98
// user's staked information
function getUserStaked(address user) external view returns ( uint256 amount, uint256 claimedBlock, uint256 claimedAmount, uint256 releasedBlock, uint256 releasedAmount, uint256 releasedTOSAmount,
function getUserStaked(address user) external view returns ( uint256 amount, uint256 claimedBlock, uint256 claimedAmount, uint256 releasedBlock, uint256 releasedAmount, uint256 releasedTOSAmount,
28,238
11
// Check token balances
if ( frameToken.balanceOf(_account) < _amount || frameToken.accountLocked(_account) ) { return false; }
if ( frameToken.balanceOf(_account) < _amount || frameToken.accountLocked(_account) ) { return false; }
26,645
19
// FIXME: is block.number right?
balances[msg.sender][x].lastInterestBlock = block.number; return interest;
balances[msg.sender][x].lastInterestBlock = block.number; return interest;
35,229
38
// Values 0-10,000 map to 0%-100% Author's share from the owner cut.
uint256 public authorShare;
uint256 public authorShare;
27,681
44
// use burn() instead
&& _to != 0x0) { piecesOwned[msg.sender] -= _amount; piecesOwned[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; }
&& _to != 0x0) { piecesOwned[msg.sender] -= _amount; piecesOwned[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; }
31,784
48
// Nonce to ensure that old vouchers cannot be reused
uint256 nonce;
uint256 nonce;
68,884
85
// Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],but performing a static call. _Available since v3.3._ /
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract");
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract");
1,419
329
// Update endpoint mapping
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID;
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID;
38,451
478
// calculates and returns the borrow balances of the user_reserve the address of the reserve_user the address of the user return the principal borrow balance, the compounded balance and the balance increase since the last borrow/repay/swap/rebalance/
{ CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (user.principalBorrowBalance == 0) { return (0, 0, 0); } uint256 principal = user.principalBorrowBalance; uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance( user, reserves[_reserve] ); return (principal, compoundedBalance, compoundedBalance.sub(principal)); }
{ CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve]; if (user.principalBorrowBalance == 0) { return (0, 0, 0); } uint256 principal = user.principalBorrowBalance; uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance( user, reserves[_reserve] ); return (principal, compoundedBalance, compoundedBalance.sub(principal)); }
16,354
108
// Return Staking interfacereturn Staking contract registered with Controller /
function staking() internal view returns (IStaking) { return IStaking(controller.getContractProxy(keccak256("Staking"))); }
function staking() internal view returns (IStaking) { return IStaking(controller.getContractProxy(keccak256("Staking"))); }
81,666
1
// Errors
error AlpacaFeeder02_InvalidToken(); error AlpacaFeeder02_InvalidRewardToken(); error AlpacaFeeder02_Deposited();
error AlpacaFeeder02_InvalidToken(); error AlpacaFeeder02_InvalidRewardToken(); error AlpacaFeeder02_Deposited();
24,817
100
// Sets new supply according to buy or sell
if(_buy) { newSupply = this.totalSupply() + _tokens;
if(_buy) { newSupply = this.totalSupply() + _tokens;
2,127
26
// Pause the contract.
function pause() external only(pauser) { paused = true; emit Paused(pauser); }
function pause() external only(pauser) { paused = true; emit Paused(pauser); }
51,054
8
// Current Treasury Fee
uint16 public treasuryFee;
uint16 public treasuryFee;
73,263
101
// used by vault cash back
function getMyVoteForCurrentMilestoneRelease(address _voter) public view returns (bool) { // find proposal id for current milestone uint8 recordId = MilestonesEntity.currentRecord(); bytes32 hash = getHash( getActionType("MILESTONE_DEADLINE"), bytes32( recordId ), 0 ); uint256 proposalId = ProposalIdByHash[hash]; // based on that proposal id, find my vote VoteStruct memory vote = VotesByCaster[proposalId][_voter]; return vote.vote; }
function getMyVoteForCurrentMilestoneRelease(address _voter) public view returns (bool) { // find proposal id for current milestone uint8 recordId = MilestonesEntity.currentRecord(); bytes32 hash = getHash( getActionType("MILESTONE_DEADLINE"), bytes32( recordId ), 0 ); uint256 proposalId = ProposalIdByHash[hash]; // based on that proposal id, find my vote VoteStruct memory vote = VotesByCaster[proposalId][_voter]; return vote.vote; }
43,982
249
// This caches the `round` variable used in shareBalances
uint256 currentRound = vaultState.round; Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; bool withdrawalIsSameRound = withdrawal.round == currentRound; emit InitiateWithdraw(msg.sender, numShares, currentRound); uint256 existingShares = uint256(withdrawal.shares); uint256 withdrawalShares;
uint256 currentRound = vaultState.round; Vault.Withdrawal storage withdrawal = withdrawals[msg.sender]; bool withdrawalIsSameRound = withdrawal.round == currentRound; emit InitiateWithdraw(msg.sender, numShares, currentRound); uint256 existingShares = uint256(withdrawal.shares); uint256 withdrawalShares;
17,358
361
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); }
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); }
30,830
55
// internal function
function _canOperate(address _tokenOwner) constant internal { require(_tokenOwner == msg.sender || ownerToOperators[_tokenOwner][msg.sender]); }
function _canOperate(address _tokenOwner) constant internal { require(_tokenOwner == msg.sender || ownerToOperators[_tokenOwner][msg.sender]); }
12,517
3
// The Erc20 asset that backs the borrows of this fyToken. /
Erc20Interface public collateral;
Erc20Interface public collateral;
40,484
38
// Creates a TokenVault contract that stores a token distribution. _token The address of the ERC20 token the vault is for _tokensToBeAllocated The amount of tokens that will be allocatedprior to locking _vestingPeriod The amount of time, in seconds, that must passafter locking in the allocations and then unlocking the allocations forclaiming /
constructor( ERC20Basic _token, uint256 _tokensToBeAllocated, uint256 _vestingPeriod ) public
constructor( ERC20Basic _token, uint256 _tokensToBeAllocated, uint256 _vestingPeriod ) public
45,706
65
// SuperRare Hint taken from Manifold's RoyaltyEngine(https:github.com/manifoldxyz/royalty-registry-solidity/blob/main/contracts/RoyaltyEngineV1.sol) To be quite honest, SuperRare is a closed marketplace. They're working on opening it up but looks like they want to use private smart contracts. We'll just leave this here for just in case they open the flood gates.
function tokenCreator( address, /* contractAddress*/ uint256 tokenId
function tokenCreator( address, /* contractAddress*/ uint256 tokenId
17,604
78
// The (older) MasterChef contract gives out a constant number of SYNAPSE tokens per block./ It is the only address with minting rights for SYNAPSE./ The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token/ that is deposited into the MasterChef V1 (MCV1) contract./ The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives.
contract MiniChefV2 is BoringOwnable, BoringBatchable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each MCV2 user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of SYNAPSE entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each MCV2 pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of SYNAPSE to distribute per block. struct PoolInfo { uint128 accSynapsePerShare; uint64 lastRewardTime; uint64 allocPoint; } /// @notice Address of SYNAPSE contract. IERC20 public immutable SYNAPSE; /// @notice Info of each MCV2 pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each MCV2 pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in MCV2. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public synapsePerSecond; uint256 private constant ACC_SYNAPSE_PRECISION = 1e12; event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardTime, uint256 lpSupply, uint256 accSynapsePerShare); event LogSynapsePerSecond(uint256 synapsePerSecond); /// @param _synapse The SYNAPSE token contract address. constructor(IERC20 _synapse) public { SYNAPSE = _synapse; } /// @notice Returns the number of MCV2 pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add(uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder) public onlyOwner { totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push(PoolInfo({ allocPoint: allocPoint.to64(), lastRewardTime: block.timestamp.to64(), accSynapsePerShare: 0 })); emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); } /// @notice Update the given pool's SYNAPSE allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set(uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite); } /// @notice Sets the synapse per second to be distributed. Can only be called by the owner. /// @param _synapsePerSecond The amount of Synapse to be distributed per second. function setSynapsePerSecond(uint256 _synapsePerSecond) public onlyOwner { synapsePerSecond = _synapsePerSecond; emit LogSynapsePerSecond(_synapsePerSecond); } /// @notice View function to see pending SYNAPSE on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending SYNAPSE reward for a given user. function pendingSynapse(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSynapsePerShare = pool.accSynapsePerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 synapseReward = time.mul(synapsePerSecond).mul(pool.allocPoint) / totalAllocPoint; accSynapsePerShare = accSynapsePerShare.add(synapseReward.mul(ACC_SYNAPSE_PRECISION) / lpSupply); } pending = int256(user.amount.mul(accSynapsePerShare) / ACC_SYNAPSE_PRECISION).sub(user.rewardDebt).toUInt256(); } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTime) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 synapseReward = time.mul(synapsePerSecond).mul(pool.allocPoint) / totalAllocPoint; pool.accSynapsePerShare = pool.accSynapsePerShare.add((synapseReward.mul(ACC_SYNAPSE_PRECISION) / lpSupply).to128()); } pool.lastRewardTime = block.timestamp.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardTime, lpSupply, pool.accSynapsePerShare); } } /// @notice Deposit LP tokens to MCV2 for SYNAPSE allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION)); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from MCV2. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION)); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward(pid, msg.sender, to, 0, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of SYNAPSE rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSynapse = int256(user.amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION); uint256 _pendingSynapse = accumulatedSynapse.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSynapse; // Interactions if (_pendingSynapse != 0) { SYNAPSE.safeTransfer(to, _pendingSynapse); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward( pid, msg.sender, to, _pendingSynapse, user.amount); } emit Harvest(msg.sender, pid, _pendingSynapse); } /// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens and SYNAPSE rewards. function withdrawAndHarvest(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSynapse = int256(user.amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION); uint256 _pendingSynapse = accumulatedSynapse.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSynapse.sub(int256(amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION)); user.amount = user.amount.sub(amount); // Interactions SYNAPSE.safeTransfer(to, _pendingSynapse); IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward(pid, msg.sender, to, _pendingSynapse, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); emit Harvest(msg.sender, pid, _pendingSynapse); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward(pid, msg.sender, to, 0, 0); } // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } }
contract MiniChefV2 is BoringOwnable, BoringBatchable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each MCV2 user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of SYNAPSE entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each MCV2 pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of SYNAPSE to distribute per block. struct PoolInfo { uint128 accSynapsePerShare; uint64 lastRewardTime; uint64 allocPoint; } /// @notice Address of SYNAPSE contract. IERC20 public immutable SYNAPSE; /// @notice Info of each MCV2 pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each MCV2 pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in MCV2. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public synapsePerSecond; uint256 private constant ACC_SYNAPSE_PRECISION = 1e12; event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardTime, uint256 lpSupply, uint256 accSynapsePerShare); event LogSynapsePerSecond(uint256 synapsePerSecond); /// @param _synapse The SYNAPSE token contract address. constructor(IERC20 _synapse) public { SYNAPSE = _synapse; } /// @notice Returns the number of MCV2 pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add(uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder) public onlyOwner { totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push(PoolInfo({ allocPoint: allocPoint.to64(), lastRewardTime: block.timestamp.to64(), accSynapsePerShare: 0 })); emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); } /// @notice Update the given pool's SYNAPSE allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set(uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite); } /// @notice Sets the synapse per second to be distributed. Can only be called by the owner. /// @param _synapsePerSecond The amount of Synapse to be distributed per second. function setSynapsePerSecond(uint256 _synapsePerSecond) public onlyOwner { synapsePerSecond = _synapsePerSecond; emit LogSynapsePerSecond(_synapsePerSecond); } /// @notice View function to see pending SYNAPSE on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending SYNAPSE reward for a given user. function pendingSynapse(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSynapsePerShare = pool.accSynapsePerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.timestamp > pool.lastRewardTime && lpSupply != 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 synapseReward = time.mul(synapsePerSecond).mul(pool.allocPoint) / totalAllocPoint; accSynapsePerShare = accSynapsePerShare.add(synapseReward.mul(ACC_SYNAPSE_PRECISION) / lpSupply); } pending = int256(user.amount.mul(accSynapsePerShare) / ACC_SYNAPSE_PRECISION).sub(user.rewardDebt).toUInt256(); } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.timestamp > pool.lastRewardTime) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 time = block.timestamp.sub(pool.lastRewardTime); uint256 synapseReward = time.mul(synapsePerSecond).mul(pool.allocPoint) / totalAllocPoint; pool.accSynapsePerShare = pool.accSynapsePerShare.add((synapseReward.mul(ACC_SYNAPSE_PRECISION) / lpSupply).to128()); } pool.lastRewardTime = block.timestamp.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardTime, lpSupply, pool.accSynapsePerShare); } } /// @notice Deposit LP tokens to MCV2 for SYNAPSE allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION)); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from MCV2. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION)); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward(pid, msg.sender, to, 0, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of SYNAPSE rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSynapse = int256(user.amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION); uint256 _pendingSynapse = accumulatedSynapse.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSynapse; // Interactions if (_pendingSynapse != 0) { SYNAPSE.safeTransfer(to, _pendingSynapse); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward( pid, msg.sender, to, _pendingSynapse, user.amount); } emit Harvest(msg.sender, pid, _pendingSynapse); } /// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens and SYNAPSE rewards. function withdrawAndHarvest(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedSynapse = int256(user.amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION); uint256 _pendingSynapse = accumulatedSynapse.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedSynapse.sub(int256(amount.mul(pool.accSynapsePerShare) / ACC_SYNAPSE_PRECISION)); user.amount = user.amount.sub(amount); // Interactions SYNAPSE.safeTransfer(to, _pendingSynapse); IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward(pid, msg.sender, to, _pendingSynapse, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); emit Harvest(msg.sender, pid, _pendingSynapse); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onSynapseReward(pid, msg.sender, to, 0, 0); } // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } }
38,943
64
// Structure representing the signature parts. r ECDSA signature parameter r. s ECDSA signature parameter s. v ECDSA signature parameter v. kind Type of signature. /
struct SignatureData
struct SignatureData
42,019
219
// user needs to contribute proportional amount of fees to pool, which ensures they are only earning fees generated after they have deposited
if (totalSupply() > 0) {
if (totalSupply() > 0) {
36,393
193
// ========== Internal Inheritance ========== // ========== Internal Interfaces ========== ///
contract SigmaIndexPoolV1 is BToken, BMath, IIndexPool { /* ========== Modifiers ========== */ modifier _lock_ { require(!_mutex, "ERR_REENTRY"); _mutex = true; _; _mutex = false; } modifier _viewlock_() { require(!_mutex, "ERR_REENTRY"); _; } modifier _control_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); _; } modifier _public_ { require(_publicSwap, "ERR_NOT_PUBLIC"); _; } /* ========== Storage ========== */ bool internal _mutex; // Account with CONTROL role. Able to modify the swap fee, // adjust token weights, bind and unbind tokens and lock // public swaps & joins. address internal _controller; // Contract that handles unbound tokens. TokenUnbindHandler internal _unbindHandler; // True if PUBLIC can call SWAP & JOIN functions bool internal _publicSwap; // `setSwapFee` requires CONTROL uint256 internal _swapFee; // Array of underlying tokens in the pool. address[] internal _tokens; // Internal records of the pool's underlying tokens mapping(address => Record) internal _records; // Total denormalized weight of the pool. uint256 internal _totalWeight; // Minimum balances for tokens which have been added without the // requisite initial balance. mapping(address => uint256) internal _minimumBalances; // Recipient for exit fees address internal _exitFeeRecipient; /* ========== Controls ========== */ /** * @dev Sets the controller address and the token name & symbol. * * Note: This saves on storage costs for multi-step pool deployment. * * @param controller Controller of the pool * @param name Name of the pool token * @param symbol Symbol of the pool token */ function configure( address controller, string calldata name, string calldata symbol ) external override { require(_controller == address(0), "ERR_CONFIGURED"); require(controller != address(0), "ERR_NULL_ADDRESS"); _controller = controller; // default fee is 2% _swapFee = BONE / 50; _initializeToken(name, symbol); } /** * @dev Sets up the initial assets for the pool. * * Note: `tokenProvider` must have approved the pool to transfer the * corresponding `balances` of `tokens`. * * @param tokens Underlying tokens to initialize the pool with * @param balances Initial balances to transfer * @param denorms Initial denormalized weights for the tokens * @param tokenProvider Address to transfer the balances from * @param unbindHandler Address that receives tokens removed from the pool * @param exitFeeRecipient Address that receives exit fees */ function initialize( address[] calldata tokens, uint256[] calldata balances, uint96[] calldata denorms, address tokenProvider, address unbindHandler, address exitFeeRecipient ) external override _control_ { require(_tokens.length == 0, "ERR_INITIALIZED"); uint256 len = tokens.length; require(len >= MIN_BOUND_TOKENS, "ERR_MIN_TOKENS"); require(len <= MAX_BOUND_TOKENS, "ERR_MAX_TOKENS"); require(balances.length == len && denorms.length == len, "ERR_ARR_LEN"); uint256 totalWeight = 0; for (uint256 i = 0; i < len; i++) { address token = tokens[i]; uint96 denorm = denorms[i]; uint256 balance = balances[i]; require(denorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(denorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); require(balance >= MIN_BALANCE, "ERR_MIN_BALANCE"); _records[token] = Record({ bound: true, ready: true, lastDenormUpdate: uint40(now), denorm: denorm, desiredDenorm: denorm, index: uint8(i), balance: balance }); _tokens.push(token); totalWeight = badd(totalWeight, denorm); _pullUnderlying(token, tokenProvider, balance); } require(totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); _totalWeight = totalWeight; _publicSwap = true; emit LOG_PUBLIC_SWAP_TOGGLED(true); _mintPoolShare(INIT_POOL_SUPPLY); _pushPoolShare(tokenProvider, INIT_POOL_SUPPLY); _unbindHandler = TokenUnbindHandler(unbindHandler); _exitFeeRecipient = exitFeeRecipient; } /** * @dev Set the swap fee. * Note: Swap fee must be between 0.0001% and 10% */ function setSwapFee(uint256 swapFee) external override _control_ { require(swapFee >= MIN_FEE && swapFee <= MAX_FEE, "ERR_INVALID_FEE"); _swapFee = swapFee; emit LOG_SWAP_FEE_UPDATED(swapFee); } /** * @dev Set the controller address. */ function setController(address controller) external override _control_ { require(controller != address(0), "ERR_NULL_ADDRESS"); _controller = controller; emit LOG_CONTROLLER_UPDATED(controller); } /** * @dev Delegate a comp-like governance token to an address * specified by the controller. */ function delegateCompLikeToken(address token, address delegatee) external override _control_ { ICompLikeToken(token).delegate(delegatee); } /** * @dev Set the exit fee recipient address. */ function setExitFeeRecipient(address exitFeeRecipient) external override _control_ { require(exitFeeRecipient != address(0), "ERR_NULL_ADDRESS"); _exitFeeRecipient = exitFeeRecipient; emit LOG_EXIT_FEE_RECIPIENT_UPDATED(exitFeeRecipient); } /** * @dev Toggle public trading for the index pool. * This will enable or disable swaps and single-token joins and exits. */ function setPublicSwap(bool enabled) external override _control_ { _publicSwap = enabled; emit LOG_PUBLIC_SWAP_TOGGLED(enabled); } /* ========== Token Management Actions ========== */ /** * @dev Sets the desired weights for the pool tokens, which * will be adjusted over time as they are swapped. * * Note: This does not check for duplicate tokens or that the total * of the desired weights is equal to the target total weight (25). * Those assumptions should be met in the controller. Further, the * provided tokens should only include the tokens which are not set * for removal. */ function reweighTokens( address[] calldata tokens, uint96[] calldata desiredDenorms ) external override _lock_ _control_ { require(desiredDenorms.length == tokens.length, "ERR_ARR_LEN"); for (uint256 i = 0; i < tokens.length; i++) _setDesiredDenorm(tokens[i], desiredDenorms[i]); } /** * @dev Update the underlying assets held by the pool and their associated * weights. Tokens which are not currently bound will be gradually added * as they are swapped in to reach the provided minimum balances, which must * be an amount of tokens worth the minimum weight of the total pool value. * If a currently bound token is not received in this call, the token's * desired weight will be set to 0. */ function reindexTokens( address[] calldata tokens, uint96[] calldata desiredDenorms, uint256[] calldata minimumBalances ) external override _lock_ _control_ { require( desiredDenorms.length == tokens.length && minimumBalances.length == tokens.length, "ERR_ARR_LEN" ); // This size may not be the same as the input size, as it is possible // to temporarily exceed the index size while tokens are being phased in // or out. uint256 tLen = _tokens.length; bool[] memory receivedIndices = new bool[](tLen); // We need to read token records in two separate loops, so // write them to memory to avoid duplicate storage reads. Record[] memory records = new Record[](tokens.length); // Read all the records from storage and mark which of the existing tokens // were represented in the reindex call. for (uint256 i = 0; i < tokens.length; i++) { records[i] = _records[tokens[i]]; if (records[i].bound) receivedIndices[records[i].index] = true; } // If any bound tokens were not sent in this call, set their desired weights to 0. for (uint256 i = 0; i < tLen; i++) { if (!receivedIndices[i]) { _setDesiredDenorm(_tokens[i], 0); } } for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; // If an input weight is less than the minimum weight, use that instead. uint96 denorm = desiredDenorms[i]; if (denorm < MIN_WEIGHT) denorm = uint96(MIN_WEIGHT); if (!records[i].bound) { // If the token is not bound, bind it. _bind(token, minimumBalances[i], denorm); } else { _setDesiredDenorm(token, denorm); } } } /** * @dev Updates the minimum balance for an uninitialized token. * This becomes useful if a token's external price significantly * rises after being bound, since the pool can not send a token * out until it reaches the minimum balance. */ function setMinimumBalance( address token, uint256 minimumBalance ) external override _control_ { Record storage record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); require(!record.ready, "ERR_READY"); _minimumBalances[token] = minimumBalance; emit LOG_MINIMUM_BALANCE_UPDATED(token, minimumBalance); } /* ========== Liquidity Provider Actions ========== */ /** * @dev Mint new pool tokens by providing the proportional amount of each * underlying token's balance relative to the proportion of pool tokens minted. * * For any underlying tokens which are not initialized, the caller must provide * the proportional share of the minimum balance for the token rather than the * actual balance. * * @param poolAmountOut Amount of pool tokens to mint * @param maxAmountsIn Maximum amount of each token to pay in the same * order as the pool's _tokens list. */ function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external override _lock_ _public_ { uint256 poolTotal = totalSupply(); uint256 ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); require(maxAmountsIn.length == _tokens.length, "ERR_ARR_LEN"); for (uint256 i = 0; i < maxAmountsIn.length; i++) { address t = _tokens[i]; (Record memory record, uint256 realBalance) = _getInputToken(t); uint256 tokenAmountIn = bmul(ratio, record.balance); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN"); _updateInputToken(t, record, badd(realBalance, tokenAmountIn)); emit LOG_JOIN(msg.sender, t, tokenAmountIn); _pullUnderlying(t, msg.sender, tokenAmountIn); } _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); } /** * @dev Pay `tokenAmountIn` of `tokenIn` to mint at least `minPoolAmountOut` * pool tokens. * * The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other * underlying tokens. Thus a swap fee is charged against the input tokens. * * @param tokenIn Token to send the pool * @param tokenAmountIn Exact amount of `tokenIn` to pay * @param minPoolAmountOut Minimum amount of pool tokens to mint * @return poolAmountOut - Amount of pool tokens minted */ function joinswapExternAmountIn( address tokenIn, uint256 tokenAmountIn, uint256 minPoolAmountOut ) external override _lock_ _public_ returns (uint256/* poolAmountOut */) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); require(tokenAmountIn != 0, "ERR_ZERO_IN"); require( tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO" ); uint256 poolAmountOut = calcPoolOutGivenSingleIn( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, tokenAmountIn, _swapFee ); require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT"); _updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn)); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return poolAmountOut; } /** * @dev Pay up to `maxAmountIn` of `tokenIn` to mint exactly `poolAmountOut`. * * The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other * underlying tokens. Thus a swap fee is charged against the input tokens. * * @param tokenIn Token to send the pool * @param poolAmountOut Exact amount of pool tokens to mint * @param maxAmountIn Maximum amount of `tokenIn` to pay * @return tokenAmountIn - Amount of `tokenIn` paid */ function joinswapPoolAmountOut( address tokenIn, uint256 poolAmountOut, uint256 maxAmountIn ) external override _lock_ _public_ returns (uint256/* tokenAmountIn */) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); uint256 tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, poolAmountOut, _swapFee ); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); require( tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO" ); _updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn)); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return tokenAmountIn; } /** * @dev Burns `poolAmountIn` pool tokens in exchange for the amounts of each * underlying token's balance proportional to the ratio of tokens burned to * total pool supply. The amount of each token transferred to the caller must * be greater than or equal to the associated minimum output amount from the * `minAmountsOut` array. * * @param poolAmountIn Exact amount of pool tokens to burn * @param minAmountsOut Minimum amount of each token to receive, in the same * order as the pool's _tokens list. */ function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external override _lock_ { require(minAmountsOut.length == _tokens.length, "ERR_ARR_LEN"); uint256 poolTotal = totalSupply(); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); uint256 pAiAfterExitFee = bsub(poolAmountIn, exitFee); uint256 ratio = bdiv(pAiAfterExitFee, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); _pullPoolShare(msg.sender, poolAmountIn); _pushPoolShare(_exitFeeRecipient, exitFee); _burnPoolShare(pAiAfterExitFee); for (uint256 i = 0; i < minAmountsOut.length; i++) { address t = _tokens[i]; Record memory record = _records[t]; if (record.ready) { uint256 tokenAmountOut = bmul(ratio, record.balance); require(tokenAmountOut != 0, "ERR_MATH_APPROX"); require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT"); _records[t].balance = bsub(record.balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut); _pushUnderlying(t, msg.sender, tokenAmountOut); } else { // If the token is not initialized, it can not exit the pool. require(minAmountsOut[i] == 0, "ERR_OUT_NOT_READY"); } } } /** * @dev Burns `poolAmountIn` pool tokens in exchange for at least `minAmountOut` * of `tokenOut`. Returns the number of tokens sent to the caller. * * The pool implicitly burns the tokens for all underlying tokens and swaps them * to the desired output token. A swap fee is charged against the output tokens. * * @param tokenOut Token to receive * @param poolAmountIn Exact amount of pool tokens to burn * @param minAmountOut Minimum amount of `tokenOut` to receive * @return tokenAmountOut - Amount of `tokenOut` received */ function exitswapPoolAmountIn( address tokenOut, uint256 poolAmountIn, uint256 minAmountOut ) external override _lock_ returns (uint256/* tokenAmountOut */) { Record memory outRecord = _getOutputToken(tokenOut); uint256 tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, poolAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require( tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO" ); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); _records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut); _decreaseDenorm(outRecord, tokenOut); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_exitFeeRecipient, exitFee); return tokenAmountOut; } /** * @dev Burn up to `maxPoolAmountIn` for exactly `tokenAmountOut` of `tokenOut`. * Returns the number of pool tokens burned. * * The pool implicitly burns the tokens for all underlying tokens and swaps them * to the desired output token. A swap fee is charged against the output tokens. * * @param tokenOut Token to receive * @param tokenAmountOut Exact amount of `tokenOut` to receive * @param maxPoolAmountIn Maximum amount of pool tokens to burn * @return poolAmountIn - Amount of pool tokens burned */ function exitswapExternAmountOut( address tokenOut, uint256 tokenAmountOut, uint256 maxPoolAmountIn ) external override _lock_ returns (uint256/* poolAmountIn */) { Record memory outRecord = _getOutputToken(tokenOut); require( tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO" ); uint256 poolAmountIn = calcPoolInGivenSingleOut( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, tokenAmountOut, _swapFee ); require(poolAmountIn != 0, "ERR_MATH_APPROX"); require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN"); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); _records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut); _decreaseDenorm(outRecord, tokenOut); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_exitFeeRecipient, exitFee); return poolAmountIn; } /* ========== Other ========== */ /** * @dev Absorb any tokens that have been sent to the pool. * If the token is not bound, it will be sent to the unbound * token handler. */ function gulp(address token) external override _lock_ { Record storage record = _records[token]; uint256 balance = IERC20(token).balanceOf(address(this)); if (record.bound) { if (!record.ready) { uint256 minimumBalance = _minimumBalances[token]; if (balance >= minimumBalance) { _minimumBalances[token] = 0; record.ready = true; emit LOG_TOKEN_READY(token); uint256 additionalBalance = bsub(balance, minimumBalance); uint256 balRatio = bdiv(additionalBalance, minimumBalance); uint96 newDenorm = uint96(badd(MIN_WEIGHT, bmul(MIN_WEIGHT, balRatio))); record.denorm = newDenorm; record.lastDenormUpdate = uint40(now); _totalWeight = badd(_totalWeight, newDenorm); emit LOG_DENORM_UPDATED(token, record.denorm); } } _records[token].balance = balance; } else { _pushUnderlying(token, address(_unbindHandler), balance); _unbindHandler.handleUnbindToken(token, balance); } } /* ========== Token Swaps ========== */ /** * @dev Execute a token swap with a specified amount of input * tokens and a minimum amount of output tokens. * * Note: Will revert if `tokenOut` is uninitialized. * * @param tokenIn Token to swap in * @param tokenAmountIn Exact amount of `tokenIn` to swap in * @param tokenOut Token to swap out * @param minAmountOut Minimum amount of `tokenOut` to receive * @param maxPrice Maximum ratio of input to output tokens * @return (tokenAmountOut, spotPriceAfter) */ function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external override _lock_ _public_ returns (uint256/* tokenAmountOut */, uint256/* spotPriceAfter */) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); Record memory outRecord = _getOutputToken(tokenOut); require( tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO" ); uint256 spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); uint256 tokenAmountOut = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); // Update the in-memory record for the spotPriceAfter calculation, // then update the storage record with the local balance. outRecord.balance = bsub(outRecord.balance, tokenAmountOut); _records[tokenOut].balance = outRecord.balance; // If needed, update the output token's weight. _decreaseDenorm(outRecord, tokenOut); realInBalance = badd(realInBalance, tokenAmountIn); _updateInputToken(tokenIn, inRecord, realInBalance); if (inRecord.ready) { inRecord.balance = realInBalance; } uint256 spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX_2"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require( spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX" ); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); return (tokenAmountOut, spotPriceAfter); } /** * @dev Trades at most `maxAmountIn` of `tokenIn` for exactly `tokenAmountOut` * of `tokenOut`. * * Returns the actual input amount and the new spot price after the swap, * which can not exceed `maxPrice`. * * @param tokenIn Token to swap in * @param maxAmountIn Maximum amount of `tokenIn` to pay * @param tokenOut Token to swap out * @param tokenAmountOut Exact amount of `tokenOut` to receive * @param maxPrice Maximum ratio of input to output tokens * @return (tokenAmountIn, spotPriceAfter) */ function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external override _lock_ _public_ returns (uint256 /* tokenAmountIn */, uint256 /* spotPriceAfter */) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); Record memory outRecord = _getOutputToken(tokenOut); require( tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO" ); uint256 spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); uint256 tokenAmountIn = calcInGivenOut( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountOut, _swapFee ); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); // Update the in-memory record for the spotPriceAfter calculation, // then update the storage record with the local balance. outRecord.balance = bsub(outRecord.balance, tokenAmountOut); _records[tokenOut].balance = outRecord.balance; // If needed, update the output token's weight. _decreaseDenorm(outRecord, tokenOut); // Update the balance and (if necessary) weight of the input token. realInBalance = badd(realInBalance, tokenAmountIn); _updateInputToken(tokenIn, inRecord, realInBalance); if (inRecord.ready) { inRecord.balance = realInBalance; } uint256 spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require( spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX" ); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); return (tokenAmountIn, spotPriceAfter); } /* ========== Config Queries ========== */ /** * @dev Check if swapping tokens and joining the pool is allowed. */ function isPublicSwap() external view override returns (bool) { return _publicSwap; } function getSwapFee() external view override _viewlock_ returns (uint256/* swapFee */) { return _swapFee; } function getExitFee() external view override _viewlock_ returns (uint256/* exitFee */) { return EXIT_FEE; } /** * @dev Returns the controller address. */ function getController() external view override returns (address) { return _controller; } /** * @dev Returns the exit fee recipient address. */ function getExitFeeRecipient() external view override returns (address) { return _exitFeeRecipient; } /* ========== Token Queries ========== */ /** * @dev Check if a token is bound to the pool. */ function isBound(address t) external view override returns (bool) { return _records[t].bound; } /** * @dev Get the number of tokens bound to the pool. */ function getNumTokens() external view override returns (uint256) { return _tokens.length; } /** * @dev Get all bound tokens. */ function getCurrentTokens() external view override _viewlock_ returns (address[] memory tokens) { tokens = _tokens; } /** * @dev Returns the list of tokens which have a desired weight above 0. * Tokens with a desired weight of 0 are set to be phased out of the pool. */ function getCurrentDesiredTokens() external view override _viewlock_ returns (address[] memory tokens) { address[] memory tempTokens = _tokens; tokens = new address[](tempTokens.length); uint256 usedIndex = 0; for (uint256 i = 0; i < tokens.length; i++) { address token = tempTokens[i]; if (_records[token].desiredDenorm > 0) { tokens[usedIndex++] = token; } } assembly { mstore(tokens, usedIndex) } } /** * @dev Returns the denormalized weight of a bound token. */ function getDenormalizedWeight(address token) external view override _viewlock_ returns (uint256/* denorm */) { require(_records[token].bound, "ERR_NOT_BOUND"); return _records[token].denorm; } /** * @dev Returns the record for a token bound to the pool. */ function getTokenRecord(address token) external view override _viewlock_ returns (Record memory record) { record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); } /** * @dev Finds the first token which is both initialized and has a * desired weight above 0, then returns the address of that token * and the extrapolated value of the pool in terms of that token. * * The value is extrapolated by multiplying the token's * balance by the reciprocal of its normalized weight. * @return (token, extrapolatedValue) */ function extrapolatePoolValueFromToken() external view override _viewlock_ returns (address/* token */, uint256/* extrapolatedValue */) { address token; uint256 extrapolatedValue; uint256 len = _tokens.length; for (uint256 i = 0; i < len; i++) { token = _tokens[i]; Record storage record = _records[token]; if (record.ready && record.desiredDenorm > 0) { extrapolatedValue = bmul( record.balance, bdiv(_totalWeight, record.denorm) ); break; } } require(extrapolatedValue > 0, "ERR_NONE_READY"); return (token, extrapolatedValue); } /** * @dev Get the total denormalized weight of the pool. */ function getTotalDenormalizedWeight() external view override _viewlock_ returns (uint256) { return _totalWeight; } /** * @dev Returns the stored balance of a bound token. */ function getBalance(address token) external view override _viewlock_ returns (uint256) { Record storage record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); return record.balance; } /** * @dev Get the minimum balance of an uninitialized token. * Note: Throws if the token is initialized. */ function getMinimumBalance(address token) external view override _viewlock_ returns (uint256) { Record memory record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); require(!record.ready, "ERR_READY"); return _minimumBalances[token]; } /** * @dev Returns the balance of a token which is used in price * calculations. If the token is initialized, this is the * stored balance; if not, this is the minimum balance. */ function getUsedBalance(address token) external view override _viewlock_ returns (uint256) { Record memory record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); if (!record.ready) { return _minimumBalances[token]; } return record.balance; } /* ========== Price Queries ========== */ /** * @dev Returns the spot price for `tokenOut` in terms of `tokenIn`. */ function getSpotPrice(address tokenIn, address tokenOut) external view override _viewlock_ returns (uint256) { (Record memory inRecord,) = _getInputToken(tokenIn); Record memory outRecord = _getOutputToken(tokenOut); return calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); } /* ========== Pool Share Internal Functions ========== */ function _pullPoolShare(address from, uint256 amount) internal { _pull(from, amount); } function _pushPoolShare(address to, uint256 amount) internal { _push(to, amount); } function _mintPoolShare(uint256 amount) internal { _mint(amount); } function _burnPoolShare(uint256 amount) internal { _burn(amount); } /* ========== Underlying Token Internal Functions ========== */ // 'Underlying' token-manipulation functions make external calls but are NOT locked // You must `_lock_` or otherwise ensure reentry-safety function _pullUnderlying( address erc20, address from, uint256 amount ) internal { (bool success, bytes memory data) = erc20.call( abi.encodeWithSelector( IERC20.transferFrom.selector, from, address(this), amount ) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "ERR_ERC20_FALSE" ); } function _pushUnderlying( address erc20, address to, uint256 amount ) internal { (bool success, bytes memory data) = erc20.call( abi.encodeWithSelector( IERC20.transfer.selector, to, amount ) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "ERR_ERC20_FALSE" ); } /* ========== Token Management Internal Functions ========== */ /** * @dev Bind a token by address without actually depositing a balance. * The token will be unable to be swapped out until it reaches the minimum balance. * Note: Token must not already be bound. * Note: `minimumBalance` should represent an amount of the token which is worth * the portion of the current pool value represented by the minimum weight. * @param token Address of the token to bind * @param minimumBalance minimum balance to reach before the token can be swapped out * @param desiredDenorm Desired weight for the token. */ function _bind( address token, uint256 minimumBalance, uint96 desiredDenorm ) internal { require(!_records[token].bound, "ERR_IS_BOUND"); require(desiredDenorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(desiredDenorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); require(minimumBalance >= MIN_BALANCE, "ERR_MIN_BALANCE"); _records[token] = Record({ bound: true, ready: false, lastDenormUpdate: 0, denorm: 0, desiredDenorm: desiredDenorm, index: uint8(_tokens.length), balance: 0 }); _tokens.push(token); _minimumBalances[token] = minimumBalance; emit LOG_TOKEN_ADDED(token, desiredDenorm, minimumBalance); } /** * @dev Remove a token from the pool. * Replaces the address in the tokens array with the last address, * then removes it from the array. * Note: This should only be called after the total weight has been adjusted. * Note: Must be called in a function with: * - _lock_ modifier to prevent reentrance * - requirement that the token is bound */ function _unbind(address token) internal { Record memory record = _records[token]; uint256 tokenBalance = record.balance; // Swap the token-to-unbind with the last token, // then delete the last token uint256 index = record.index; uint256 last = _tokens.length - 1; // Only swap the token with the last token if it is not // already at the end of the array. if (index != last) { _tokens[index] = _tokens[last]; _records[_tokens[index]].index = uint8(index); } _tokens.pop(); _records[token] = Record({ bound: false, ready: false, lastDenormUpdate: 0, denorm: 0, desiredDenorm: 0, index: 0, balance: 0 }); // transfer any remaining tokens out _pushUnderlying(token, address(_unbindHandler), tokenBalance); _unbindHandler.handleUnbindToken(token, tokenBalance); emit LOG_TOKEN_REMOVED(token); } function _setDesiredDenorm(address token, uint96 desiredDenorm) internal { Record storage record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); // If the desired weight is 0, this will trigger a gradual unbinding of the token. // Therefore the weight only needs to be above the minimum weight if it isn't 0. require( desiredDenorm >= MIN_WEIGHT || desiredDenorm == 0, "ERR_MIN_WEIGHT" ); require(desiredDenorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); record.desiredDenorm = desiredDenorm; emit LOG_DESIRED_DENORM_SET(token, desiredDenorm); } function _increaseDenorm(Record memory record, address token) internal { // If the weight does not need to increase or the token is not // initialized, don't do anything. if ( record.denorm >= record.desiredDenorm || !record.ready || now - record.lastDenormUpdate < WEIGHT_UPDATE_DELAY ) return; uint96 oldWeight = record.denorm; uint96 denorm = record.desiredDenorm; uint256 maxDiff = bmul(oldWeight, WEIGHT_CHANGE_PCT); uint256 diff = bsub(denorm, oldWeight); if (diff > maxDiff) { denorm = uint96(badd(oldWeight, maxDiff)); diff = maxDiff; } // If new total weight exceeds the maximum, do not update uint256 newTotalWeight = badd(_totalWeight, diff); if (newTotalWeight > MAX_TOTAL_WEIGHT) return; _totalWeight = newTotalWeight; // Update the in-memory denorm value for spot-price computations. record.denorm = denorm; // Update the storage record _records[token].denorm = denorm; _records[token].lastDenormUpdate = uint40(now); emit LOG_DENORM_UPDATED(token, denorm); } function _decreaseDenorm(Record memory record, address token) internal { // If the weight does not need to decrease, don't do anything. if ( record.denorm <= record.desiredDenorm || !record.ready || now - record.lastDenormUpdate < WEIGHT_UPDATE_DELAY ) return; uint96 oldWeight = record.denorm; uint96 denorm = record.desiredDenorm; uint256 maxDiff = bmul(oldWeight, WEIGHT_CHANGE_PCT); uint256 diff = bsub(oldWeight, denorm); if (diff > maxDiff) { denorm = uint96(bsub(oldWeight, maxDiff)); diff = maxDiff; } if (denorm <= MIN_WEIGHT) { denorm = 0; _totalWeight = bsub(_totalWeight, denorm); // Because this is removing the token from the pool, the // in-memory denorm value is irrelevant, as it is only used // to calculate the new spot price, but the spot price calc // will throw if it is passed 0 for the denorm. _unbind(token); } else { _totalWeight = bsub(_totalWeight, diff); // Update the in-memory denorm value for spot-price computations. record.denorm = denorm; // Update the stored denorm value _records[token].denorm = denorm; _records[token].lastDenormUpdate = uint40(now); emit LOG_DENORM_UPDATED(token, denorm); } } /** * @dev Handles weight changes and initialization of an * input token. * * If the token is not initialized and the new balance is * still below the minimum, this will not do anything. * * If the token is not initialized but the new balance will * bring the token above the minimum balance, this will * mark the token as initialized, remove the minimum * balance and set the weight to the minimum weight plus * 1%. * * * @param token Address of the input token * @param record Token record with minimums applied to the balance * and weight if the token was uninitialized. */ function _updateInputToken( address token, Record memory record, uint256 realBalance ) internal { if (!record.ready) { // Check if the minimum balance has been reached if (realBalance >= record.balance) { // Remove the minimum balance record _minimumBalances[token] = 0; // Mark the token as initialized _records[token].ready = true; record.ready = true; emit LOG_TOKEN_READY(token); // Set the initial denorm value to the minimum weight times one plus // the ratio of the increase in balance over the minimum to the minimum // balance. // weight = (1 + ((bal - min_bal) / min_bal)) * min_weight uint256 additionalBalance = bsub(realBalance, record.balance); uint256 balRatio = bdiv(additionalBalance, record.balance); record.denorm = uint96(badd(MIN_WEIGHT, bmul(MIN_WEIGHT, balRatio))); _records[token].denorm = record.denorm; _records[token].lastDenormUpdate = uint40(now); _totalWeight = badd(_totalWeight, record.denorm); emit LOG_DENORM_UPDATED(token, record.denorm); } else { uint256 realToMinRatio = bdiv( bsub(record.balance, realBalance), record.balance ); uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio); record.denorm = uint96(badd(MIN_WEIGHT, weightPremium)); } // If the token is still not ready, do not adjust the weight. } else { // If the token is already initialized, update the weight (if any adjustment // is needed). _increaseDenorm(record, token); } // Regardless of whether the token is initialized, store the actual new balance. _records[token].balance = realBalance; } /* ========== Token Query Internal Functions ========== */ /** * @dev Get the record for a token which is being swapped in. * The token must be bound to the pool. If the token is not * initialized (meaning it does not have the minimum balance) * this function will return the actual balance of the token * which the pool holds, but set the record's balance and weight * to the token's minimum balance and the pool's minimum weight. * This allows the token swap to be priced correctly even if the * pool does not own any of the tokens. */ function _getInputToken(address token) internal view returns (Record memory record, uint256 realBalance) { record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); realBalance = record.balance; // If the input token is not initialized, we use the minimum // initial weight and minimum initial balance instead of the // real values for price and output calculations. if (!record.ready) { record.balance = _minimumBalances[token]; uint256 realToMinRatio = bdiv( bsub(record.balance, realBalance), record.balance ); uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio); record.denorm = uint96(badd(MIN_WEIGHT, weightPremium)); } } function _getOutputToken(address token) internal view returns (Record memory record) { record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); // Tokens which have not reached their minimum balance can not be // swapped out. require(record.ready, "ERR_OUT_NOT_READY"); } }
contract SigmaIndexPoolV1 is BToken, BMath, IIndexPool { /* ========== Modifiers ========== */ modifier _lock_ { require(!_mutex, "ERR_REENTRY"); _mutex = true; _; _mutex = false; } modifier _viewlock_() { require(!_mutex, "ERR_REENTRY"); _; } modifier _control_ { require(msg.sender == _controller, "ERR_NOT_CONTROLLER"); _; } modifier _public_ { require(_publicSwap, "ERR_NOT_PUBLIC"); _; } /* ========== Storage ========== */ bool internal _mutex; // Account with CONTROL role. Able to modify the swap fee, // adjust token weights, bind and unbind tokens and lock // public swaps & joins. address internal _controller; // Contract that handles unbound tokens. TokenUnbindHandler internal _unbindHandler; // True if PUBLIC can call SWAP & JOIN functions bool internal _publicSwap; // `setSwapFee` requires CONTROL uint256 internal _swapFee; // Array of underlying tokens in the pool. address[] internal _tokens; // Internal records of the pool's underlying tokens mapping(address => Record) internal _records; // Total denormalized weight of the pool. uint256 internal _totalWeight; // Minimum balances for tokens which have been added without the // requisite initial balance. mapping(address => uint256) internal _minimumBalances; // Recipient for exit fees address internal _exitFeeRecipient; /* ========== Controls ========== */ /** * @dev Sets the controller address and the token name & symbol. * * Note: This saves on storage costs for multi-step pool deployment. * * @param controller Controller of the pool * @param name Name of the pool token * @param symbol Symbol of the pool token */ function configure( address controller, string calldata name, string calldata symbol ) external override { require(_controller == address(0), "ERR_CONFIGURED"); require(controller != address(0), "ERR_NULL_ADDRESS"); _controller = controller; // default fee is 2% _swapFee = BONE / 50; _initializeToken(name, symbol); } /** * @dev Sets up the initial assets for the pool. * * Note: `tokenProvider` must have approved the pool to transfer the * corresponding `balances` of `tokens`. * * @param tokens Underlying tokens to initialize the pool with * @param balances Initial balances to transfer * @param denorms Initial denormalized weights for the tokens * @param tokenProvider Address to transfer the balances from * @param unbindHandler Address that receives tokens removed from the pool * @param exitFeeRecipient Address that receives exit fees */ function initialize( address[] calldata tokens, uint256[] calldata balances, uint96[] calldata denorms, address tokenProvider, address unbindHandler, address exitFeeRecipient ) external override _control_ { require(_tokens.length == 0, "ERR_INITIALIZED"); uint256 len = tokens.length; require(len >= MIN_BOUND_TOKENS, "ERR_MIN_TOKENS"); require(len <= MAX_BOUND_TOKENS, "ERR_MAX_TOKENS"); require(balances.length == len && denorms.length == len, "ERR_ARR_LEN"); uint256 totalWeight = 0; for (uint256 i = 0; i < len; i++) { address token = tokens[i]; uint96 denorm = denorms[i]; uint256 balance = balances[i]; require(denorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(denorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); require(balance >= MIN_BALANCE, "ERR_MIN_BALANCE"); _records[token] = Record({ bound: true, ready: true, lastDenormUpdate: uint40(now), denorm: denorm, desiredDenorm: denorm, index: uint8(i), balance: balance }); _tokens.push(token); totalWeight = badd(totalWeight, denorm); _pullUnderlying(token, tokenProvider, balance); } require(totalWeight <= MAX_TOTAL_WEIGHT, "ERR_MAX_TOTAL_WEIGHT"); _totalWeight = totalWeight; _publicSwap = true; emit LOG_PUBLIC_SWAP_TOGGLED(true); _mintPoolShare(INIT_POOL_SUPPLY); _pushPoolShare(tokenProvider, INIT_POOL_SUPPLY); _unbindHandler = TokenUnbindHandler(unbindHandler); _exitFeeRecipient = exitFeeRecipient; } /** * @dev Set the swap fee. * Note: Swap fee must be between 0.0001% and 10% */ function setSwapFee(uint256 swapFee) external override _control_ { require(swapFee >= MIN_FEE && swapFee <= MAX_FEE, "ERR_INVALID_FEE"); _swapFee = swapFee; emit LOG_SWAP_FEE_UPDATED(swapFee); } /** * @dev Set the controller address. */ function setController(address controller) external override _control_ { require(controller != address(0), "ERR_NULL_ADDRESS"); _controller = controller; emit LOG_CONTROLLER_UPDATED(controller); } /** * @dev Delegate a comp-like governance token to an address * specified by the controller. */ function delegateCompLikeToken(address token, address delegatee) external override _control_ { ICompLikeToken(token).delegate(delegatee); } /** * @dev Set the exit fee recipient address. */ function setExitFeeRecipient(address exitFeeRecipient) external override _control_ { require(exitFeeRecipient != address(0), "ERR_NULL_ADDRESS"); _exitFeeRecipient = exitFeeRecipient; emit LOG_EXIT_FEE_RECIPIENT_UPDATED(exitFeeRecipient); } /** * @dev Toggle public trading for the index pool. * This will enable or disable swaps and single-token joins and exits. */ function setPublicSwap(bool enabled) external override _control_ { _publicSwap = enabled; emit LOG_PUBLIC_SWAP_TOGGLED(enabled); } /* ========== Token Management Actions ========== */ /** * @dev Sets the desired weights for the pool tokens, which * will be adjusted over time as they are swapped. * * Note: This does not check for duplicate tokens or that the total * of the desired weights is equal to the target total weight (25). * Those assumptions should be met in the controller. Further, the * provided tokens should only include the tokens which are not set * for removal. */ function reweighTokens( address[] calldata tokens, uint96[] calldata desiredDenorms ) external override _lock_ _control_ { require(desiredDenorms.length == tokens.length, "ERR_ARR_LEN"); for (uint256 i = 0; i < tokens.length; i++) _setDesiredDenorm(tokens[i], desiredDenorms[i]); } /** * @dev Update the underlying assets held by the pool and their associated * weights. Tokens which are not currently bound will be gradually added * as they are swapped in to reach the provided minimum balances, which must * be an amount of tokens worth the minimum weight of the total pool value. * If a currently bound token is not received in this call, the token's * desired weight will be set to 0. */ function reindexTokens( address[] calldata tokens, uint96[] calldata desiredDenorms, uint256[] calldata minimumBalances ) external override _lock_ _control_ { require( desiredDenorms.length == tokens.length && minimumBalances.length == tokens.length, "ERR_ARR_LEN" ); // This size may not be the same as the input size, as it is possible // to temporarily exceed the index size while tokens are being phased in // or out. uint256 tLen = _tokens.length; bool[] memory receivedIndices = new bool[](tLen); // We need to read token records in two separate loops, so // write them to memory to avoid duplicate storage reads. Record[] memory records = new Record[](tokens.length); // Read all the records from storage and mark which of the existing tokens // were represented in the reindex call. for (uint256 i = 0; i < tokens.length; i++) { records[i] = _records[tokens[i]]; if (records[i].bound) receivedIndices[records[i].index] = true; } // If any bound tokens were not sent in this call, set their desired weights to 0. for (uint256 i = 0; i < tLen; i++) { if (!receivedIndices[i]) { _setDesiredDenorm(_tokens[i], 0); } } for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; // If an input weight is less than the minimum weight, use that instead. uint96 denorm = desiredDenorms[i]; if (denorm < MIN_WEIGHT) denorm = uint96(MIN_WEIGHT); if (!records[i].bound) { // If the token is not bound, bind it. _bind(token, minimumBalances[i], denorm); } else { _setDesiredDenorm(token, denorm); } } } /** * @dev Updates the minimum balance for an uninitialized token. * This becomes useful if a token's external price significantly * rises after being bound, since the pool can not send a token * out until it reaches the minimum balance. */ function setMinimumBalance( address token, uint256 minimumBalance ) external override _control_ { Record storage record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); require(!record.ready, "ERR_READY"); _minimumBalances[token] = minimumBalance; emit LOG_MINIMUM_BALANCE_UPDATED(token, minimumBalance); } /* ========== Liquidity Provider Actions ========== */ /** * @dev Mint new pool tokens by providing the proportional amount of each * underlying token's balance relative to the proportion of pool tokens minted. * * For any underlying tokens which are not initialized, the caller must provide * the proportional share of the minimum balance for the token rather than the * actual balance. * * @param poolAmountOut Amount of pool tokens to mint * @param maxAmountsIn Maximum amount of each token to pay in the same * order as the pool's _tokens list. */ function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external override _lock_ _public_ { uint256 poolTotal = totalSupply(); uint256 ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); require(maxAmountsIn.length == _tokens.length, "ERR_ARR_LEN"); for (uint256 i = 0; i < maxAmountsIn.length; i++) { address t = _tokens[i]; (Record memory record, uint256 realBalance) = _getInputToken(t); uint256 tokenAmountIn = bmul(ratio, record.balance); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN"); _updateInputToken(t, record, badd(realBalance, tokenAmountIn)); emit LOG_JOIN(msg.sender, t, tokenAmountIn); _pullUnderlying(t, msg.sender, tokenAmountIn); } _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); } /** * @dev Pay `tokenAmountIn` of `tokenIn` to mint at least `minPoolAmountOut` * pool tokens. * * The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other * underlying tokens. Thus a swap fee is charged against the input tokens. * * @param tokenIn Token to send the pool * @param tokenAmountIn Exact amount of `tokenIn` to pay * @param minPoolAmountOut Minimum amount of pool tokens to mint * @return poolAmountOut - Amount of pool tokens minted */ function joinswapExternAmountIn( address tokenIn, uint256 tokenAmountIn, uint256 minPoolAmountOut ) external override _lock_ _public_ returns (uint256/* poolAmountOut */) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); require(tokenAmountIn != 0, "ERR_ZERO_IN"); require( tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO" ); uint256 poolAmountOut = calcPoolOutGivenSingleIn( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, tokenAmountIn, _swapFee ); require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT"); _updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn)); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return poolAmountOut; } /** * @dev Pay up to `maxAmountIn` of `tokenIn` to mint exactly `poolAmountOut`. * * The pool implicitly swaps `(1- weightTokenIn) * tokenAmountIn` to the other * underlying tokens. Thus a swap fee is charged against the input tokens. * * @param tokenIn Token to send the pool * @param poolAmountOut Exact amount of pool tokens to mint * @param maxAmountIn Maximum amount of `tokenIn` to pay * @return tokenAmountIn - Amount of `tokenIn` paid */ function joinswapPoolAmountOut( address tokenIn, uint256 poolAmountOut, uint256 maxAmountIn ) external override _lock_ _public_ returns (uint256/* tokenAmountIn */) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); uint256 tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, poolAmountOut, _swapFee ); require(tokenAmountIn != 0, "ERR_MATH_APPROX"); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); require( tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO" ); _updateInputToken(tokenIn, inRecord, badd(realInBalance, tokenAmountIn)); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return tokenAmountIn; } /** * @dev Burns `poolAmountIn` pool tokens in exchange for the amounts of each * underlying token's balance proportional to the ratio of tokens burned to * total pool supply. The amount of each token transferred to the caller must * be greater than or equal to the associated minimum output amount from the * `minAmountsOut` array. * * @param poolAmountIn Exact amount of pool tokens to burn * @param minAmountsOut Minimum amount of each token to receive, in the same * order as the pool's _tokens list. */ function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external override _lock_ { require(minAmountsOut.length == _tokens.length, "ERR_ARR_LEN"); uint256 poolTotal = totalSupply(); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); uint256 pAiAfterExitFee = bsub(poolAmountIn, exitFee); uint256 ratio = bdiv(pAiAfterExitFee, poolTotal); require(ratio != 0, "ERR_MATH_APPROX"); _pullPoolShare(msg.sender, poolAmountIn); _pushPoolShare(_exitFeeRecipient, exitFee); _burnPoolShare(pAiAfterExitFee); for (uint256 i = 0; i < minAmountsOut.length; i++) { address t = _tokens[i]; Record memory record = _records[t]; if (record.ready) { uint256 tokenAmountOut = bmul(ratio, record.balance); require(tokenAmountOut != 0, "ERR_MATH_APPROX"); require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT"); _records[t].balance = bsub(record.balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut); _pushUnderlying(t, msg.sender, tokenAmountOut); } else { // If the token is not initialized, it can not exit the pool. require(minAmountsOut[i] == 0, "ERR_OUT_NOT_READY"); } } } /** * @dev Burns `poolAmountIn` pool tokens in exchange for at least `minAmountOut` * of `tokenOut`. Returns the number of tokens sent to the caller. * * The pool implicitly burns the tokens for all underlying tokens and swaps them * to the desired output token. A swap fee is charged against the output tokens. * * @param tokenOut Token to receive * @param poolAmountIn Exact amount of pool tokens to burn * @param minAmountOut Minimum amount of `tokenOut` to receive * @return tokenAmountOut - Amount of `tokenOut` received */ function exitswapPoolAmountIn( address tokenOut, uint256 poolAmountIn, uint256 minAmountOut ) external override _lock_ returns (uint256/* tokenAmountOut */) { Record memory outRecord = _getOutputToken(tokenOut); uint256 tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, poolAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); require( tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO" ); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); _records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut); _decreaseDenorm(outRecord, tokenOut); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_exitFeeRecipient, exitFee); return tokenAmountOut; } /** * @dev Burn up to `maxPoolAmountIn` for exactly `tokenAmountOut` of `tokenOut`. * Returns the number of pool tokens burned. * * The pool implicitly burns the tokens for all underlying tokens and swaps them * to the desired output token. A swap fee is charged against the output tokens. * * @param tokenOut Token to receive * @param tokenAmountOut Exact amount of `tokenOut` to receive * @param maxPoolAmountIn Maximum amount of pool tokens to burn * @return poolAmountIn - Amount of pool tokens burned */ function exitswapExternAmountOut( address tokenOut, uint256 tokenAmountOut, uint256 maxPoolAmountIn ) external override _lock_ returns (uint256/* poolAmountIn */) { Record memory outRecord = _getOutputToken(tokenOut); require( tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO" ); uint256 poolAmountIn = calcPoolInGivenSingleOut( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, tokenAmountOut, _swapFee ); require(poolAmountIn != 0, "ERR_MATH_APPROX"); require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN"); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); _records[tokenOut].balance = bsub(outRecord.balance, tokenAmountOut); _decreaseDenorm(outRecord, tokenOut); uint256 exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_exitFeeRecipient, exitFee); return poolAmountIn; } /* ========== Other ========== */ /** * @dev Absorb any tokens that have been sent to the pool. * If the token is not bound, it will be sent to the unbound * token handler. */ function gulp(address token) external override _lock_ { Record storage record = _records[token]; uint256 balance = IERC20(token).balanceOf(address(this)); if (record.bound) { if (!record.ready) { uint256 minimumBalance = _minimumBalances[token]; if (balance >= minimumBalance) { _minimumBalances[token] = 0; record.ready = true; emit LOG_TOKEN_READY(token); uint256 additionalBalance = bsub(balance, minimumBalance); uint256 balRatio = bdiv(additionalBalance, minimumBalance); uint96 newDenorm = uint96(badd(MIN_WEIGHT, bmul(MIN_WEIGHT, balRatio))); record.denorm = newDenorm; record.lastDenormUpdate = uint40(now); _totalWeight = badd(_totalWeight, newDenorm); emit LOG_DENORM_UPDATED(token, record.denorm); } } _records[token].balance = balance; } else { _pushUnderlying(token, address(_unbindHandler), balance); _unbindHandler.handleUnbindToken(token, balance); } } /* ========== Token Swaps ========== */ /** * @dev Execute a token swap with a specified amount of input * tokens and a minimum amount of output tokens. * * Note: Will revert if `tokenOut` is uninitialized. * * @param tokenIn Token to swap in * @param tokenAmountIn Exact amount of `tokenIn` to swap in * @param tokenOut Token to swap out * @param minAmountOut Minimum amount of `tokenOut` to receive * @param maxPrice Maximum ratio of input to output tokens * @return (tokenAmountOut, spotPriceAfter) */ function swapExactAmountIn( address tokenIn, uint256 tokenAmountIn, address tokenOut, uint256 minAmountOut, uint256 maxPrice ) external override _lock_ _public_ returns (uint256/* tokenAmountOut */, uint256/* spotPriceAfter */) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); Record memory outRecord = _getOutputToken(tokenOut); require( tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO" ); uint256 spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); uint256 tokenAmountOut = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT"); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); // Update the in-memory record for the spotPriceAfter calculation, // then update the storage record with the local balance. outRecord.balance = bsub(outRecord.balance, tokenAmountOut); _records[tokenOut].balance = outRecord.balance; // If needed, update the output token's weight. _decreaseDenorm(outRecord, tokenOut); realInBalance = badd(realInBalance, tokenAmountIn); _updateInputToken(tokenIn, inRecord, realInBalance); if (inRecord.ready) { inRecord.balance = realInBalance; } uint256 spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX_2"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require( spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX" ); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); return (tokenAmountOut, spotPriceAfter); } /** * @dev Trades at most `maxAmountIn` of `tokenIn` for exactly `tokenAmountOut` * of `tokenOut`. * * Returns the actual input amount and the new spot price after the swap, * which can not exceed `maxPrice`. * * @param tokenIn Token to swap in * @param maxAmountIn Maximum amount of `tokenIn` to pay * @param tokenOut Token to swap out * @param tokenAmountOut Exact amount of `tokenOut` to receive * @param maxPrice Maximum ratio of input to output tokens * @return (tokenAmountIn, spotPriceAfter) */ function swapExactAmountOut( address tokenIn, uint256 maxAmountIn, address tokenOut, uint256 tokenAmountOut, uint256 maxPrice ) external override _lock_ _public_ returns (uint256 /* tokenAmountIn */, uint256 /* spotPriceAfter */) { (Record memory inRecord, uint256 realInBalance) = _getInputToken(tokenIn); Record memory outRecord = _getOutputToken(tokenOut); require( tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO" ); uint256 spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE"); uint256 tokenAmountIn = calcInGivenOut( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountOut, _swapFee ); require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN"); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); // Update the in-memory record for the spotPriceAfter calculation, // then update the storage record with the local balance. outRecord.balance = bsub(outRecord.balance, tokenAmountOut); _records[tokenOut].balance = outRecord.balance; // If needed, update the output token's weight. _decreaseDenorm(outRecord, tokenOut); // Update the balance and (if necessary) weight of the input token. realInBalance = badd(realInBalance, tokenAmountIn); _updateInputToken(tokenIn, inRecord, realInBalance); if (inRecord.ready) { inRecord.balance = realInBalance; } uint256 spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX"); require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE"); require( spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX" ); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); return (tokenAmountIn, spotPriceAfter); } /* ========== Config Queries ========== */ /** * @dev Check if swapping tokens and joining the pool is allowed. */ function isPublicSwap() external view override returns (bool) { return _publicSwap; } function getSwapFee() external view override _viewlock_ returns (uint256/* swapFee */) { return _swapFee; } function getExitFee() external view override _viewlock_ returns (uint256/* exitFee */) { return EXIT_FEE; } /** * @dev Returns the controller address. */ function getController() external view override returns (address) { return _controller; } /** * @dev Returns the exit fee recipient address. */ function getExitFeeRecipient() external view override returns (address) { return _exitFeeRecipient; } /* ========== Token Queries ========== */ /** * @dev Check if a token is bound to the pool. */ function isBound(address t) external view override returns (bool) { return _records[t].bound; } /** * @dev Get the number of tokens bound to the pool. */ function getNumTokens() external view override returns (uint256) { return _tokens.length; } /** * @dev Get all bound tokens. */ function getCurrentTokens() external view override _viewlock_ returns (address[] memory tokens) { tokens = _tokens; } /** * @dev Returns the list of tokens which have a desired weight above 0. * Tokens with a desired weight of 0 are set to be phased out of the pool. */ function getCurrentDesiredTokens() external view override _viewlock_ returns (address[] memory tokens) { address[] memory tempTokens = _tokens; tokens = new address[](tempTokens.length); uint256 usedIndex = 0; for (uint256 i = 0; i < tokens.length; i++) { address token = tempTokens[i]; if (_records[token].desiredDenorm > 0) { tokens[usedIndex++] = token; } } assembly { mstore(tokens, usedIndex) } } /** * @dev Returns the denormalized weight of a bound token. */ function getDenormalizedWeight(address token) external view override _viewlock_ returns (uint256/* denorm */) { require(_records[token].bound, "ERR_NOT_BOUND"); return _records[token].denorm; } /** * @dev Returns the record for a token bound to the pool. */ function getTokenRecord(address token) external view override _viewlock_ returns (Record memory record) { record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); } /** * @dev Finds the first token which is both initialized and has a * desired weight above 0, then returns the address of that token * and the extrapolated value of the pool in terms of that token. * * The value is extrapolated by multiplying the token's * balance by the reciprocal of its normalized weight. * @return (token, extrapolatedValue) */ function extrapolatePoolValueFromToken() external view override _viewlock_ returns (address/* token */, uint256/* extrapolatedValue */) { address token; uint256 extrapolatedValue; uint256 len = _tokens.length; for (uint256 i = 0; i < len; i++) { token = _tokens[i]; Record storage record = _records[token]; if (record.ready && record.desiredDenorm > 0) { extrapolatedValue = bmul( record.balance, bdiv(_totalWeight, record.denorm) ); break; } } require(extrapolatedValue > 0, "ERR_NONE_READY"); return (token, extrapolatedValue); } /** * @dev Get the total denormalized weight of the pool. */ function getTotalDenormalizedWeight() external view override _viewlock_ returns (uint256) { return _totalWeight; } /** * @dev Returns the stored balance of a bound token. */ function getBalance(address token) external view override _viewlock_ returns (uint256) { Record storage record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); return record.balance; } /** * @dev Get the minimum balance of an uninitialized token. * Note: Throws if the token is initialized. */ function getMinimumBalance(address token) external view override _viewlock_ returns (uint256) { Record memory record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); require(!record.ready, "ERR_READY"); return _minimumBalances[token]; } /** * @dev Returns the balance of a token which is used in price * calculations. If the token is initialized, this is the * stored balance; if not, this is the minimum balance. */ function getUsedBalance(address token) external view override _viewlock_ returns (uint256) { Record memory record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); if (!record.ready) { return _minimumBalances[token]; } return record.balance; } /* ========== Price Queries ========== */ /** * @dev Returns the spot price for `tokenOut` in terms of `tokenIn`. */ function getSpotPrice(address tokenIn, address tokenOut) external view override _viewlock_ returns (uint256) { (Record memory inRecord,) = _getInputToken(tokenIn); Record memory outRecord = _getOutputToken(tokenOut); return calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); } /* ========== Pool Share Internal Functions ========== */ function _pullPoolShare(address from, uint256 amount) internal { _pull(from, amount); } function _pushPoolShare(address to, uint256 amount) internal { _push(to, amount); } function _mintPoolShare(uint256 amount) internal { _mint(amount); } function _burnPoolShare(uint256 amount) internal { _burn(amount); } /* ========== Underlying Token Internal Functions ========== */ // 'Underlying' token-manipulation functions make external calls but are NOT locked // You must `_lock_` or otherwise ensure reentry-safety function _pullUnderlying( address erc20, address from, uint256 amount ) internal { (bool success, bytes memory data) = erc20.call( abi.encodeWithSelector( IERC20.transferFrom.selector, from, address(this), amount ) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "ERR_ERC20_FALSE" ); } function _pushUnderlying( address erc20, address to, uint256 amount ) internal { (bool success, bytes memory data) = erc20.call( abi.encodeWithSelector( IERC20.transfer.selector, to, amount ) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "ERR_ERC20_FALSE" ); } /* ========== Token Management Internal Functions ========== */ /** * @dev Bind a token by address without actually depositing a balance. * The token will be unable to be swapped out until it reaches the minimum balance. * Note: Token must not already be bound. * Note: `minimumBalance` should represent an amount of the token which is worth * the portion of the current pool value represented by the minimum weight. * @param token Address of the token to bind * @param minimumBalance minimum balance to reach before the token can be swapped out * @param desiredDenorm Desired weight for the token. */ function _bind( address token, uint256 minimumBalance, uint96 desiredDenorm ) internal { require(!_records[token].bound, "ERR_IS_BOUND"); require(desiredDenorm >= MIN_WEIGHT, "ERR_MIN_WEIGHT"); require(desiredDenorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); require(minimumBalance >= MIN_BALANCE, "ERR_MIN_BALANCE"); _records[token] = Record({ bound: true, ready: false, lastDenormUpdate: 0, denorm: 0, desiredDenorm: desiredDenorm, index: uint8(_tokens.length), balance: 0 }); _tokens.push(token); _minimumBalances[token] = minimumBalance; emit LOG_TOKEN_ADDED(token, desiredDenorm, minimumBalance); } /** * @dev Remove a token from the pool. * Replaces the address in the tokens array with the last address, * then removes it from the array. * Note: This should only be called after the total weight has been adjusted. * Note: Must be called in a function with: * - _lock_ modifier to prevent reentrance * - requirement that the token is bound */ function _unbind(address token) internal { Record memory record = _records[token]; uint256 tokenBalance = record.balance; // Swap the token-to-unbind with the last token, // then delete the last token uint256 index = record.index; uint256 last = _tokens.length - 1; // Only swap the token with the last token if it is not // already at the end of the array. if (index != last) { _tokens[index] = _tokens[last]; _records[_tokens[index]].index = uint8(index); } _tokens.pop(); _records[token] = Record({ bound: false, ready: false, lastDenormUpdate: 0, denorm: 0, desiredDenorm: 0, index: 0, balance: 0 }); // transfer any remaining tokens out _pushUnderlying(token, address(_unbindHandler), tokenBalance); _unbindHandler.handleUnbindToken(token, tokenBalance); emit LOG_TOKEN_REMOVED(token); } function _setDesiredDenorm(address token, uint96 desiredDenorm) internal { Record storage record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); // If the desired weight is 0, this will trigger a gradual unbinding of the token. // Therefore the weight only needs to be above the minimum weight if it isn't 0. require( desiredDenorm >= MIN_WEIGHT || desiredDenorm == 0, "ERR_MIN_WEIGHT" ); require(desiredDenorm <= MAX_WEIGHT, "ERR_MAX_WEIGHT"); record.desiredDenorm = desiredDenorm; emit LOG_DESIRED_DENORM_SET(token, desiredDenorm); } function _increaseDenorm(Record memory record, address token) internal { // If the weight does not need to increase or the token is not // initialized, don't do anything. if ( record.denorm >= record.desiredDenorm || !record.ready || now - record.lastDenormUpdate < WEIGHT_UPDATE_DELAY ) return; uint96 oldWeight = record.denorm; uint96 denorm = record.desiredDenorm; uint256 maxDiff = bmul(oldWeight, WEIGHT_CHANGE_PCT); uint256 diff = bsub(denorm, oldWeight); if (diff > maxDiff) { denorm = uint96(badd(oldWeight, maxDiff)); diff = maxDiff; } // If new total weight exceeds the maximum, do not update uint256 newTotalWeight = badd(_totalWeight, diff); if (newTotalWeight > MAX_TOTAL_WEIGHT) return; _totalWeight = newTotalWeight; // Update the in-memory denorm value for spot-price computations. record.denorm = denorm; // Update the storage record _records[token].denorm = denorm; _records[token].lastDenormUpdate = uint40(now); emit LOG_DENORM_UPDATED(token, denorm); } function _decreaseDenorm(Record memory record, address token) internal { // If the weight does not need to decrease, don't do anything. if ( record.denorm <= record.desiredDenorm || !record.ready || now - record.lastDenormUpdate < WEIGHT_UPDATE_DELAY ) return; uint96 oldWeight = record.denorm; uint96 denorm = record.desiredDenorm; uint256 maxDiff = bmul(oldWeight, WEIGHT_CHANGE_PCT); uint256 diff = bsub(oldWeight, denorm); if (diff > maxDiff) { denorm = uint96(bsub(oldWeight, maxDiff)); diff = maxDiff; } if (denorm <= MIN_WEIGHT) { denorm = 0; _totalWeight = bsub(_totalWeight, denorm); // Because this is removing the token from the pool, the // in-memory denorm value is irrelevant, as it is only used // to calculate the new spot price, but the spot price calc // will throw if it is passed 0 for the denorm. _unbind(token); } else { _totalWeight = bsub(_totalWeight, diff); // Update the in-memory denorm value for spot-price computations. record.denorm = denorm; // Update the stored denorm value _records[token].denorm = denorm; _records[token].lastDenormUpdate = uint40(now); emit LOG_DENORM_UPDATED(token, denorm); } } /** * @dev Handles weight changes and initialization of an * input token. * * If the token is not initialized and the new balance is * still below the minimum, this will not do anything. * * If the token is not initialized but the new balance will * bring the token above the minimum balance, this will * mark the token as initialized, remove the minimum * balance and set the weight to the minimum weight plus * 1%. * * * @param token Address of the input token * @param record Token record with minimums applied to the balance * and weight if the token was uninitialized. */ function _updateInputToken( address token, Record memory record, uint256 realBalance ) internal { if (!record.ready) { // Check if the minimum balance has been reached if (realBalance >= record.balance) { // Remove the minimum balance record _minimumBalances[token] = 0; // Mark the token as initialized _records[token].ready = true; record.ready = true; emit LOG_TOKEN_READY(token); // Set the initial denorm value to the minimum weight times one plus // the ratio of the increase in balance over the minimum to the minimum // balance. // weight = (1 + ((bal - min_bal) / min_bal)) * min_weight uint256 additionalBalance = bsub(realBalance, record.balance); uint256 balRatio = bdiv(additionalBalance, record.balance); record.denorm = uint96(badd(MIN_WEIGHT, bmul(MIN_WEIGHT, balRatio))); _records[token].denorm = record.denorm; _records[token].lastDenormUpdate = uint40(now); _totalWeight = badd(_totalWeight, record.denorm); emit LOG_DENORM_UPDATED(token, record.denorm); } else { uint256 realToMinRatio = bdiv( bsub(record.balance, realBalance), record.balance ); uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio); record.denorm = uint96(badd(MIN_WEIGHT, weightPremium)); } // If the token is still not ready, do not adjust the weight. } else { // If the token is already initialized, update the weight (if any adjustment // is needed). _increaseDenorm(record, token); } // Regardless of whether the token is initialized, store the actual new balance. _records[token].balance = realBalance; } /* ========== Token Query Internal Functions ========== */ /** * @dev Get the record for a token which is being swapped in. * The token must be bound to the pool. If the token is not * initialized (meaning it does not have the minimum balance) * this function will return the actual balance of the token * which the pool holds, but set the record's balance and weight * to the token's minimum balance and the pool's minimum weight. * This allows the token swap to be priced correctly even if the * pool does not own any of the tokens. */ function _getInputToken(address token) internal view returns (Record memory record, uint256 realBalance) { record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); realBalance = record.balance; // If the input token is not initialized, we use the minimum // initial weight and minimum initial balance instead of the // real values for price and output calculations. if (!record.ready) { record.balance = _minimumBalances[token]; uint256 realToMinRatio = bdiv( bsub(record.balance, realBalance), record.balance ); uint256 weightPremium = bmul(MIN_WEIGHT / 10, realToMinRatio); record.denorm = uint96(badd(MIN_WEIGHT, weightPremium)); } } function _getOutputToken(address token) internal view returns (Record memory record) { record = _records[token]; require(record.bound, "ERR_NOT_BOUND"); // Tokens which have not reached their minimum balance can not be // swapped out. require(record.ready, "ERR_OUT_NOT_READY"); } }
12,447
5
// True when token URI contract can no longer be changed
bool public tokenURIFrozen;
bool public tokenURIFrozen;
7,875
84
// DOTX lib mainly uses for Chainlink
dotxLibAddress = dotxLibAddr; dotxLib = IDoTxLib(dotxLibAddress); if(setupAddressInLib){ dotxLib.setDoTxGame(address(this)); }
dotxLibAddress = dotxLibAddr; dotxLib = IDoTxLib(dotxLibAddress); if(setupAddressInLib){ dotxLib.setDoTxGame(address(this)); }
12,169
20
// return the balance of the tokens being held. /
function balance() public view returns (uint256) { return _token.balanceOf(address(this)); }
function balance() public view returns (uint256) { return _token.balanceOf(address(this)); }
15,349
70
// Emitted after reward added
event RewardAdded(address indexed rewardToken, uint256 reward, uint256 rewardDuration);
event RewardAdded(address indexed rewardToken, uint256 reward, uint256 rewardDuration);
28,856
3
// solium-disable-next-line security/no-assign-params
function uint2str(uint256 _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); }
function uint2str(uint256 _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); }
30,537
13
// number token we are going to provide in one ethereum
uint256 public tokenPerEth = 5000;
uint256 public tokenPerEth = 5000;
33,363
199
// mark the tokenURI token as minted
mintedTokens[uriHash] = true;
mintedTokens[uriHash] = true;
32,353
126
// StakedToken Contract to stake Roya token, tokenize the position and get rewards, inheriting from a distribution manager contract Roya /
contract StakedToken is IStakedRoya, ERC20WithSnapshot, VersionedInitializable, RoyaDistributionManager { using SafeERC20 for IERC20; uint256 public constant REVISION = 1; IERC20 public immutable STAKED_TOKEN; IERC20 public immutable REWARD_TOKEN; uint256 public immutable COOLDOWN_SECONDS; /// @notice Seconds available to redeem once the cooldown period is fullfilled uint256 public immutable UNSTAKE_WINDOW; /// @notice Address to pull from the rewards, needs to have approved this contract address public immutable REWARDS_VAULT; mapping(address => uint256) public stakerRewardsToClaim; mapping(address => uint256) public stakersCooldowns; event Staked(address indexed from, address indexed onBehalfOf, uint256 amount); event Redeem(address indexed from, address indexed to, uint256 amount); event RewardsAccrued(address user, uint256 amount); event RewardsClaimed(address indexed from, address indexed to, uint256 amount); event Cooldown(address indexed user); constructor( IERC20 stakedToken, IERC20 rewardToken, uint256 cooldownSeconds, uint256 unstakeWindow, address rewardsVault, address emissionManager, uint128 distributionDuration, string memory name, string memory symbol, uint8 decimals ) public ERC20WithSnapshot(name, symbol, decimals) RoyaDistributionManager(emissionManager, distributionDuration) { STAKED_TOKEN = stakedToken; REWARD_TOKEN = rewardToken; COOLDOWN_SECONDS = cooldownSeconds; UNSTAKE_WINDOW = unstakeWindow; REWARDS_VAULT = rewardsVault; } /** * @dev Called by the proxy contract **/ function initialize(ITransferHook royaGovernance, string calldata name, string calldata symbol, uint8 decimals) external initializer { _setName(name); _setSymbol(symbol); _setDecimals(decimals); _setRoyaGovernance(royaGovernance); } function getStakersCooldowns(address user) public view returns(uint256){ uint256 cooldownStartTimestamp = stakersCooldowns[user]; if (block.timestamp < cooldownStartTimestamp.add(COOLDOWN_SECONDS)) return 1; else if (block.timestamp.sub(cooldownStartTimestamp.add(COOLDOWN_SECONDS)) <= UNSTAKE_WINDOW) return 2; else return 0; } function stake(address onBehalfOf, uint256 amount) external override { require(amount != 0, 'INVALID_ZERO_AMOUNT'); uint256 balanceOfUser = balanceOf(onBehalfOf); uint256 accruedRewards = _updateUserAssetInternal( onBehalfOf, address(this), balanceOfUser, totalSupply() ); if (accruedRewards != 0) { emit RewardsAccrued(onBehalfOf, accruedRewards); stakerRewardsToClaim[onBehalfOf] = stakerRewardsToClaim[onBehalfOf].add(accruedRewards); } stakersCooldowns[onBehalfOf] = getNextCooldownTimestamp(0, amount, onBehalfOf, balanceOfUser); _mint(onBehalfOf, amount); IERC20(STAKED_TOKEN).safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, onBehalfOf, amount); } /** * @dev Redeems staked tokens, and stop earning rewards * @param to Address to redeem to * @param amount Amount to redeem **/ function redeem(address to, uint256 amount) external override { require(amount != 0, 'INVALID_ZERO_AMOUNT'); //solium-disable-next-line uint256 cooldownStartTimestamp = stakersCooldowns[msg.sender]; require( block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS), 'INSUFFICIENT_COOLDOWN' ); require( block.timestamp.sub(cooldownStartTimestamp.add(COOLDOWN_SECONDS)) <= UNSTAKE_WINDOW, 'UNSTAKE_WINDOW_FINISHED' ); uint256 balanceOfMessageSender = balanceOf(msg.sender); uint256 amountToRedeem = (amount > balanceOfMessageSender) ? balanceOfMessageSender : amount; _updateCurrentUnclaimedRewards(msg.sender, balanceOfMessageSender, true); _burn(msg.sender, amountToRedeem); if (balanceOfMessageSender.sub(amountToRedeem) == 0) { stakersCooldowns[msg.sender] = 0; } IERC20(STAKED_TOKEN).safeTransfer(to, amountToRedeem); emit Redeem(msg.sender, to, amountToRedeem); } /** * @dev Activates the cooldown period to unstake * - It can't be called if the user is not staking **/ function cooldown() external override { require(balanceOf(msg.sender) != 0, "INVALID_BALANCE_ON_COOLDOWN"); //solium-disable-next-line stakersCooldowns[msg.sender] = block.timestamp; emit Cooldown(msg.sender); } /** * @dev Claims an `amount` of `REWARD_TOKEN` to the address `to` * @param to Address to stake for * @param amount Amount to stake **/ function claimRewards(address to, uint256 amount) external override { uint256 newTotalRewards = _updateCurrentUnclaimedRewards( msg.sender, balanceOf(msg.sender), false ); uint256 amountToClaim = (amount == type(uint256).max) ? newTotalRewards : amount; stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(amountToClaim, "INVALID_AMOUNT"); REWARD_TOKEN.safeTransferFrom(REWARDS_VAULT, to, amountToClaim); emit RewardsClaimed(msg.sender, to, amountToClaim); } /** * @dev Internal ERC20 _transfer of the tokenized staked tokens * @param from Address to transfer from * @param to Address to transfer to * @param amount Amount to transfer **/ function _transfer( address from, address to, uint256 amount ) internal override { uint256 balanceOfFrom = balanceOf(from); // Sender _updateCurrentUnclaimedRewards(from, balanceOfFrom, true); // Recipient if (from != to) { uint256 balanceOfTo = balanceOf(to); _updateCurrentUnclaimedRewards(to, balanceOfTo, true); uint256 previousSenderCooldown = stakersCooldowns[from]; stakersCooldowns[to] = getNextCooldownTimestamp(previousSenderCooldown, amount, to, balanceOfTo); // if cooldown was set and whole balance of sender was transferred - clear cooldown if (balanceOfFrom == amount && previousSenderCooldown != 0) { stakersCooldowns[from] = 0; } } super._transfer(from, to, amount); } /** * @dev Updates the user state related with his accrued rewards * @param user Address of the user * @param userBalance The current balance of the user * @param updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total accrued **/ function _updateCurrentUnclaimedRewards( address user, uint256 userBalance, bool updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal( user, address(this), userBalance, totalSupply() ); uint256 unclaimedRewards = stakerRewardsToClaim[user].add(accruedRewards); if (accruedRewards != 0) { if (updateStorage) { stakerRewardsToClaim[user] = unclaimedRewards; } emit RewardsAccrued(user, accruedRewards); } return unclaimedRewards; } /** * @dev Calculates the how is gonna be a new cooldown timestamp depending on the sender/receiver situation * - If the timestamp of the sender is "better" or the timestamp of the recipient is 0, we take the one of the recipient * - Weighted average of from/to cooldown timestamps if: * # The sender doesn't have the cooldown activated (timestamp 0). * # The sender timestamp is expired * # The sender has a "worse" timestamp * - If the receiver's cooldown timestamp expired (too old), the next is 0 * @param fromCooldownTimestamp Cooldown timestamp of the sender * @param amountToReceive Amount * @param toAddress Address of the recipient * @param toBalance Current balance of the receiver * @return The new cooldown timestamp **/ function getNextCooldownTimestamp( uint256 fromCooldownTimestamp, uint256 amountToReceive, address toAddress, uint256 toBalance ) public view returns (uint256) { uint256 toCooldownTimestamp = stakersCooldowns[toAddress]; if (toCooldownTimestamp == 0) { return 0; } uint256 minimalValidCooldownTimestamp = block.timestamp.sub(COOLDOWN_SECONDS).sub( UNSTAKE_WINDOW ); if (minimalValidCooldownTimestamp > toCooldownTimestamp) { toCooldownTimestamp = 0; } else { uint256 fromCooldownTimestamp = (minimalValidCooldownTimestamp > fromCooldownTimestamp) ? block.timestamp : fromCooldownTimestamp; if (fromCooldownTimestamp < toCooldownTimestamp) { return toCooldownTimestamp; } else { toCooldownTimestamp = ( amountToReceive.mul(fromCooldownTimestamp).add(toBalance.mul(toCooldownTimestamp)) ) .div(amountToReceive.add(toBalance)); } } //stakersCooldowns[toAddress] = toCooldownTimestamp; return toCooldownTimestamp; } /** * @dev Return the total rewards pending to claim by an staker * @param staker The staker address * @return The rewards */ function getTotalRewardsBalance(address staker) external view returns (uint256) { DistributionTypes.UserStakeInput[] memory userStakeInputs = new DistributionTypes.UserStakeInput[](1); userStakeInputs[0] = DistributionTypes.UserStakeInput({ underlyingAsset: address(this), stakedByUser: balanceOf(staker), totalStaked: totalSupply() }); return stakerRewardsToClaim[staker].add(_getUnclaimedRewards(staker, userStakeInputs)); } /** * @dev returns the revision of the implementation contract * @return The revision */ function getRevision() internal override pure returns (uint256) { return REVISION; } }
contract StakedToken is IStakedRoya, ERC20WithSnapshot, VersionedInitializable, RoyaDistributionManager { using SafeERC20 for IERC20; uint256 public constant REVISION = 1; IERC20 public immutable STAKED_TOKEN; IERC20 public immutable REWARD_TOKEN; uint256 public immutable COOLDOWN_SECONDS; /// @notice Seconds available to redeem once the cooldown period is fullfilled uint256 public immutable UNSTAKE_WINDOW; /// @notice Address to pull from the rewards, needs to have approved this contract address public immutable REWARDS_VAULT; mapping(address => uint256) public stakerRewardsToClaim; mapping(address => uint256) public stakersCooldowns; event Staked(address indexed from, address indexed onBehalfOf, uint256 amount); event Redeem(address indexed from, address indexed to, uint256 amount); event RewardsAccrued(address user, uint256 amount); event RewardsClaimed(address indexed from, address indexed to, uint256 amount); event Cooldown(address indexed user); constructor( IERC20 stakedToken, IERC20 rewardToken, uint256 cooldownSeconds, uint256 unstakeWindow, address rewardsVault, address emissionManager, uint128 distributionDuration, string memory name, string memory symbol, uint8 decimals ) public ERC20WithSnapshot(name, symbol, decimals) RoyaDistributionManager(emissionManager, distributionDuration) { STAKED_TOKEN = stakedToken; REWARD_TOKEN = rewardToken; COOLDOWN_SECONDS = cooldownSeconds; UNSTAKE_WINDOW = unstakeWindow; REWARDS_VAULT = rewardsVault; } /** * @dev Called by the proxy contract **/ function initialize(ITransferHook royaGovernance, string calldata name, string calldata symbol, uint8 decimals) external initializer { _setName(name); _setSymbol(symbol); _setDecimals(decimals); _setRoyaGovernance(royaGovernance); } function getStakersCooldowns(address user) public view returns(uint256){ uint256 cooldownStartTimestamp = stakersCooldowns[user]; if (block.timestamp < cooldownStartTimestamp.add(COOLDOWN_SECONDS)) return 1; else if (block.timestamp.sub(cooldownStartTimestamp.add(COOLDOWN_SECONDS)) <= UNSTAKE_WINDOW) return 2; else return 0; } function stake(address onBehalfOf, uint256 amount) external override { require(amount != 0, 'INVALID_ZERO_AMOUNT'); uint256 balanceOfUser = balanceOf(onBehalfOf); uint256 accruedRewards = _updateUserAssetInternal( onBehalfOf, address(this), balanceOfUser, totalSupply() ); if (accruedRewards != 0) { emit RewardsAccrued(onBehalfOf, accruedRewards); stakerRewardsToClaim[onBehalfOf] = stakerRewardsToClaim[onBehalfOf].add(accruedRewards); } stakersCooldowns[onBehalfOf] = getNextCooldownTimestamp(0, amount, onBehalfOf, balanceOfUser); _mint(onBehalfOf, amount); IERC20(STAKED_TOKEN).safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, onBehalfOf, amount); } /** * @dev Redeems staked tokens, and stop earning rewards * @param to Address to redeem to * @param amount Amount to redeem **/ function redeem(address to, uint256 amount) external override { require(amount != 0, 'INVALID_ZERO_AMOUNT'); //solium-disable-next-line uint256 cooldownStartTimestamp = stakersCooldowns[msg.sender]; require( block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS), 'INSUFFICIENT_COOLDOWN' ); require( block.timestamp.sub(cooldownStartTimestamp.add(COOLDOWN_SECONDS)) <= UNSTAKE_WINDOW, 'UNSTAKE_WINDOW_FINISHED' ); uint256 balanceOfMessageSender = balanceOf(msg.sender); uint256 amountToRedeem = (amount > balanceOfMessageSender) ? balanceOfMessageSender : amount; _updateCurrentUnclaimedRewards(msg.sender, balanceOfMessageSender, true); _burn(msg.sender, amountToRedeem); if (balanceOfMessageSender.sub(amountToRedeem) == 0) { stakersCooldowns[msg.sender] = 0; } IERC20(STAKED_TOKEN).safeTransfer(to, amountToRedeem); emit Redeem(msg.sender, to, amountToRedeem); } /** * @dev Activates the cooldown period to unstake * - It can't be called if the user is not staking **/ function cooldown() external override { require(balanceOf(msg.sender) != 0, "INVALID_BALANCE_ON_COOLDOWN"); //solium-disable-next-line stakersCooldowns[msg.sender] = block.timestamp; emit Cooldown(msg.sender); } /** * @dev Claims an `amount` of `REWARD_TOKEN` to the address `to` * @param to Address to stake for * @param amount Amount to stake **/ function claimRewards(address to, uint256 amount) external override { uint256 newTotalRewards = _updateCurrentUnclaimedRewards( msg.sender, balanceOf(msg.sender), false ); uint256 amountToClaim = (amount == type(uint256).max) ? newTotalRewards : amount; stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(amountToClaim, "INVALID_AMOUNT"); REWARD_TOKEN.safeTransferFrom(REWARDS_VAULT, to, amountToClaim); emit RewardsClaimed(msg.sender, to, amountToClaim); } /** * @dev Internal ERC20 _transfer of the tokenized staked tokens * @param from Address to transfer from * @param to Address to transfer to * @param amount Amount to transfer **/ function _transfer( address from, address to, uint256 amount ) internal override { uint256 balanceOfFrom = balanceOf(from); // Sender _updateCurrentUnclaimedRewards(from, balanceOfFrom, true); // Recipient if (from != to) { uint256 balanceOfTo = balanceOf(to); _updateCurrentUnclaimedRewards(to, balanceOfTo, true); uint256 previousSenderCooldown = stakersCooldowns[from]; stakersCooldowns[to] = getNextCooldownTimestamp(previousSenderCooldown, amount, to, balanceOfTo); // if cooldown was set and whole balance of sender was transferred - clear cooldown if (balanceOfFrom == amount && previousSenderCooldown != 0) { stakersCooldowns[from] = 0; } } super._transfer(from, to, amount); } /** * @dev Updates the user state related with his accrued rewards * @param user Address of the user * @param userBalance The current balance of the user * @param updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total accrued **/ function _updateCurrentUnclaimedRewards( address user, uint256 userBalance, bool updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal( user, address(this), userBalance, totalSupply() ); uint256 unclaimedRewards = stakerRewardsToClaim[user].add(accruedRewards); if (accruedRewards != 0) { if (updateStorage) { stakerRewardsToClaim[user] = unclaimedRewards; } emit RewardsAccrued(user, accruedRewards); } return unclaimedRewards; } /** * @dev Calculates the how is gonna be a new cooldown timestamp depending on the sender/receiver situation * - If the timestamp of the sender is "better" or the timestamp of the recipient is 0, we take the one of the recipient * - Weighted average of from/to cooldown timestamps if: * # The sender doesn't have the cooldown activated (timestamp 0). * # The sender timestamp is expired * # The sender has a "worse" timestamp * - If the receiver's cooldown timestamp expired (too old), the next is 0 * @param fromCooldownTimestamp Cooldown timestamp of the sender * @param amountToReceive Amount * @param toAddress Address of the recipient * @param toBalance Current balance of the receiver * @return The new cooldown timestamp **/ function getNextCooldownTimestamp( uint256 fromCooldownTimestamp, uint256 amountToReceive, address toAddress, uint256 toBalance ) public view returns (uint256) { uint256 toCooldownTimestamp = stakersCooldowns[toAddress]; if (toCooldownTimestamp == 0) { return 0; } uint256 minimalValidCooldownTimestamp = block.timestamp.sub(COOLDOWN_SECONDS).sub( UNSTAKE_WINDOW ); if (minimalValidCooldownTimestamp > toCooldownTimestamp) { toCooldownTimestamp = 0; } else { uint256 fromCooldownTimestamp = (minimalValidCooldownTimestamp > fromCooldownTimestamp) ? block.timestamp : fromCooldownTimestamp; if (fromCooldownTimestamp < toCooldownTimestamp) { return toCooldownTimestamp; } else { toCooldownTimestamp = ( amountToReceive.mul(fromCooldownTimestamp).add(toBalance.mul(toCooldownTimestamp)) ) .div(amountToReceive.add(toBalance)); } } //stakersCooldowns[toAddress] = toCooldownTimestamp; return toCooldownTimestamp; } /** * @dev Return the total rewards pending to claim by an staker * @param staker The staker address * @return The rewards */ function getTotalRewardsBalance(address staker) external view returns (uint256) { DistributionTypes.UserStakeInput[] memory userStakeInputs = new DistributionTypes.UserStakeInput[](1); userStakeInputs[0] = DistributionTypes.UserStakeInput({ underlyingAsset: address(this), stakedByUser: balanceOf(staker), totalStaked: totalSupply() }); return stakerRewardsToClaim[staker].add(_getUnclaimedRewards(staker, userStakeInputs)); } /** * @dev returns the revision of the implementation contract * @return The revision */ function getRevision() internal override pure returns (uint256) { return REVISION; } }
24,990
156
// - extract Merkle root field from a raw Dogecoin block header_blockHeader - Dogecoin block header bytespos - where to start reading root from return - block's Merkle root in big endian format
function getHeaderMerkleRoot(bytes memory _blockHeader, uint pos) public pure returns (uint) { uint merkle; assembly { merkle := mload(add(add(_blockHeader, 0x44), pos)) } return flip32Bytes(merkle); }
function getHeaderMerkleRoot(bytes memory _blockHeader, uint pos) public pure returns (uint) { uint merkle; assembly { merkle := mload(add(add(_blockHeader, 0x44), pos)) } return flip32Bytes(merkle); }
38,127
17
// allow the seller to send funds in the offer they may also send funds directly to the contract (fallback function)
self.accountLib.depositToSeller();
self.accountLib.depositToSeller();
37,937
32
// DAAContract, TicketContract, CitizenContract
function joinNetwork(address[3] _contract) public
function joinNetwork(address[3] _contract) public
10,316
41
// welp you are here now, only have high card? boring
output[0]=1; currcard=1; for (i=13;i>=1;i--){ if (CardTracker[i]>0){ output[currcard]=i; currcard++; if (currcard==6){ return output; }
output[0]=1; currcard=1; for (i=13;i>=1;i--){ if (CardTracker[i]>0){ output[currcard]=i; currcard++; if (currcard==6){ return output; }
42,979
22
// Update the rewards of caller, and harvests if needed
function _updateUserReward(uint256 _pid, bool _shouldHarvest) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount == 0) { user.lastPawPerShare = pool.accPawPerShare; } uint256 pending = user.amount.mul(pool.accPawPerShare.sub(user.lastPawPerShare)).div(1e18).add(user.unclaimed); user.unclaimed = _shouldHarvest ? 0 : pending; if (_shouldHarvest && pending > 0) { _lockReward(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); } user.lastPawPerShare = pool.accPawPerShare; }
function _updateUserReward(uint256 _pid, bool _shouldHarvest) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount == 0) { user.lastPawPerShare = pool.accPawPerShare; } uint256 pending = user.amount.mul(pool.accPawPerShare.sub(user.lastPawPerShare)).div(1e18).add(user.unclaimed); user.unclaimed = _shouldHarvest ? 0 : pending; if (_shouldHarvest && pending > 0) { _lockReward(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); } user.lastPawPerShare = pool.accPawPerShare; }
12,974
35
// ´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.:// READ LOGIC //.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•//Returns all the `data` from the bytecode of the storage contract at `pointer`.
function read(address pointer) internal view returns (bytes memory data) { /// @solidity memory-safe-assembly assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { // Store the function selector of `InvalidPointer()`. mstore(0x00, 0x11052bb4) // Revert with (offset, size). revert(0x1c, 0x04) } // Offset all indices by 1 to skip the STOP opcode. let size := sub(pointerCodesize, DATA_OFFSET) // Get the pointer to the free memory and allocate // enough 32-byte words for the data and the length of the data, // then copy the code to the allocated memory. // Masking with 0xffe0 will suffice, since contract size is less than 16 bits. data := mload(0x40) mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) mstore(add(add(data, 0x20), size), 0) // Zeroize the last slot. extcodecopy(pointer, add(data, 0x20), DATA_OFFSET, size) } }
function read(address pointer) internal view returns (bytes memory data) { /// @solidity memory-safe-assembly assembly { let pointerCodesize := extcodesize(pointer) if iszero(pointerCodesize) { // Store the function selector of `InvalidPointer()`. mstore(0x00, 0x11052bb4) // Revert with (offset, size). revert(0x1c, 0x04) } // Offset all indices by 1 to skip the STOP opcode. let size := sub(pointerCodesize, DATA_OFFSET) // Get the pointer to the free memory and allocate // enough 32-byte words for the data and the length of the data, // then copy the code to the allocated memory. // Masking with 0xffe0 will suffice, since contract size is less than 16 bits. data := mload(0x40) mstore(0x40, add(data, and(add(size, 0x3f), 0xffe0))) mstore(data, size) mstore(add(add(data, 0x20), size), 0) // Zeroize the last slot. extcodecopy(pointer, add(data, 0x20), DATA_OFFSET, size) } }
40,995
65
// Constant flow agreement v1 library Superfluid for working with the constant flow agreement within solidity the first set of functions are each for callAgreement() the second set of functions are each for use in callAgreementWithContext() /
library CFAv1Library { /** * @dev Initialization data * @param host Superfluid host for calling agreements * @param cfa Constant Flow Agreement contract */ struct InitData { ISuperfluid host; IConstantFlowAgreementV1 cfa; } /** * @dev Create flow without userData * @param cfaLibrary The cfaLibrary storage variable * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function createFlow( InitData storage cfaLibrary, address receiver, ISuperfluidToken token, int96 flowRate ) internal { createFlow(cfaLibrary, receiver, token, flowRate, new bytes(0)); } /** * @dev Create flow with userData * @param cfaLibrary The cfaLibrary storage variable * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function createFlow( InitData storage cfaLibrary, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal { cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.createFlow, ( token, receiver, flowRate, new bytes(0) // placeholder ) ), userData ); } /** * @dev Update flow without userData * @param cfaLibrary The cfaLibrary storage variable * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function updateFlow( InitData storage cfaLibrary, address receiver, ISuperfluidToken token, int96 flowRate ) internal { updateFlow(cfaLibrary, receiver, token, flowRate, new bytes(0)); } /** * @dev Update flow with userData * @param cfaLibrary The cfaLibrary storage variable * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function updateFlow( InitData storage cfaLibrary, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal { cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlow, ( token, receiver, flowRate, new bytes(0) // placeholder ) ), userData ); } /** * @dev Delete flow without userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow */ function deleteFlow( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token ) internal { deleteFlow(cfaLibrary, sender, receiver, token, new bytes(0)); } /** * @dev Delete flow with userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param userData The user provided data */ function deleteFlow( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, bytes memory userData ) internal { cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.deleteFlow, ( token, sender, receiver, new bytes(0) // placeholder ) ), userData ); } /** * @dev Create flow with context and userData * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function createFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return createFlowWithCtx(cfaLibrary, ctx, receiver, token, flowRate, new bytes(0)); } /** * @dev Create flow with context and userData * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function createFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.createFlow, ( token, receiver, flowRate, new bytes(0) // placeholder ) ), userData, ctx ); } /** * @dev Update flow with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function updateFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return updateFlowWithCtx(cfaLibrary, ctx, receiver, token, flowRate, new bytes(0)); } /** * @dev Update flow with context and userData * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function updateFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlow, ( token, receiver, flowRate, new bytes(0) // placeholder ) ), userData, ctx ); } /** * @dev Delete flow with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow */ function deleteFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token ) internal returns (bytes memory newCtx) { return deleteFlowWithCtx(cfaLibrary, ctx, sender, receiver, token, new bytes(0)); } /** * @dev Delete flow with context and userData * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param userData The user provided data */ function deleteFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.deleteFlow, ( token, sender, receiver, new bytes(0) // placeholder ) ), userData, ctx ); } /** * @dev Creates flow as an operator without userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function createFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return createFlowByOperator(cfaLibrary, sender, receiver, token, flowRate, new bytes(0)); } /** * @dev Creates flow as an operator with userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function createFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.createFlowByOperator, ( token, sender, receiver, flowRate, new bytes(0) // placeholder ) ), userData ); } /** * @dev Creates flow as an operator without userData with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function createFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return createFlowByOperatorWithCtx( cfaLibrary, ctx, sender, receiver, token, flowRate, new bytes(0) ); } /** * @dev Creates flow as an operator with userData and context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function createFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.createFlowByOperator, ( token, sender, receiver, flowRate, new bytes(0) // placeholder ) ), userData, ctx ); } /** * @dev Updates a flow as an operator without userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function updateFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return updateFlowByOperator(cfaLibrary, sender, receiver, token, flowRate, new bytes(0)); } /** * @dev Updates flow as an operator with userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function updateFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlowByOperator, ( token, sender, receiver, flowRate, new bytes(0) ) ), userData ); } /** * @dev Updates a flow as an operator without userData with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function updateFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return updateFlowByOperatorWithCtx( cfaLibrary, ctx, sender, receiver, token, flowRate, new bytes(0) ); } /** * @dev Updates flow as an operator with userData and context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function updateFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlowByOperator, ( token, sender, receiver, flowRate, new bytes(0) ) ), userData, ctx ); } /** * @dev Deletes a flow as an operator without userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow */ function deleteFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token ) internal returns (bytes memory newCtx) { return deleteFlowByOperator(cfaLibrary, sender, receiver, token, new bytes(0)); } /** * @dev Deletes a flow as an operator with userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param userData The user provided data */ function deleteFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, bytes memory userData ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.deleteFlowByOperator, ( token, sender, receiver, new bytes(0) ) ), userData ); } /** * @dev Deletes a flow as an operator without userData with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow */ function deleteFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token ) internal returns (bytes memory newCtx) { return deleteFlowByOperatorWithCtx(cfaLibrary, ctx, sender, receiver, token, new bytes(0)); } /** * @dev Deletes a flow as an operator with userData and context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param userData The user provided data */ function deleteFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.deleteFlowByOperator, ( token, sender, receiver, new bytes(0) ) ), userData, ctx ); } /** * @dev Updates the permissions of a flow operator * @param cfaLibrary The cfaLibrary storage variable * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator * @param permissions The number of the permissions: create = 1; update = 2; delete = 4; * To give multiple permissions, sum the above. create_delete = 5; create_update_delete = 7; etc * @param flowRateAllowance The allowance for flow creation. Decremented as flowRate increases */ function updateFlowOperatorPermissions( InitData storage cfaLibrary, address flowOperator, ISuperfluidToken token, uint8 permissions, int96 flowRateAllowance ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlowOperatorPermissions, ( token, flowOperator, permissions, flowRateAllowance, new bytes(0) ) ), new bytes(0) ); } /** * @dev Updates the permissions of a flow operator with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator * @param permissions The number of the permissions: create = 1; update = 2; delete = 4; * To give multiple permissions, sum the above. create_delete = 5; create_update_delete = 7; etc * @param flowRateAllowance The allowance for flow creation. Decremented as flowRate increases */ function updateFlowOperatorPermissionsWithCtx( InitData storage cfaLibrary, bytes memory ctx, address flowOperator, ISuperfluidToken token, uint8 permissions, int96 flowRateAllowance ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlowOperatorPermissions, ( token, flowOperator, permissions, flowRateAllowance, new bytes(0) ) ), new bytes(0), ctx ); } /** * @dev Grants full, unlimited permission to a flow operator * @param cfaLibrary The cfaLibrary storage variable * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator */ function authorizeFlowOperatorWithFullControl( InitData storage cfaLibrary, address flowOperator, ISuperfluidToken token ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.authorizeFlowOperatorWithFullControl, ( token, flowOperator, new bytes(0) ) ), new bytes(0) ); } /** * @dev Grants full, unlimited permission to a flow operator with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator */ function authorizeFlowOperatorWithFullControlWithCtx( InitData storage cfaLibrary, bytes memory ctx, address flowOperator, ISuperfluidToken token ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.authorizeFlowOperatorWithFullControl, ( token, flowOperator, new bytes(0) ) ), new bytes(0), ctx ); } /** * @dev Revokes all permissions from a flow operator * @param cfaLibrary The cfaLibrary storage variable * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator */ function revokeFlowOperatorWithFullControl( InitData storage cfaLibrary, address flowOperator, ISuperfluidToken token ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.revokeFlowOperatorWithFullControl, ( token, flowOperator, new bytes(0) ) ), new bytes(0) ); } /** * @dev Revokes all permissions from a flow operator * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator */ function revokeFlowOperatorWithFullControlWithCtx( InitData storage cfaLibrary, bytes memory ctx, address flowOperator, ISuperfluidToken token ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.revokeFlowOperatorWithFullControl, ( token, flowOperator, new bytes(0) ) ), new bytes(0), ctx ); } }
library CFAv1Library { /** * @dev Initialization data * @param host Superfluid host for calling agreements * @param cfa Constant Flow Agreement contract */ struct InitData { ISuperfluid host; IConstantFlowAgreementV1 cfa; } /** * @dev Create flow without userData * @param cfaLibrary The cfaLibrary storage variable * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function createFlow( InitData storage cfaLibrary, address receiver, ISuperfluidToken token, int96 flowRate ) internal { createFlow(cfaLibrary, receiver, token, flowRate, new bytes(0)); } /** * @dev Create flow with userData * @param cfaLibrary The cfaLibrary storage variable * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function createFlow( InitData storage cfaLibrary, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal { cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.createFlow, ( token, receiver, flowRate, new bytes(0) // placeholder ) ), userData ); } /** * @dev Update flow without userData * @param cfaLibrary The cfaLibrary storage variable * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function updateFlow( InitData storage cfaLibrary, address receiver, ISuperfluidToken token, int96 flowRate ) internal { updateFlow(cfaLibrary, receiver, token, flowRate, new bytes(0)); } /** * @dev Update flow with userData * @param cfaLibrary The cfaLibrary storage variable * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function updateFlow( InitData storage cfaLibrary, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal { cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlow, ( token, receiver, flowRate, new bytes(0) // placeholder ) ), userData ); } /** * @dev Delete flow without userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow */ function deleteFlow( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token ) internal { deleteFlow(cfaLibrary, sender, receiver, token, new bytes(0)); } /** * @dev Delete flow with userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param userData The user provided data */ function deleteFlow( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, bytes memory userData ) internal { cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.deleteFlow, ( token, sender, receiver, new bytes(0) // placeholder ) ), userData ); } /** * @dev Create flow with context and userData * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function createFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return createFlowWithCtx(cfaLibrary, ctx, receiver, token, flowRate, new bytes(0)); } /** * @dev Create flow with context and userData * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function createFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.createFlow, ( token, receiver, flowRate, new bytes(0) // placeholder ) ), userData, ctx ); } /** * @dev Update flow with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function updateFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return updateFlowWithCtx(cfaLibrary, ctx, receiver, token, flowRate, new bytes(0)); } /** * @dev Update flow with context and userData * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function updateFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlow, ( token, receiver, flowRate, new bytes(0) // placeholder ) ), userData, ctx ); } /** * @dev Delete flow with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow */ function deleteFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token ) internal returns (bytes memory newCtx) { return deleteFlowWithCtx(cfaLibrary, ctx, sender, receiver, token, new bytes(0)); } /** * @dev Delete flow with context and userData * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param userData The user provided data */ function deleteFlowWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.deleteFlow, ( token, sender, receiver, new bytes(0) // placeholder ) ), userData, ctx ); } /** * @dev Creates flow as an operator without userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function createFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return createFlowByOperator(cfaLibrary, sender, receiver, token, flowRate, new bytes(0)); } /** * @dev Creates flow as an operator with userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function createFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.createFlowByOperator, ( token, sender, receiver, flowRate, new bytes(0) // placeholder ) ), userData ); } /** * @dev Creates flow as an operator without userData with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function createFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return createFlowByOperatorWithCtx( cfaLibrary, ctx, sender, receiver, token, flowRate, new bytes(0) ); } /** * @dev Creates flow as an operator with userData and context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function createFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.createFlowByOperator, ( token, sender, receiver, flowRate, new bytes(0) // placeholder ) ), userData, ctx ); } /** * @dev Updates a flow as an operator without userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function updateFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return updateFlowByOperator(cfaLibrary, sender, receiver, token, flowRate, new bytes(0)); } /** * @dev Updates flow as an operator with userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function updateFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlowByOperator, ( token, sender, receiver, flowRate, new bytes(0) ) ), userData ); } /** * @dev Updates a flow as an operator without userData with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate */ function updateFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, int96 flowRate ) internal returns (bytes memory newCtx) { return updateFlowByOperatorWithCtx( cfaLibrary, ctx, sender, receiver, token, flowRate, new bytes(0) ); } /** * @dev Updates flow as an operator with userData and context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param flowRate The desired flowRate * @param userData The user provided data */ function updateFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, int96 flowRate, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlowByOperator, ( token, sender, receiver, flowRate, new bytes(0) ) ), userData, ctx ); } /** * @dev Deletes a flow as an operator without userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow */ function deleteFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token ) internal returns (bytes memory newCtx) { return deleteFlowByOperator(cfaLibrary, sender, receiver, token, new bytes(0)); } /** * @dev Deletes a flow as an operator with userData * @param cfaLibrary The cfaLibrary storage variable * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param userData The user provided data */ function deleteFlowByOperator( InitData storage cfaLibrary, address sender, address receiver, ISuperfluidToken token, bytes memory userData ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.deleteFlowByOperator, ( token, sender, receiver, new bytes(0) ) ), userData ); } /** * @dev Deletes a flow as an operator without userData with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow */ function deleteFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token ) internal returns (bytes memory newCtx) { return deleteFlowByOperatorWithCtx(cfaLibrary, ctx, sender, receiver, token, new bytes(0)); } /** * @dev Deletes a flow as an operator with userData and context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param sender The sender of the flow * @param receiver The receiver of the flow * @param token The token to flow * @param userData The user provided data */ function deleteFlowByOperatorWithCtx( InitData storage cfaLibrary, bytes memory ctx, address sender, address receiver, ISuperfluidToken token, bytes memory userData ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.deleteFlowByOperator, ( token, sender, receiver, new bytes(0) ) ), userData, ctx ); } /** * @dev Updates the permissions of a flow operator * @param cfaLibrary The cfaLibrary storage variable * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator * @param permissions The number of the permissions: create = 1; update = 2; delete = 4; * To give multiple permissions, sum the above. create_delete = 5; create_update_delete = 7; etc * @param flowRateAllowance The allowance for flow creation. Decremented as flowRate increases */ function updateFlowOperatorPermissions( InitData storage cfaLibrary, address flowOperator, ISuperfluidToken token, uint8 permissions, int96 flowRateAllowance ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlowOperatorPermissions, ( token, flowOperator, permissions, flowRateAllowance, new bytes(0) ) ), new bytes(0) ); } /** * @dev Updates the permissions of a flow operator with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator * @param permissions The number of the permissions: create = 1; update = 2; delete = 4; * To give multiple permissions, sum the above. create_delete = 5; create_update_delete = 7; etc * @param flowRateAllowance The allowance for flow creation. Decremented as flowRate increases */ function updateFlowOperatorPermissionsWithCtx( InitData storage cfaLibrary, bytes memory ctx, address flowOperator, ISuperfluidToken token, uint8 permissions, int96 flowRateAllowance ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.updateFlowOperatorPermissions, ( token, flowOperator, permissions, flowRateAllowance, new bytes(0) ) ), new bytes(0), ctx ); } /** * @dev Grants full, unlimited permission to a flow operator * @param cfaLibrary The cfaLibrary storage variable * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator */ function authorizeFlowOperatorWithFullControl( InitData storage cfaLibrary, address flowOperator, ISuperfluidToken token ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.authorizeFlowOperatorWithFullControl, ( token, flowOperator, new bytes(0) ) ), new bytes(0) ); } /** * @dev Grants full, unlimited permission to a flow operator with context * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator */ function authorizeFlowOperatorWithFullControlWithCtx( InitData storage cfaLibrary, bytes memory ctx, address flowOperator, ISuperfluidToken token ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.authorizeFlowOperatorWithFullControl, ( token, flowOperator, new bytes(0) ) ), new bytes(0), ctx ); } /** * @dev Revokes all permissions from a flow operator * @param cfaLibrary The cfaLibrary storage variable * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator */ function revokeFlowOperatorWithFullControl( InitData storage cfaLibrary, address flowOperator, ISuperfluidToken token ) internal returns (bytes memory newCtx) { return cfaLibrary.host.callAgreement( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.revokeFlowOperatorWithFullControl, ( token, flowOperator, new bytes(0) ) ), new bytes(0) ); } /** * @dev Revokes all permissions from a flow operator * @param cfaLibrary The cfaLibrary storage variable * @param ctx Context bytes (see ISuperfluid.sol for Context struct) * @param flowOperator The operator that can create/update/delete flows * @param token The token of flows handled by the operator */ function revokeFlowOperatorWithFullControlWithCtx( InitData storage cfaLibrary, bytes memory ctx, address flowOperator, ISuperfluidToken token ) internal returns (bytes memory newCtx) { (newCtx, ) = cfaLibrary.host.callAgreementWithContext( cfaLibrary.cfa, abi.encodeCall( cfaLibrary.cfa.revokeFlowOperatorWithFullControl, ( token, flowOperator, new bytes(0) ) ), new bytes(0), ctx ); } }
23,074
20
// The refundCompleted function updates the campaign status after the refunds are processed.If the reason is "DELETED", the campaign status is set to "DELETED".If the reason is "REVERTING", the campaign status is updated based on the remaining active backers. _id The ID of the campaign. _reason The reason for the refund ("DELETED" or "REVERTING"). /
function refundCompleted(uint _id, string memory _reason) internal { if (keccak256(bytes(_reason)) == keccak256(bytes("DELETED"))) { campaigns[_id].campaignStatus = campaignStatusEnum.DELETED; numberOfCampaignsExcludeRefund -= 1; // dời ra ngoài vì sau khi refund hết backers của 1 campaign mới xóa campaign khỏi ds } else if (keccak256(bytes(_reason)) == keccak256(bytes("REVERTING"))) { // kiểm xem rút hết chưa? if (campaigns[_id].activeDonating > 0) { if (campaigns[_id].campaignStatus == campaignStatusEnum.OPEN) { campaigns[_id].campaignStatus = campaignStatusEnum .REVERTING; } } else { campaigns[_id].campaignStatus = campaignStatusEnum.REVERTED; // point when all backers withdrew } } }
function refundCompleted(uint _id, string memory _reason) internal { if (keccak256(bytes(_reason)) == keccak256(bytes("DELETED"))) { campaigns[_id].campaignStatus = campaignStatusEnum.DELETED; numberOfCampaignsExcludeRefund -= 1; // dời ra ngoài vì sau khi refund hết backers của 1 campaign mới xóa campaign khỏi ds } else if (keccak256(bytes(_reason)) == keccak256(bytes("REVERTING"))) { // kiểm xem rút hết chưa? if (campaigns[_id].activeDonating > 0) { if (campaigns[_id].campaignStatus == campaignStatusEnum.OPEN) { campaigns[_id].campaignStatus = campaignStatusEnum .REVERTING; } } else { campaigns[_id].campaignStatus = campaignStatusEnum.REVERTED; // point when all backers withdrew } } }
23,009
29
// Confirm new address is signed by current address
bytes32 _currentAddressDigest = signingLogic.generateAddAddressSchemaHash(_newAddress, _nonce); require(_sender == signingLogic.recoverSigner(_currentAddressDigest, _senderSig));
bytes32 _currentAddressDigest = signingLogic.generateAddAddressSchemaHash(_newAddress, _nonce); require(_sender == signingLogic.recoverSigner(_currentAddressDigest, _senderSig));
12,301
1
// The OpenSea operator filter registry.
address internal constant _OPERATOR_FILTER_REGISTRY = 0x000000000000AAeB6D7670E522A718067333cd4E;
address internal constant _OPERATOR_FILTER_REGISTRY = 0x000000000000AAeB6D7670E522A718067333cd4E;
22,366
38
// Player has won their wager back
profit = spin.tokenValue; emit ReturnBet(target);
profit = spin.tokenValue; emit ReturnBet(target);
8,948
1
// Address of the accepted token for ReplyTicket payment (i.e. ReplyCoin)
address _tokenContract;
address _tokenContract;
7,319
3
// Transfers ownership of the contract to a new account (`newOwner`). This caninclude renouncing ownership by transferring to the zero address.Can only be called by the current owner. /
function transferOwnership(address newOwner) external;
function transferOwnership(address newOwner) external;
29,928
8
// Modifier allows functions calls only when contract is not initialized. /
modifier whenNotInitialized() { require(!initialized, "Nexus is already initialized"); _; }
modifier whenNotInitialized() { require(!initialized, "Nexus is already initialized"); _; }
31,923
72
// Originating wallet for yield payments
address internal yieldWallet;
address internal yieldWallet;
36,356
19
// Get the number of available Noun `glasses`. /
function glassesCount() external view override returns (uint256) { return art.getGlassesTrait().storedImagesCount; }
function glassesCount() external view override returns (uint256) { return art.getGlassesTrait().storedImagesCount; }
39,381
212
// encode data for FL
bytes memory recipeData = abi.encode(_currRecipe, address(this)); IFlashLoanBase.FlashLoanParams memory params = abi.decode( _currRecipe.callData[0], (IFlashLoanBase.FlashLoanParams) ); params.recipeData = recipeData; _currRecipe.callData[0] = abi.encode(params);
bytes memory recipeData = abi.encode(_currRecipe, address(this)); IFlashLoanBase.FlashLoanParams memory params = abi.decode( _currRecipe.callData[0], (IFlashLoanBase.FlashLoanParams) ); params.recipeData = recipeData; _currRecipe.callData[0] = abi.encode(params);
12,438
3
// requestVolumeData(rand_a, rand_b);
qlist[Qcount].title=coinlist[rand_a].title; qlist[Qcount].story=coinlist[rand_a].story; qlist[Qcount].question=Qtopic[rand_b]; qlist[Qcount].revealTime=now; qlist[Qcount].lifeLength=7; qlist[Qcount].property="Crypto";
qlist[Qcount].title=coinlist[rand_a].title; qlist[Qcount].story=coinlist[rand_a].story; qlist[Qcount].question=Qtopic[rand_b]; qlist[Qcount].revealTime=now; qlist[Qcount].lifeLength=7; qlist[Qcount].property="Crypto";
14,001
198
// Return job info _jobId Job identifier /
function getJob( uint256 _jobId ) public view returns (string streamId, string transcodingOptions, uint256 maxPricePerSegment, address broadcasterAddress, address transcoderAddress, uint256 creationRound, uint256 creationBlock, uint256 endBlock, uint256 escrow, uint256 totalClaims)
function getJob( uint256 _jobId ) public view returns (string streamId, string transcodingOptions, uint256 maxPricePerSegment, address broadcasterAddress, address transcoderAddress, uint256 creationRound, uint256 creationBlock, uint256 endBlock, uint256 escrow, uint256 totalClaims)
50,919
30
// already joined
return Error.NO_ERROR;
return Error.NO_ERROR;
16,353
24
// All Aave math performed in RAY (1e27).
return liquidityRate / 1e9;
return liquidityRate / 1e9;
29,681
168
// Add
uint256 id = authorizedContractList.push(false); authorizedContractIds[_contract] = id; authorizedContracts[id] = AuthorizedContract(_name, _contract);
uint256 id = authorizedContractList.push(false); authorizedContractIds[_contract] = id; authorizedContracts[id] = AuthorizedContract(_name, _contract);
68,095
103
// If you somehow manage to free yourself from that Rat Trap, you may go on living.
function removeRatTrap(address account) public onlyOwner { inRatTrap[account] = false; emit RatReleased(account); }
function removeRatTrap(address account) public onlyOwner { inRatTrap[account] = false; emit RatReleased(account); }
39,615
30
// Note that this pool has no minter key of BpEUR (rewards). Instead, the governance will call BpEUR distributeReward method and send reward to this pool at the beginning.
contract bpEURRewardPool { using SafeMath for uint256; using SafeERC20 for IERC20; // governance address public operator; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. bpEURs to distribute per block. uint256 lastRewardBlock; // Last block number that bpEURs distribution occurs. uint256 accBpEurPerShare; // Accumulated bpEURs per share, times 1e18. See below. bool isStarted; // if lastRewardBlock has passed } IERC20 public bpeur = IERC20(0x0000000000000000000000000000000000000000); // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BpEUR mining starts. uint256 public startBlock; uint256 public constant BLOCKS_PER_DAY = 28800; // Day 1 to day 5: 20,000 bpeur daily // Day 6 to day 26: 5,000 bpeur daily // Day 27 to day 180: 1,000 daily uint256[] public epochTotalRewards = [100000 ether, 105000 ether, 154000 ether]; // Block number when each epoch ends. uint[3] public epochEndBlocks; // Reward per block for each of 3 epochs (last item is equal to 0 - for sanity). uint[4] public epochBpEURPerBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event RewardPaid(address indexed user, uint256 amount); constructor( address _bpEUR, uint256 _startBlock ) public { require(block.number < _startBlock, "late"); if (_bpEUR != address(0)) bpeur = IERC20(_bpEUR); startBlock = _startBlock; // supposed to be 6180000 (Thu Apr 01 2021 05:30:00 GMT+0) epochEndBlocks[0] = startBlock + BLOCKS_PER_DAY * 5; epochBpEURPerBlock[0] = epochTotalRewards[0].div(BLOCKS_PER_DAY * 5); epochEndBlocks[1] = epochEndBlocks[0] + BLOCKS_PER_DAY * 21; epochBpEURPerBlock[1] = epochTotalRewards[1].div(BLOCKS_PER_DAY * 21); epochEndBlocks[2] = epochEndBlocks[1] + BLOCKS_PER_DAY * 154; epochBpEURPerBlock[2] = epochTotalRewards[1].div(BLOCKS_PER_DAY * 154); epochBpEURPerBlock[3] = 0; operator = msg.sender; } modifier onlyOperator() { require(operator == msg.sender, "bpEURRewardPool: caller is not the operator"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } function checkPoolDuplicate(IERC20 _lpToken) internal view { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _lpToken, "bpEURRewardPool: existing pool?"); } } // Add a new lp to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock ) public onlyOperator { checkPoolDuplicate(_lpToken); if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { // chef is sleeping if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; } else { if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } } else { // chef is cooking if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (_lastRewardBlock <= startBlock) || (_lastRewardBlock <= block.number); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : _lastRewardBlock, accBpEurPerShare : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's BpEUR allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) public onlyOperator { massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); } pool.allocPoint = _allocPoint; } // Return accumulate rewards over the given _from to _to block. function getGeneratedReward(uint256 _from, uint256 _to) public view returns (uint256) { for (uint8 epochId = 3; epochId >= 1; --epochId) { if (_to >= epochEndBlocks[epochId - 1]) { if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochBpEURPerBlock[epochId]); uint256 _generatedReward = _to.sub(epochEndBlocks[epochId - 1]).mul(epochBpEURPerBlock[epochId]); if (epochId == 1) return _generatedReward.add(epochEndBlocks[0].sub(_from).mul(epochBpEURPerBlock[0])); for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_from >= epochEndBlocks[epochId - 1]) return _generatedReward.add(epochEndBlocks[epochId].sub(_from).mul(epochBpEURPerBlock[epochId])); _generatedReward = _generatedReward.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochBpEURPerBlock[epochId])); } return _generatedReward.add(epochEndBlocks[0].sub(_from).mul(epochBpEURPerBlock[0])); } } return _to.sub(_from).mul(epochBpEURPerBlock[0]); } // View function to see pending bpEURs on frontend. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBpEurPerShare = pool.accBpEurPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _bpEURReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); accBpEurPerShare = accBpEurPerShare.add(_bpEURReward.mul(1e18).div(lpSupply)); } return user.amount.mul(accBpEurPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } if (totalAllocPoint > 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _bpEURReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); pool.accBpEurPerShare = pool.accBpEurPerShare.add(_bpEURReward.mul(1e18).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens. function deposit(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accBpEurPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeBpEURTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_sender, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBpEurPerShare).div(1e18); emit Deposit(_sender, _pid, _amount); } // Withdraw LP tokens. function withdraw(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 _pending = user.amount.mul(pool.accBpEurPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeBpEURTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accBpEurPerShare).div(1e18); emit Withdraw(_sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _pid, _amount); } // Safe transfer function, just in case if rounding error causes pool to not have enough bpEURs. function safeBpEURTransfer(address _to, uint256 _amount) internal { uint256 _bpEURBal = bpeur.balanceOf(address(this)); if (_bpEURBal > 0) { if (_amount > _bpEURBal) { bpeur.safeTransfer(_to, _bpEURBal); } else { bpeur.safeTransfer(_to, _amount); } } } function setOperator(address _operator) external onlyOperator { operator = _operator; } function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator { if (block.number < epochEndBlocks[2] + BLOCKS_PER_DAY * 180) { // do not allow to drain lpToken if less than 6 months after farming ends. require(_token != bpeur, "!bpeur"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; require(_token != pool.lpToken, "!pool.lpToken"); } } _token.safeTransfer(to, amount); } }
contract bpEURRewardPool { using SafeMath for uint256; using SafeERC20 for IERC20; // governance address public operator; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. bpEURs to distribute per block. uint256 lastRewardBlock; // Last block number that bpEURs distribution occurs. uint256 accBpEurPerShare; // Accumulated bpEURs per share, times 1e18. See below. bool isStarted; // if lastRewardBlock has passed } IERC20 public bpeur = IERC20(0x0000000000000000000000000000000000000000); // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BpEUR mining starts. uint256 public startBlock; uint256 public constant BLOCKS_PER_DAY = 28800; // Day 1 to day 5: 20,000 bpeur daily // Day 6 to day 26: 5,000 bpeur daily // Day 27 to day 180: 1,000 daily uint256[] public epochTotalRewards = [100000 ether, 105000 ether, 154000 ether]; // Block number when each epoch ends. uint[3] public epochEndBlocks; // Reward per block for each of 3 epochs (last item is equal to 0 - for sanity). uint[4] public epochBpEURPerBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event RewardPaid(address indexed user, uint256 amount); constructor( address _bpEUR, uint256 _startBlock ) public { require(block.number < _startBlock, "late"); if (_bpEUR != address(0)) bpeur = IERC20(_bpEUR); startBlock = _startBlock; // supposed to be 6180000 (Thu Apr 01 2021 05:30:00 GMT+0) epochEndBlocks[0] = startBlock + BLOCKS_PER_DAY * 5; epochBpEURPerBlock[0] = epochTotalRewards[0].div(BLOCKS_PER_DAY * 5); epochEndBlocks[1] = epochEndBlocks[0] + BLOCKS_PER_DAY * 21; epochBpEURPerBlock[1] = epochTotalRewards[1].div(BLOCKS_PER_DAY * 21); epochEndBlocks[2] = epochEndBlocks[1] + BLOCKS_PER_DAY * 154; epochBpEURPerBlock[2] = epochTotalRewards[1].div(BLOCKS_PER_DAY * 154); epochBpEURPerBlock[3] = 0; operator = msg.sender; } modifier onlyOperator() { require(operator == msg.sender, "bpEURRewardPool: caller is not the operator"); _; } function poolLength() external view returns (uint256) { return poolInfo.length; } function checkPoolDuplicate(IERC20 _lpToken) internal view { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].lpToken != _lpToken, "bpEURRewardPool: existing pool?"); } } // Add a new lp to the pool. Can only be called by the owner. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, uint256 _lastRewardBlock ) public onlyOperator { checkPoolDuplicate(_lpToken); if (_withUpdate) { massUpdatePools(); } if (block.number < startBlock) { // chef is sleeping if (_lastRewardBlock == 0) { _lastRewardBlock = startBlock; } else { if (_lastRewardBlock < startBlock) { _lastRewardBlock = startBlock; } } } else { // chef is cooking if (_lastRewardBlock == 0 || _lastRewardBlock < block.number) { _lastRewardBlock = block.number; } } bool _isStarted = (_lastRewardBlock <= startBlock) || (_lastRewardBlock <= block.number); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : _lastRewardBlock, accBpEurPerShare : 0, isStarted : _isStarted })); if (_isStarted) { totalAllocPoint = totalAllocPoint.add(_allocPoint); } } // Update the given pool's BpEUR allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) public onlyOperator { massUpdatePools(); PoolInfo storage pool = poolInfo[_pid]; if (pool.isStarted) { totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add( _allocPoint ); } pool.allocPoint = _allocPoint; } // Return accumulate rewards over the given _from to _to block. function getGeneratedReward(uint256 _from, uint256 _to) public view returns (uint256) { for (uint8 epochId = 3; epochId >= 1; --epochId) { if (_to >= epochEndBlocks[epochId - 1]) { if (_from >= epochEndBlocks[epochId - 1]) return _to.sub(_from).mul(epochBpEURPerBlock[epochId]); uint256 _generatedReward = _to.sub(epochEndBlocks[epochId - 1]).mul(epochBpEURPerBlock[epochId]); if (epochId == 1) return _generatedReward.add(epochEndBlocks[0].sub(_from).mul(epochBpEURPerBlock[0])); for (epochId = epochId - 1; epochId >= 1; --epochId) { if (_from >= epochEndBlocks[epochId - 1]) return _generatedReward.add(epochEndBlocks[epochId].sub(_from).mul(epochBpEURPerBlock[epochId])); _generatedReward = _generatedReward.add(epochEndBlocks[epochId].sub(epochEndBlocks[epochId - 1]).mul(epochBpEURPerBlock[epochId])); } return _generatedReward.add(epochEndBlocks[0].sub(_from).mul(epochBpEURPerBlock[0])); } } return _to.sub(_from).mul(epochBpEURPerBlock[0]); } // View function to see pending bpEURs on frontend. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBpEurPerShare = pool.accBpEurPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _bpEURReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); accBpEurPerShare = accBpEurPerShare.add(_bpEURReward.mul(1e18).div(lpSupply)); } return user.amount.mul(accBpEurPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } if (!pool.isStarted) { pool.isStarted = true; totalAllocPoint = totalAllocPoint.add(pool.allocPoint); } if (totalAllocPoint > 0) { uint256 _generatedReward = getGeneratedReward(pool.lastRewardBlock, block.number); uint256 _bpEURReward = _generatedReward.mul(pool.allocPoint).div(totalAllocPoint); pool.accBpEurPerShare = pool.accBpEurPerShare.add(_bpEURReward.mul(1e18).div(lpSupply)); } pool.lastRewardBlock = block.number; } // Deposit LP tokens. function deposit(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; updatePool(_pid); if (user.amount > 0) { uint256 _pending = user.amount.mul(pool.accBpEurPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeBpEURTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_sender, address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBpEurPerShare).div(1e18); emit Deposit(_sender, _pid, _amount); } // Withdraw LP tokens. function withdraw(uint256 _pid, uint256 _amount) public { address _sender = msg.sender; PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 _pending = user.amount.mul(pool.accBpEurPerShare).div(1e18).sub(user.rewardDebt); if (_pending > 0) { safeBpEURTransfer(_sender, _pending); emit RewardPaid(_sender, _pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(_sender, _amount); } user.rewardDebt = user.amount.mul(pool.accBpEurPerShare).div(1e18); emit Withdraw(_sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 _amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(msg.sender, _amount); emit EmergencyWithdraw(msg.sender, _pid, _amount); } // Safe transfer function, just in case if rounding error causes pool to not have enough bpEURs. function safeBpEURTransfer(address _to, uint256 _amount) internal { uint256 _bpEURBal = bpeur.balanceOf(address(this)); if (_bpEURBal > 0) { if (_amount > _bpEURBal) { bpeur.safeTransfer(_to, _bpEURBal); } else { bpeur.safeTransfer(_to, _amount); } } } function setOperator(address _operator) external onlyOperator { operator = _operator; } function governanceRecoverUnsupported(IERC20 _token, uint256 amount, address to) external onlyOperator { if (block.number < epochEndBlocks[2] + BLOCKS_PER_DAY * 180) { // do not allow to drain lpToken if less than 6 months after farming ends. require(_token != bpeur, "!bpeur"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; require(_token != pool.lpToken, "!pool.lpToken"); } } _token.safeTransfer(to, amount); } }
40,383
66
// Private implementation of staking methods. staker User address who deposits tokens to stake. beneficiary User address who gains credit for this stake operation. amount Number of deposit tokens to stake. /
function _stakeFor(address staker, address beneficiary, uint256 amount) private { require(amount > 0, 'SwingySeesaw: stake amount is zero'); require(beneficiary != address(0), 'SwingySeesaw: beneficiary is zero address'); require(totalStakingShares == 0 || totalStaked() > 0, 'SwingySeesaw: 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, 'SwingySeesaw: 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), 'SwingySeesaw: transfer into staking pool failed'); emit Staked(beneficiary, amount, totalStakedFor(beneficiary), ""); }
function _stakeFor(address staker, address beneficiary, uint256 amount) private { require(amount > 0, 'SwingySeesaw: stake amount is zero'); require(beneficiary != address(0), 'SwingySeesaw: beneficiary is zero address'); require(totalStakingShares == 0 || totalStaked() > 0, 'SwingySeesaw: 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, 'SwingySeesaw: 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), 'SwingySeesaw: transfer into staking pool failed'); emit Staked(beneficiary, amount, totalStakedFor(beneficiary), ""); }
14,364
335
// harvest must be a controlled function b/c engages with uniswap in mean time, can gain sushi rewards via xsushi on sushi gained from depositing into masterchef mid term
function midTermDepositLp(IERC20 pool, uint256 _lpTokens) internal { PoolData storage poolData = pools[address(pool)]; uint256 sushiAmt = sushiToken.balanceOf(address(this)); pool.ondoSafeIncreaseAllowance(address(masterChef), _lpTokens); masterChef.deposit(pools[address(pool)].pid, _lpTokens); sushiAmt = sushiToken.balanceOf(address(this)) - sushiAmt; uint256 xSushiAmt = xSushi.balanceOf(address(this)); sushiToken.ondoSafeIncreaseAllowance(address(xSushi), sushiAmt); xSushi.enter(sushiAmt); poolData.pendingXSushi += xSushi.balanceOf(address(this)) - xSushiAmt; }
function midTermDepositLp(IERC20 pool, uint256 _lpTokens) internal { PoolData storage poolData = pools[address(pool)]; uint256 sushiAmt = sushiToken.balanceOf(address(this)); pool.ondoSafeIncreaseAllowance(address(masterChef), _lpTokens); masterChef.deposit(pools[address(pool)].pid, _lpTokens); sushiAmt = sushiToken.balanceOf(address(this)) - sushiAmt; uint256 xSushiAmt = xSushi.balanceOf(address(this)); sushiToken.ondoSafeIncreaseAllowance(address(xSushi), sushiAmt); xSushi.enter(sushiAmt); poolData.pendingXSushi += xSushi.balanceOf(address(this)) - xSushiAmt; }
81,194
262
// Tells the proxy type (EIP 897)return proxyTypeId Proxy type, 2 for forwarding proxy /
function proxyType() public pure override returns (uint256 proxyTypeId) { return 2; }
function proxyType() public pure override returns (uint256 proxyTypeId) { return 2; }
20,812
22
// It should either call `exampleExternalContract.complete{value: address(this).balance}()` to send all the value Send ETH to external contract
require(address(this).balance >= threshold, "Not enough ETH staked");
require(address(this).balance >= threshold, "Not enough ETH staked");
7,112
205
// returns the ether KTY price on uniswap, that is, how many KTYs for 1 ether /
function ETH_KTY_price() public view returns (uint256) { uint256 _amountETH = 1e18; // 1 KTY (uint256 _reserveKTY, uint256 _reserveETH) = getReserve(kittieFightTokenAddr, wethAddr, ktyWethPair); return UniswapV2Library.getAmountIn(_amountETH, _reserveKTY, _reserveETH); }
function ETH_KTY_price() public view returns (uint256) { uint256 _amountETH = 1e18; // 1 KTY (uint256 _reserveKTY, uint256 _reserveETH) = getReserve(kittieFightTokenAddr, wethAddr, ktyWethPair); return UniswapV2Library.getAmountIn(_amountETH, _reserveKTY, _reserveETH); }
44,181
163
// How long each inflation period is before mint can be called
uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay)
uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay)
4,872
314
// Resolves an offset stored at `cdPtr` to a calldata pointer./`cdPtr` must point to some parent object with a dynamic type as its
/// first member, e.g. `struct { bytes data; }` function pptr( CalldataPointer cdPtr ) internal pure returns (CalldataPointer cdPtrChild) { cdPtrChild = cdPtr.offset(cdPtr.readUint256() & OffsetOrLengthMask); }
/// first member, e.g. `struct { bytes data; }` function pptr( CalldataPointer cdPtr ) internal pure returns (CalldataPointer cdPtrChild) { cdPtrChild = cdPtr.offset(cdPtr.readUint256() & OffsetOrLengthMask); }
40,218
214
// ORACLIZE IMPLEMENTATION //Converts 'uint' to 'string' /
function uint2str(uint256 i) internal pure returns(string) { if (i == 0) return "0"; uint256 j = i; uint256 len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); }
function uint2str(uint256 i) internal pure returns(string) { if (i == 0) return "0"; uint256 j = i; uint256 len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); }
26,045
106
// Usually a temp variable when compounding
mapping(address => uint256) pendingRewards;
mapping(address => uint256) pendingRewards;
34,161
394
// Standard implementation of ERC20's transferFrom()./ Overridden to allow arbitrary logic in ComptrollerProxy prior to transfer.
function transferFrom( address _sender, address _recipient, uint256 _amount ) public override returns (bool success_) { __invokePreTransferSharesHook(_sender, _recipient, _amount); return super.transferFrom(_sender, _recipient, _amount); }
function transferFrom( address _sender, address _recipient, uint256 _amount ) public override returns (bool success_) { __invokePreTransferSharesHook(_sender, _recipient, _amount); return super.transferFrom(_sender, _recipient, _amount); }
38,842
7
// address owner,
string memory MedicineName, uint256 NationalDrugCode, string[] memory Conditions, address Manufacturer, string memory Quantity, string memory status, string[] memory Ingredients, string[] memory sideEffects, string memory ExpiryDate,
string memory MedicineName, uint256 NationalDrugCode, string[] memory Conditions, address Manufacturer, string memory Quantity, string memory status, string[] memory Ingredients, string[] memory sideEffects, string memory ExpiryDate,
18,357
289
// reverse iteration since we're removing from the list
for (uint256 i = length; i > 0; i--) { uint256 index = i - 1; if (expirationTimes[index] > time()) { continue; }
for (uint256 i = length; i > 0; i--) { uint256 index = i - 1; if (expirationTimes[index] > time()) { continue; }
33,942
50
// check if timestamp is falling in the range
bool validTimestamp = startingTimestamp <= block.timestamp && endingTimestamp >= block.timestamp;
bool validTimestamp = startingTimestamp <= block.timestamp && endingTimestamp >= block.timestamp;
42,438
267
// Purchase senior token through delegacy to get fidu inside the delegacy _amount the amount of usdc to purchase by /
function purchaseSeniorTokens(uint256 _amount) external onlyOwner { require(_amount > 0, "Must deposit more than zero"); goldfinchDelegacy.purchaseSeniorTokens(_amount); emit PurchaseSenior(_amount); }
function purchaseSeniorTokens(uint256 _amount) external onlyOwner { require(_amount > 0, "Must deposit more than zero"); goldfinchDelegacy.purchaseSeniorTokens(_amount); emit PurchaseSenior(_amount); }
38,696
15
// CPD
{ (EventType eventType, uint256 scheduleTimeOffset) = decodeEvent(ICERTFEngine(asset.engine).computeNextCyclicEvent( terms, asset.schedule.lastScheduleTimeOfCyclicEvent[EventType.CPD], EventType.CPD )); if ( (nextScheduleTimeOffset == 0) || (scheduleTimeOffset != 0 && scheduleTimeOffset < nextScheduleTimeOffset)
{ (EventType eventType, uint256 scheduleTimeOffset) = decodeEvent(ICERTFEngine(asset.engine).computeNextCyclicEvent( terms, asset.schedule.lastScheduleTimeOfCyclicEvent[EventType.CPD], EventType.CPD )); if ( (nextScheduleTimeOffset == 0) || (scheduleTimeOffset != 0 && scheduleTimeOffset < nextScheduleTimeOffset)
40,025
21
// only addresses/roles configured with functionHash are allowed to call/internally it calls canPerform()/_functionStr functioHash
modifier authFunctionHash(string _functionStr) { require(msg.sender == address(this) || canPerform(msg.sender, _functionStr)); _; }
modifier authFunctionHash(string _functionStr) { require(msg.sender == address(this) || canPerform(msg.sender, _functionStr)); _; }
20,927
55
// Give the contract crowdsale amount
balances[this] = CROWDSALE_AMOUNT;
balances[this] = CROWDSALE_AMOUNT;
23,406
135
// Modifies an assetClassSets the immutable data on an ACNodeRequires that:caller holds ACtokenACnode is managementType 255 (unconfigured) /
function updateACImmutable(
function updateACImmutable(
34,204
8
// ============ Internal functions ============/ Return true if the given domain / router is the address of a remote xApp Router _domain The domain of the potential remote xApp Router _router The address of the potential remote xApp Router /
function _isRemoteRouter(uint32 _domain, bytes32 _router) internal view returns (bool)
function _isRemoteRouter(uint32 _domain, bytes32 _router) internal view returns (bool)
31,021
11
// sets the base uri used by tokenURI()
function setBaseURI(string calldata _uri) external onlyOwner
function setBaseURI(string calldata _uri) external onlyOwner
57,368