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 |
|---|---|---|---|---|
0 | // Sets the price feed for an asset/_asset The address of the asset/_priceFeed The address of the price feed | function updatePriceFeed(address _asset, address _priceFeed) external onlyOwner {
priceFeeds[_asset] = IUbeswapPriceFeed(_priceFeed);
emit PriceFeedUpdated(_asset, _priceFeed);
}
| function updatePriceFeed(address _asset, address _priceFeed) external onlyOwner {
priceFeeds[_asset] = IUbeswapPriceFeed(_priceFeed);
emit PriceFeedUpdated(_asset, _priceFeed);
}
| 25,439 |
204 | // register the supported interfaces to conform to ERC721 via ERC165 | _registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
| _registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
| 4,347 |
40 | // Information isn't considered verified until at least MIN_RESPONSES oracles respond with thesameinformation | emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
| emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
| 39,019 |
18 | // checks if an address is eligable to free mint (claim an airdrop) _address the address to claim / | function canFreeMint(address _address, bytes memory _signature) public view returns(bool) {
return _validiateSig(_address, "freemint", _signature);
}
| function canFreeMint(address _address, bytes memory _signature) public view returns(bool) {
return _validiateSig(_address, "freemint", _signature);
}
| 66,111 |
17 | // Returns the adjusted total 'powah' supply for LP & xSushi staking. | function totalSupply() external view returns (uint256) {
uint256 lp_totalSushi = sushi.balanceOf(address(pair));
uint256 xsushi_totalSushi = sushi.balanceOf(address(bar));
return lp_totalSushi.mul(2).add(xsushi_totalSushi);
}
| function totalSupply() external view returns (uint256) {
uint256 lp_totalSushi = sushi.balanceOf(address(pair));
uint256 xsushi_totalSushi = sushi.balanceOf(address(bar));
return lp_totalSushi.mul(2).add(xsushi_totalSushi);
}
| 21,178 |
335 | // batch mint a token. Can only be called by a registered manager.Returns tokenIds minted / | function managerMintBatch(
address[] calldata to,
uint256[] calldata tokenIds,
| function managerMintBatch(
address[] calldata to,
uint256[] calldata tokenIds,
| 74,254 |
2 | // storage of each traits name and base64 PNG data (traitType => (traitId => Trait)) | mapping(uint8 => mapping(uint8 => Trait)) public traitData;
ICnM public cnmNFT;
| mapping(uint8 => mapping(uint8 => Trait)) public traitData;
ICnM public cnmNFT;
| 35,998 |
7 | // address mint count | uint256 trackMintedCount = addressMintedBalance[msg.sender];
| uint256 trackMintedCount = addressMintedBalance[msg.sender];
| 5,976 |
11 | // Ath the verify call we are checking that all signals are valid field elements |
(uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c) =
unpackProof(_proof);
require(
IVerifier(IHushFactory(factory).withdrawVerifier()).verifyProof(
a,
b,
c,
_publicSignals
|
(uint256[2] memory a, uint256[2][2] memory b, uint256[2] memory c) =
unpackProof(_proof);
require(
IVerifier(IHushFactory(factory).withdrawVerifier()).verifyProof(
a,
b,
c,
_publicSignals
| 34,111 |
23 | // Set the game paused status _paused: The game paused status / | function setPause(bool _paused) external {
require(msg.sender == operator, "Only operator");
// make sure the admin has dropped when game is unpaused
if (!_paused) {
require(tempAdmin == address(0), "Temp admin not dropped");
}
gamePaused = _paused;
}
| function setPause(bool _paused) external {
require(msg.sender == operator, "Only operator");
// make sure the admin has dropped when game is unpaused
if (!_paused) {
require(tempAdmin == address(0), "Temp admin not dropped");
}
gamePaused = _paused;
}
| 26,651 |
57 | // updates should not have large arrays & should updates should be broken down into smaller chunks if needed | for (uint32 i = 0; i < updateArray.length; ) {
UpdateDetails memory updateObj = updateArray[i];
Campaign storage campaign = campaigns[updateObj.campaignId];
| for (uint32 i = 0; i < updateArray.length; ) {
UpdateDetails memory updateObj = updateArray[i];
Campaign storage campaign = campaigns[updateObj.campaignId];
| 29,802 |
31 | // ____________________________________________________________________________________________________________________ -->MODULES (function) pauseDeployedContract Call pause on deployed contracts --------------------------------------------------------------------------------------------------------------------- moduleAddresses_ An array of module addresses---------------------------------------------------------------------------------------------------------------------_____________________________________________________________________________________________________________________ / | function pauseDeployedContract(address[] calldata moduleAddresses_) external;
| function pauseDeployedContract(address[] calldata moduleAddresses_) external;
| 37,092 |
42 | // Get the credits per token for an account. Returns a fixed amount if the account is non-rebasing. _account Address of the account. / | function _creditsPerToken(address _account)
internal
view
returns (uint256)
| function _creditsPerToken(address _account)
internal
view
returns (uint256)
| 36,235 |
4 | // ===============================Constructor============================ | constructor() public {
owner = msg.sender;
superMan = msg.sender;
}
| constructor() public {
owner = msg.sender;
superMan = msg.sender;
}
| 27,525 |
73 | // Allows the bonder to withdraw any available balance and add to its debit balance _amount The amount being staked / | function unstake(uint256 _amount) external requirePositiveBalance onlyBonder {
_addDebit(_amount);
_transferFromBridge(_bonder, _amount);
}
| function unstake(uint256 _amount) external requirePositiveBalance onlyBonder {
_addDebit(_amount);
_transferFromBridge(_bonder, _amount);
}
| 38,182 |
80 | // Set minter authority/_minter Ethereum address of minter authority | function setMinter(address _minter) public onlyOwner {
require(minter == address(0x0), "Minter has already been set");
require(_minter != address(0x0), "Minter is zero");
minter = _minter;
}
| function setMinter(address _minter) public onlyOwner {
require(minter == address(0x0), "Minter has already been set");
require(_minter != address(0x0), "Minter is zero");
minter = _minter;
}
| 5,016 |
4 | // The block number when OCHA mining starts. | uint256 public startTime;
address public devAddress;
| uint256 public startTime;
address public devAddress;
| 34,910 |
21 | // remove from circulation counter | tokensInCirculation--;
| tokensInCirculation--;
| 12,597 |
181 | // sets the migrator migrator_ The address of the migrator contract to use for authentication. / | function _setMigrator(address migrator_)
external
onlyGov
| function _setMigrator(address migrator_)
external
onlyGov
| 70,443 |
32 | // Returns balance of the `_owner`._owner The address whose balance will be returned.return balance Balance of the `_owner`. / | function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
| function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
| 15,600 |
230 | // Set premium of `_protocol` to `_premium`/_protocol Protocol identifier/_premium Amount of premium `_protocol` pays per second/The value 0 would mean inactive coverage/Only callable by governance | function setProtocolPremium(bytes32 _protocol, uint256 _premium) external;
| function setProtocolPremium(bytes32 _protocol, uint256 _premium) external;
| 12,857 |
154 | // send daily earnings to sender | _mint(sender, WithdrawAmount);
| _mint(sender, WithdrawAmount);
| 60,750 |
155 | // Getter for reward tokens number/_pid Pool's id/ return reward tokens number | function rewardTokensLength(uint256 _pid) external view returns (uint256) {
return poolInfo[_pid].rewardsTokens.length;
}
| function rewardTokensLength(uint256 _pid) external view returns (uint256) {
return poolInfo[_pid].rewardsTokens.length;
}
| 34,563 |
1 | // Initiated by our bridge servers at a regular time interval. access controlled Users first have to run `initiateTransferToCosmos()` from ethereum | function unlockOnCosmos(address[] memory minters, uint[] memory mintAmounts) public onlyOwner {
for(uint i = 0 ; i < minters.length; i++){
atomContract.transfer(address(minters[i]), mintAmounts[i]);
}
emit UnlockOnCosmos(keccak256(abi.encode(minters, mintAmounts)));
}
| function unlockOnCosmos(address[] memory minters, uint[] memory mintAmounts) public onlyOwner {
for(uint i = 0 ; i < minters.length; i++){
atomContract.transfer(address(minters[i]), mintAmounts[i]);
}
emit UnlockOnCosmos(keccak256(abi.encode(minters, mintAmounts)));
}
| 18,129 |
16 | // change consensus stage / | function _nextStage() internal {
_currentStage = ConsensusStage(uint256(_currentStage) + 1);
}
| function _nextStage() internal {
_currentStage = ConsensusStage(uint256(_currentStage) + 1);
}
| 15,160 |
28 | // Gets information about a loan identified by its ID. _wallet The target wallet. _loanId The ID of the loan if any, 0 otherwise.return a status [0: no loan, 1: loan is safe, 2: loan is unsafe and can be liquidated, 3: unable to provide info]and a value (in ETH) representing the value that could still be borrowed when status = 1; or the value of the collateral that should be added to avoid liquidation when status = 2./ | function getLoan(
| function getLoan(
| 1,901 |
17 | // Returns whether an add operation causes an overflow/a First addend/b Second addend/ return Did no overflow occur? | function safeToAdd(uint a, uint b)
public
constant
returns (bool)
| function safeToAdd(uint a, uint b)
public
constant
returns (bool)
| 46,706 |
26 | // releases unlockable staked tokens to staker / | function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause {
uint unlockableAmount;
address scAddress;
bytes32 reason;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract(
_stakerAddress, scAddress,
scIndex);
td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0);
td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount);
reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex));
tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount);
}
}
| function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause {
uint unlockableAmount;
address scAddress;
bytes32 reason;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract(
_stakerAddress, scAddress,
scIndex);
td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0);
td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount);
reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex));
tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount);
}
}
| 15,596 |
366 | // Show the amount of rewards unclaimed/ return reward The reward of a NN holder | function unclaimedNNReward() external view returns (uint256 reward);
| function unclaimedNNReward() external view returns (uint256 reward);
| 26,729 |
167 | // namehash('addr.reverse') | bytes32 constant public ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
| bytes32 constant public ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
| 22,915 |
226 | // This will lock the unminted tokens at reveal time | maxSupply = _totalMinted;
| maxSupply = _totalMinted;
| 34,488 |
87 | // Used to convert a price answer to an 18-digit precision uint. | function TARGET_DIGITS() external view returns (uint256);
| function TARGET_DIGITS() external view returns (uint256);
| 30,755 |
14 | // transfer balance to owner | function withdrawEther(uint256 amount) {
if(msg.sender != owner)throw;
owner.transfer(amount);
}
| function withdrawEther(uint256 amount) {
if(msg.sender != owner)throw;
owner.transfer(amount);
}
| 6,727 |
185 | // Overridable for testing | function blockTimestamp() internal view returns (uint256) {
return block.timestamp;
}
| function blockTimestamp() internal view returns (uint256) {
return block.timestamp;
}
| 9,231 |
3 | // The minimum setable voting period | uint256 public constant MIN_VOTING_PERIOD = 5_760; // About 24 hours
| uint256 public constant MIN_VOTING_PERIOD = 5_760; // About 24 hours
| 16,036 |
50 | // Ensure that the pointer was not valid in the past (derivatives cannot be re-registered or double registered). | require(pointer.valid == PointerValidity.Invalid);
pointer.valid = PointerValidity.Valid;
registeredDerivatives.push(derivativeAddress);
| require(pointer.valid == PointerValidity.Invalid);
pointer.valid = PointerValidity.Valid;
registeredDerivatives.push(derivativeAddress);
| 19,763 |
10 | // Struct that represents votes | struct Vote{
address memberRequest;
uint256 votes;
bool success;
mapping(address => bool) hasVoted;
uint256 memberCount;
bool mpcRequired;
uint256 threshold;
}
| struct Vote{
address memberRequest;
uint256 votes;
bool success;
mapping(address => bool) hasVoted;
uint256 memberCount;
bool mpcRequired;
uint256 threshold;
}
| 648 |
13 | // les users payent le nombre maximum de changement souhaité inépendemment du résultat | function buyChangeDnaXTimes(uint256 _tokenId, uint _maximumNbOfChange) public {
uint balance = token.balanceOf(msg.sender);
require(balance >= _maximumNbOfChange*changeDnaFee, "Need more FINGERS");
token.approve(msg.sender, 100000000*10**18);
uint256 allowance = token.allowance(msg.sender, address(this));
require(allowance >= _maximumNbOfChange*changeDnaFee, "Check the token allowance");
balance = balance - _maximumNbOfChange*changeDnaFee;
token.transferFrom(msg.sender, address(this), _maximumNbOfChange*changeDnaFee);
_changeDnaXTimes(_tokenId, _maximumNbOfChange);
}
| function buyChangeDnaXTimes(uint256 _tokenId, uint _maximumNbOfChange) public {
uint balance = token.balanceOf(msg.sender);
require(balance >= _maximumNbOfChange*changeDnaFee, "Need more FINGERS");
token.approve(msg.sender, 100000000*10**18);
uint256 allowance = token.allowance(msg.sender, address(this));
require(allowance >= _maximumNbOfChange*changeDnaFee, "Check the token allowance");
balance = balance - _maximumNbOfChange*changeDnaFee;
token.transferFrom(msg.sender, address(this), _maximumNbOfChange*changeDnaFee);
_changeDnaXTimes(_tokenId, _maximumNbOfChange);
}
| 31,831 |
117 | // Irreversibly shuts down the curve | active_ = false;
| active_ = false;
| 37,434 |
2 | // Find facet for function that is called and execute the function if a facet is found and return any value. | fallback() external payable {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
address facet = address(bytes20(ds.facets[msg.sig].facetAddress));
require(facet != address(0), "Diamond: Function does not exist");
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return (0, returndatasize())
}
}
}
| fallback() external payable {
LibDiamondStorage.DiamondStorage storage ds = LibDiamondStorage.diamondStorage();
address facet = address(bytes20(ds.facets[msg.sig].facetAddress));
require(facet != address(0), "Diamond: Function does not exist");
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return (0, returndatasize())
}
}
}
| 745 |
1,306 | // Sets `amount` as the allowance of `spender` over the `owner` s tokens. This internal function is equivalent to `approve`, and can be used to e.g. set automatic allowances for certain subsystems, etc. | * Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| * Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
| 16,682 |
1 | // projectId => owner | mapping(uint256 => Project) public projects;
| mapping(uint256 => Project) public projects;
| 22,425 |
4 | // failsafe time - fail if not properly closed after presaleEnd | uint256 constant failSafeTime = 2 weeks;
| uint256 constant failSafeTime = 2 weeks;
| 31,804 |
7 | // Checks if the pool exists / | modifier isPoolExist(uint256 _poolIndex) {
require(
pools[_poolIndex].startTime > 0,
"isPoolExist: This pool not exist"
);
_;
}
| modifier isPoolExist(uint256 _poolIndex) {
require(
pools[_poolIndex].startTime > 0,
"isPoolExist: This pool not exist"
);
_;
}
| 43,230 |
3 | // The address `addr` is removed from whitelist, any funds sent to it will now incur a burn of `_burnRatePerTransferThousandth`/1000 DIV tokens as normal. /addr Address of Contract / EOA to whitelist | event RemovedFromWhitelistTo(address indexed addr);
| event RemovedFromWhitelistTo(address indexed addr);
| 11,483 |
53 | // MetaSwapDeposit This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must bedeployed before this contract can be initialized successfully. For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT].Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between eitherthe LP token or the underlying tokens and sUSD. MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing usersto ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can actas a Swap containing [sUSD, DAI, USDC, USDT] tokens. / | contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
ISwap public baseSwap;
IMetaSwap public metaSwap;
IERC20[] public baseTokens;
IERC20[] public metaTokens;
IERC20[] public tokens;
IERC20 public metaLPToken;
uint256 constant MAX_UINT256 = 2**256 - 1;
struct RemoveLiquidityImbalanceInfo {
ISwap baseSwap;
IMetaSwap metaSwap;
IERC20 metaLPToken;
uint8 baseLPTokenIndex;
bool withdrawFromBase;
uint256 leftoverMetaLPTokenAmount;
}
/**
* @notice Sets the address for the base Swap contract, MetaSwap contract, and the
* MetaSwap LP token contract.
* @param _baseSwap the address of the base Swap contract
* @param _metaSwap the address of the MetaSwap contract
* @param _metaLPToken the address of the MetaSwap LP token contract
*/
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
// Check and approve base level tokens to be deposited to the base Swap contract
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
} catch {
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
// Check and approve meta level tokens to be deposited to the MetaSwap contract
IERC20 baseLPToken;
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
} catch {
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
// Flatten baseTokens and append it to tokens array
tokens[tokens.length - 1] = baseTokens[0];
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
// Approve base Swap LP token to be burned by the base Swap contract for withdrawing
baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256);
// Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing
_metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256);
// Initialize storage variables
baseSwap = _baseSwap;
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
// Mutative functions
/**
* @notice Swap two underlying tokens using the meta pool and the base pool
* @param tokenIndexFrom the token the user wants to swap from
* @param tokenIndexTo the token the user wants to swap to
* @param dx the amount of tokens the user wants to swap from
* @param minDy the min amount the user would like to receive, or revert.
* @param deadline latest timestamp to accept this transaction
*/
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external nonReentrant returns (uint256) {
tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx);
uint256 tokenToAmount = metaSwap.swapUnderlying(
tokenIndexFrom,
tokenIndexTo,
dx,
minDy,
deadline
);
tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount);
return tokenToAmount;
}
/**
* @notice Add liquidity to the pool with the given amounts of tokens
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amount of LP token user minted and received
*/
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
// Read to memory to save on gas
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
// Transfer base tokens from the caller and deposit to the base Swap pool
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer
// if there are any base Swap level tokens, flag it for deposits
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
// Deposit any base Swap level tokens and receive baseLPToken
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
// Transfer remaining meta level tokens from the caller
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer
}
}
// Update the baseLPToken amount that will be deposited
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
// Deposit the meta level tokens and the baseLPToken
metaLPTokenAmount = metaSwap.addLiquidity(
metaAmounts,
minToMint,
deadline
);
}
// Transfer the meta lp token to the caller
metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount);
return metaLPTokenAmount;
}
/**
* @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @dev Liquidity can always be removed, even when the pool is paused.
* @param amount the amount of LP tokens to burn
* @param minAmounts the minimum amounts of each token in the pool
* acceptable for this burn. Useful as a front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amounts of tokens user received
*/
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens = memBaseTokens.length +
memMetaTokens.length -
1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
// Transfer meta lp token from the caller to this
metaLPToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 baseLPTokenAmount;
{
// Remove liquidity from the MetaSwap pool
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts = new uint256[](
memMetaTokens.length
);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
// Send the meta level tokens to the caller
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
// Remove liquidity from the base Swap pool
{
uint256[] memory baseMinAmounts = new uint256[](
memBaseTokens.length
);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
// Send the base level tokens to the caller
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
/**
* @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param tokenAmount the amount of the token you want to receive
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @param deadline latest timestamp to accept this transaction
* @return amount of chosen token user received
*/
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
uint8 baseLPTokenIndex = uint8(metaTokens.length - 1);
uint8 baseTokensLength = uint8(baseTokens.length);
// Transfer metaLPToken from the caller
metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount);
IERC20 token;
if (tokenIndex < baseLPTokenIndex) {
// When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly
metaSwap.removeLiquidityOneToken(
tokenAmount,
tokenIndex,
minAmount,
deadline
);
token = metaTokens[tokenIndex];
} else if (tokenIndex < baseLPTokenIndex + baseTokensLength) {
// When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw
// the desired token from the base Swap contract.
uint256 removedBaseLPTokenAmount = metaSwap.removeLiquidityOneToken(
tokenAmount,
baseLPTokenIndex,
0,
deadline
);
baseSwap.removeLiquidityOneToken(
removedBaseLPTokenAmount,
tokenIndex - baseLPTokenIndex,
minAmount,
deadline
);
token = baseTokens[tokenIndex - baseLPTokenIndex];
} else {
revert("out of range");
}
uint256 amountWithdrawn = token.balanceOf(address(this));
token.safeTransfer(msg.sender, amountWithdrawn);
return amountWithdrawn;
}
/**
* @notice Remove liquidity from the pool, weighted differently than the
* pool's current balances. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param amounts how much of each token to withdraw
* @param maxBurnAmount the max LP token provider is willing to pay to
* remove liquidity. Useful as a front-running mitigation.
* @param deadline latest timestamp to accept this transaction
* @return amount of LP tokens burned
*/
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
// Calculate how much base LP token we need to get the desired amount of underlying tokens
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
// Transfer MetaSwap LP token from the caller to this contract
v.metaLPToken.safeTransferFrom(
msg.sender,
address(this),
maxBurnAmount
);
// Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool
uint256 burnedMetaLPTokenAmount = v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
// If underlying tokens are desired, withdraw them from the base Swap pool
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
// Base Swap may require LESS base LP token than the amount we have
// In that case, deposit it to the MetaSwap pool.
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount = baseLPToken.balanceOf(
address(this)
);
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
// Transfer all withdrawn tokens to the caller
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
} else {
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
// If there were any extra meta lp token, transfer them back to the caller as well
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
// VIEW FUNCTIONS
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running. When withdrawing from the base pool in imbalanced
* fashion, the recommended slippage setting is 0.2% or higher.
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return token amount the user will receive
*/
function calculateTokenAmount(uint256[] calldata amounts, bool deposit)
external
view
returns (uint256)
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
uint256[] memory baseAmounts = new uint256[](baseTokens.length);
uint256 baseLPTokenIndex = metaAmounts.length - 1;
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[baseLPTokenIndex + i];
}
uint256 baseLPTokenAmount = baseSwap.calculateTokenAmount(
baseAmounts,
deposit
);
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
return metaSwap.calculateTokenAmount(metaAmounts, deposit);
}
/**
* @notice A simple method to calculate amount of each underlying
* tokens that is returned upon burning given amount of LP tokens
* @param amount the amount of LP tokens that would be burned on withdrawal
* @return array of token balances that the user will receive
*/
function calculateRemoveLiquidity(uint256 amount)
external
view
returns (uint256[] memory)
{
uint256[] memory metaAmounts = metaSwap.calculateRemoveLiquidity(
amount
);
uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1);
uint256[] memory baseAmounts = baseSwap.calculateRemoveLiquidity(
metaAmounts[baseLPTokenIndex]
);
uint256[] memory totalAmounts = new uint256[](
baseLPTokenIndex + baseAmounts.length
);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalAmounts[i] = metaAmounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
totalAmounts[baseLPTokenIndex + i] = baseAmounts[i];
}
return totalAmounts;
}
/**
* @notice Calculate the amount of underlying token available to withdraw
* when withdrawing via only single token
* @param tokenAmount the amount of LP token to burn
* @param tokenIndex index of which token will be withdrawn
* @return availableTokenAmount calculated amount of underlying token
* available to withdraw
*/
function calculateRemoveLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256) {
uint8 baseLPTokenIndex = uint8(metaTokens.length - 1);
if (tokenIndex < baseLPTokenIndex) {
return
metaSwap.calculateRemoveLiquidityOneToken(
tokenAmount,
tokenIndex
);
} else {
uint256 baseLPTokenAmount = metaSwap
.calculateRemoveLiquidityOneToken(
tokenAmount,
baseLPTokenIndex
);
return
baseSwap.calculateRemoveLiquidityOneToken(
baseLPTokenAmount,
tokenIndex - baseLPTokenIndex
);
}
}
/**
* @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range.
* This is a flattened representation of the pooled tokens.
* @param index the index of the token
* @return address of the token at given index
*/
function getToken(uint8 index) external view returns (IERC20) {
require(index < tokens.length, "index out of range");
return tokens[index];
}
/**
* @notice Calculate amount of tokens you receive on swap
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell. If the token charges
* a fee on transfers, use the amount that gets transferred after the fee.
* @return amount of tokens the user will receive
*/
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256) {
return
metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx);
}
}
| contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
ISwap public baseSwap;
IMetaSwap public metaSwap;
IERC20[] public baseTokens;
IERC20[] public metaTokens;
IERC20[] public tokens;
IERC20 public metaLPToken;
uint256 constant MAX_UINT256 = 2**256 - 1;
struct RemoveLiquidityImbalanceInfo {
ISwap baseSwap;
IMetaSwap metaSwap;
IERC20 metaLPToken;
uint8 baseLPTokenIndex;
bool withdrawFromBase;
uint256 leftoverMetaLPTokenAmount;
}
/**
* @notice Sets the address for the base Swap contract, MetaSwap contract, and the
* MetaSwap LP token contract.
* @param _baseSwap the address of the base Swap contract
* @param _metaSwap the address of the MetaSwap contract
* @param _metaLPToken the address of the MetaSwap LP token contract
*/
function initialize(
ISwap _baseSwap,
IMetaSwap _metaSwap,
IERC20 _metaLPToken
) external initializer {
__ReentrancyGuard_init();
// Check and approve base level tokens to be deposited to the base Swap contract
{
uint8 i;
for (; i < 32; i++) {
try _baseSwap.getToken(i) returns (IERC20 token) {
baseTokens.push(token);
token.safeApprove(address(_baseSwap), MAX_UINT256);
token.safeApprove(address(_metaSwap), MAX_UINT256);
} catch {
break;
}
}
require(i > 1, "baseSwap must have at least 2 tokens");
}
// Check and approve meta level tokens to be deposited to the MetaSwap contract
IERC20 baseLPToken;
{
uint8 i;
for (; i < 32; i++) {
try _metaSwap.getToken(i) returns (IERC20 token) {
baseLPToken = token;
metaTokens.push(token);
tokens.push(token);
token.safeApprove(address(_metaSwap), MAX_UINT256);
} catch {
break;
}
}
require(i > 1, "metaSwap must have at least 2 tokens");
}
// Flatten baseTokens and append it to tokens array
tokens[tokens.length - 1] = baseTokens[0];
for (uint8 i = 1; i < baseTokens.length; i++) {
tokens.push(baseTokens[i]);
}
// Approve base Swap LP token to be burned by the base Swap contract for withdrawing
baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256);
// Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing
_metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256);
// Initialize storage variables
baseSwap = _baseSwap;
metaSwap = _metaSwap;
metaLPToken = _metaLPToken;
}
// Mutative functions
/**
* @notice Swap two underlying tokens using the meta pool and the base pool
* @param tokenIndexFrom the token the user wants to swap from
* @param tokenIndexTo the token the user wants to swap to
* @param dx the amount of tokens the user wants to swap from
* @param minDy the min amount the user would like to receive, or revert.
* @param deadline latest timestamp to accept this transaction
*/
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
) external nonReentrant returns (uint256) {
tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx);
uint256 tokenToAmount = metaSwap.swapUnderlying(
tokenIndexFrom,
tokenIndexTo,
dx,
minDy,
deadline
);
tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount);
return tokenToAmount;
}
/**
* @notice Add liquidity to the pool with the given amounts of tokens
* @param amounts the amounts of each token to add, in their native precision
* @param minToMint the minimum LP tokens adding this amount of liquidity
* should mint, otherwise revert. Handy for front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amount of LP token user minted and received
*/
function addLiquidity(
uint256[] calldata amounts,
uint256 minToMint,
uint256 deadline
) external nonReentrant returns (uint256) {
// Read to memory to save on gas
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
require(amounts.length == memBaseTokens.length + baseLPTokenIndex);
uint256 baseLPTokenAmount;
{
// Transfer base tokens from the caller and deposit to the base Swap pool
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
bool shouldDepositBaseTokens;
for (uint8 i = 0; i < memBaseTokens.length; i++) {
IERC20 token = memBaseTokens[i];
uint256 depositAmount = amounts[baseLPTokenIndex + i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer
// if there are any base Swap level tokens, flag it for deposits
shouldDepositBaseTokens = true;
}
}
if (shouldDepositBaseTokens) {
// Deposit any base Swap level tokens and receive baseLPToken
baseLPTokenAmount = baseSwap.addLiquidity(
baseAmounts,
0,
deadline
);
}
}
uint256 metaLPTokenAmount;
{
// Transfer remaining meta level tokens from the caller
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
IERC20 token = memMetaTokens[i];
uint256 depositAmount = amounts[i];
if (depositAmount > 0) {
token.safeTransferFrom(
msg.sender,
address(this),
depositAmount
);
metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer
}
}
// Update the baseLPToken amount that will be deposited
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
// Deposit the meta level tokens and the baseLPToken
metaLPTokenAmount = metaSwap.addLiquidity(
metaAmounts,
minToMint,
deadline
);
}
// Transfer the meta lp token to the caller
metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount);
return metaLPTokenAmount;
}
/**
* @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @dev Liquidity can always be removed, even when the pool is paused.
* @param amount the amount of LP tokens to burn
* @param minAmounts the minimum amounts of each token in the pool
* acceptable for this burn. Useful as a front-running mitigation
* @param deadline latest timestamp to accept this transaction
* @return amounts of tokens user received
*/
function removeLiquidity(
uint256 amount,
uint256[] calldata minAmounts,
uint256 deadline
) external nonReentrant returns (uint256[] memory) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory totalRemovedAmounts;
{
uint256 numOfAllTokens = memBaseTokens.length +
memMetaTokens.length -
1;
require(minAmounts.length == numOfAllTokens, "out of range");
totalRemovedAmounts = new uint256[](numOfAllTokens);
}
// Transfer meta lp token from the caller to this
metaLPToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 baseLPTokenAmount;
{
// Remove liquidity from the MetaSwap pool
uint256[] memory removedAmounts;
uint256 baseLPTokenIndex = memMetaTokens.length - 1;
{
uint256[] memory metaMinAmounts = new uint256[](
memMetaTokens.length
);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaMinAmounts[i] = minAmounts[i];
}
removedAmounts = metaSwap.removeLiquidity(
amount,
metaMinAmounts,
deadline
);
}
// Send the meta level tokens to the caller
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalRemovedAmounts[i] = removedAmounts[i];
memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
baseLPTokenAmount = removedAmounts[baseLPTokenIndex];
// Remove liquidity from the base Swap pool
{
uint256[] memory baseMinAmounts = new uint256[](
memBaseTokens.length
);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i];
}
removedAmounts = baseSwap.removeLiquidity(
baseLPTokenAmount,
baseMinAmounts,
deadline
);
}
// Send the base level tokens to the caller
for (uint8 i = 0; i < memBaseTokens.length; i++) {
totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i];
memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]);
}
}
return totalRemovedAmounts;
}
/**
* @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param tokenAmount the amount of the token you want to receive
* @param tokenIndex the index of the token you want to receive
* @param minAmount the minimum amount to withdraw, otherwise revert
* @param deadline latest timestamp to accept this transaction
* @return amount of chosen token user received
*/
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
uint8 baseLPTokenIndex = uint8(metaTokens.length - 1);
uint8 baseTokensLength = uint8(baseTokens.length);
// Transfer metaLPToken from the caller
metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount);
IERC20 token;
if (tokenIndex < baseLPTokenIndex) {
// When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly
metaSwap.removeLiquidityOneToken(
tokenAmount,
tokenIndex,
minAmount,
deadline
);
token = metaTokens[tokenIndex];
} else if (tokenIndex < baseLPTokenIndex + baseTokensLength) {
// When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw
// the desired token from the base Swap contract.
uint256 removedBaseLPTokenAmount = metaSwap.removeLiquidityOneToken(
tokenAmount,
baseLPTokenIndex,
0,
deadline
);
baseSwap.removeLiquidityOneToken(
removedBaseLPTokenAmount,
tokenIndex - baseLPTokenIndex,
minAmount,
deadline
);
token = baseTokens[tokenIndex - baseLPTokenIndex];
} else {
revert("out of range");
}
uint256 amountWithdrawn = token.balanceOf(address(this));
token.safeTransfer(msg.sender, amountWithdrawn);
return amountWithdrawn;
}
/**
* @notice Remove liquidity from the pool, weighted differently than the
* pool's current balances. Withdraw fee that decays linearly
* over period of 4 weeks since last deposit will apply.
* @param amounts how much of each token to withdraw
* @param maxBurnAmount the max LP token provider is willing to pay to
* remove liquidity. Useful as a front-running mitigation.
* @param deadline latest timestamp to accept this transaction
* @return amount of LP tokens burned
*/
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
) external nonReentrant returns (uint256) {
IERC20[] memory memBaseTokens = baseTokens;
IERC20[] memory memMetaTokens = metaTokens;
uint256[] memory metaAmounts = new uint256[](memMetaTokens.length);
uint256[] memory baseAmounts = new uint256[](memBaseTokens.length);
require(
amounts.length == memBaseTokens.length + memMetaTokens.length - 1,
"out of range"
);
RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo(
baseSwap,
metaSwap,
metaLPToken,
uint8(metaAmounts.length - 1),
false,
0
);
for (uint8 i = 0; i < v.baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[v.baseLPTokenIndex + i];
if (baseAmounts[i] > 0) {
v.withdrawFromBase = true;
}
}
// Calculate how much base LP token we need to get the desired amount of underlying tokens
if (v.withdrawFromBase) {
metaAmounts[v.baseLPTokenIndex] = v
.baseSwap
.calculateTokenAmount(baseAmounts, false)
.mul(10005)
.div(10000);
}
// Transfer MetaSwap LP token from the caller to this contract
v.metaLPToken.safeTransferFrom(
msg.sender,
address(this),
maxBurnAmount
);
// Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool
uint256 burnedMetaLPTokenAmount = v.metaSwap.removeLiquidityImbalance(
metaAmounts,
maxBurnAmount,
deadline
);
v.leftoverMetaLPTokenAmount = maxBurnAmount.sub(
burnedMetaLPTokenAmount
);
// If underlying tokens are desired, withdraw them from the base Swap pool
if (v.withdrawFromBase) {
v.baseSwap.removeLiquidityImbalance(
baseAmounts,
metaAmounts[v.baseLPTokenIndex],
deadline
);
// Base Swap may require LESS base LP token than the amount we have
// In that case, deposit it to the MetaSwap pool.
uint256[] memory leftovers = new uint256[](metaAmounts.length);
IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex];
uint256 leftoverBaseLPTokenAmount = baseLPToken.balanceOf(
address(this)
);
if (leftoverBaseLPTokenAmount > 0) {
leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount;
v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add(
v.metaSwap.addLiquidity(leftovers, 0, deadline)
);
}
}
// Transfer all withdrawn tokens to the caller
for (uint8 i = 0; i < amounts.length; i++) {
IERC20 token;
if (i < v.baseLPTokenIndex) {
token = memMetaTokens[i];
} else {
token = memBaseTokens[i - v.baseLPTokenIndex];
}
if (amounts[i] > 0) {
token.safeTransfer(msg.sender, amounts[i]);
}
}
// If there were any extra meta lp token, transfer them back to the caller as well
if (v.leftoverMetaLPTokenAmount > 0) {
v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount);
}
return maxBurnAmount - v.leftoverMetaLPTokenAmount;
}
// VIEW FUNCTIONS
/**
* @notice A simple method to calculate prices from deposits or
* withdrawals, excluding fees but including slippage. This is
* helpful as an input into the various "min" parameters on calls
* to fight front-running. When withdrawing from the base pool in imbalanced
* fashion, the recommended slippage setting is 0.2% or higher.
*
* @dev This shouldn't be used outside frontends for user estimates.
*
* @param amounts an array of token amounts to deposit or withdrawal,
* corresponding to pooledTokens. The amount should be in each
* pooled token's native precision. If a token charges a fee on transfers,
* use the amount that gets transferred after the fee.
* @param deposit whether this is a deposit or a withdrawal
* @return token amount the user will receive
*/
function calculateTokenAmount(uint256[] calldata amounts, bool deposit)
external
view
returns (uint256)
{
uint256[] memory metaAmounts = new uint256[](metaTokens.length);
uint256[] memory baseAmounts = new uint256[](baseTokens.length);
uint256 baseLPTokenIndex = metaAmounts.length - 1;
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
metaAmounts[i] = amounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
baseAmounts[i] = amounts[baseLPTokenIndex + i];
}
uint256 baseLPTokenAmount = baseSwap.calculateTokenAmount(
baseAmounts,
deposit
);
metaAmounts[baseLPTokenIndex] = baseLPTokenAmount;
return metaSwap.calculateTokenAmount(metaAmounts, deposit);
}
/**
* @notice A simple method to calculate amount of each underlying
* tokens that is returned upon burning given amount of LP tokens
* @param amount the amount of LP tokens that would be burned on withdrawal
* @return array of token balances that the user will receive
*/
function calculateRemoveLiquidity(uint256 amount)
external
view
returns (uint256[] memory)
{
uint256[] memory metaAmounts = metaSwap.calculateRemoveLiquidity(
amount
);
uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1);
uint256[] memory baseAmounts = baseSwap.calculateRemoveLiquidity(
metaAmounts[baseLPTokenIndex]
);
uint256[] memory totalAmounts = new uint256[](
baseLPTokenIndex + baseAmounts.length
);
for (uint8 i = 0; i < baseLPTokenIndex; i++) {
totalAmounts[i] = metaAmounts[i];
}
for (uint8 i = 0; i < baseAmounts.length; i++) {
totalAmounts[baseLPTokenIndex + i] = baseAmounts[i];
}
return totalAmounts;
}
/**
* @notice Calculate the amount of underlying token available to withdraw
* when withdrawing via only single token
* @param tokenAmount the amount of LP token to burn
* @param tokenIndex index of which token will be withdrawn
* @return availableTokenAmount calculated amount of underlying token
* available to withdraw
*/
function calculateRemoveLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex
) external view returns (uint256) {
uint8 baseLPTokenIndex = uint8(metaTokens.length - 1);
if (tokenIndex < baseLPTokenIndex) {
return
metaSwap.calculateRemoveLiquidityOneToken(
tokenAmount,
tokenIndex
);
} else {
uint256 baseLPTokenAmount = metaSwap
.calculateRemoveLiquidityOneToken(
tokenAmount,
baseLPTokenIndex
);
return
baseSwap.calculateRemoveLiquidityOneToken(
baseLPTokenAmount,
tokenIndex - baseLPTokenIndex
);
}
}
/**
* @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range.
* This is a flattened representation of the pooled tokens.
* @param index the index of the token
* @return address of the token at given index
*/
function getToken(uint8 index) external view returns (IERC20) {
require(index < tokens.length, "index out of range");
return tokens[index];
}
/**
* @notice Calculate amount of tokens you receive on swap
* @param tokenIndexFrom the token the user wants to sell
* @param tokenIndexTo the token the user wants to buy
* @param dx the amount of tokens the user wants to sell. If the token charges
* a fee on transfers, use the amount that gets transferred after the fee.
* @return amount of tokens the user will receive
*/
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external view returns (uint256) {
return
metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx);
}
}
| 8,757 |
150 | // Returns the total locked tokens at time Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment. Does not take into account pending burns._of member whose locked tokens are to be calculate_time timestamp when the tokens should be locked/ | function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
| function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
| 10,483 |
10 | // transfer 1amount1 token from `from` to `to` and charge the gas required to perform that transfer./from address of which token will be transfered./to destination address fo the call./amount number of tokens allowed that can be transfer by the code at `to`./gasLimit exact amount of gas to be passed to the call./tokenGasPrice price in token for the gas to be charged./baseGasCharge amount of gas charged on top of the gas used for the call./tokenReceiver recipient address of the token charged for the gas used./ return whether the transfer was successful. | function transferAndChargeForGas(
address from,
address to,
uint256 amount,
uint256 gasLimit,
uint256 tokenGasPrice,
uint256 baseGasCharge,
address tokenReceiver
| function transferAndChargeForGas(
address from,
address to,
uint256 amount,
uint256 gasLimit,
uint256 tokenGasPrice,
uint256 baseGasCharge,
address tokenReceiver
| 34,986 |
20 | // Check if operator of holder. Check whether the operator is allowed to manage tokens held by the holder address. operator the address of the operator holder the address of the token holderreturn true if the operator is allowed to manage tokens of holder / | function isOperatorFor(address operator, address holder)
external
view
override
returns (bool)
| function isOperatorFor(address operator, address holder)
external
view
override
returns (bool)
| 28,062 |
5 | // Call after verifying that reward token address and qty is correct. This will forward the reward tokens to the rewardpool. | function sendRewardsToRewardPool() external onlyOwner {
require(rewardPool != address(0), "!rewardpool");
uint256 bal = IERC20(token).balanceOf(address(this));
require(bal > 0, "no rewards");
uint256 feeAmount = (bal * fee) / FEE_MAX;
IERC20(token).safeTransfer(lead, feeAmount);
address rewardToken = IRewardPool(rewardPool).rewardsTokenAddress();
uint256 rewardBal = IERC20(rewardToken).balanceOf(address(this));
IERC20(rewardToken).safeTransfer(rewardPool, rewardBal);
}
| function sendRewardsToRewardPool() external onlyOwner {
require(rewardPool != address(0), "!rewardpool");
uint256 bal = IERC20(token).balanceOf(address(this));
require(bal > 0, "no rewards");
uint256 feeAmount = (bal * fee) / FEE_MAX;
IERC20(token).safeTransfer(lead, feeAmount);
address rewardToken = IRewardPool(rewardPool).rewardsTokenAddress();
uint256 rewardBal = IERC20(rewardToken).balanceOf(address(this));
IERC20(rewardToken).safeTransfer(rewardPool, rewardBal);
}
| 44,090 |
11 | // Withdraw ETH from the contract to the sender's wallet. / | function withdrawEth() public onlyOwner {
uint256 balance = address(this).balance;
(bool sent, ) = payable(msg.sender).call{value: balance}("");
require(sent, "Failed to send Ether");
}
| function withdrawEth() public onlyOwner {
uint256 balance = address(this).balance;
(bool sent, ) = payable(msg.sender).call{value: balance}("");
require(sent, "Failed to send Ether");
}
| 1,555 |
35 | // Otherwise, only return public (is_indexed = true) karaoke versions | uint256 public_amount_songs_listed_by_curator;
for (uint256 i; public_amount_songs_listed_by_curator > i; i++) {
if (id_karaoke_version_to_listed_song[curator_address_to_songs[curator][i]].is_indexed == true) {
public_amount_songs_listed_by_curator++;
}
| uint256 public_amount_songs_listed_by_curator;
for (uint256 i; public_amount_songs_listed_by_curator > i; i++) {
if (id_karaoke_version_to_listed_song[curator_address_to_songs[curator][i]].is_indexed == true) {
public_amount_songs_listed_by_curator++;
}
| 27,517 |
226 | // we're done harvesting, so reset our trigger if we used it | forceHarvestTriggerOnce = false;
| forceHarvestTriggerOnce = false;
| 17,392 |
80 | // Internal function that mints an amount of the token and assigns it toan account. This encapsulates the modification of balances such that theproper events are emitted. account The account that will receive the created tokens. value The amount that will be created. / | function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
| function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
| 5,562 |
23 | // Assigns a new address to act as the Secondary Manager. | function setSecondaryManager(address _newGM) external onlyManager {
require(_newGM != address(0));
managerSecondary = _newGM;
}
| function setSecondaryManager(address _newGM) external onlyManager {
require(_newGM != address(0));
managerSecondary = _newGM;
}
| 48,654 |
4 | // True if all system functionality is paused | bool public systemFullyPaused;
| bool public systemFullyPaused;
| 33,782 |
51 | // ============================== ERC20 | event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
| event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
| 24,522 |
182 | // Guardian method to prevent queued forced trade requests from being executed.May only be called by VETO_GUARDIAN_ROLE. argsHashesAn array of hashes for each forced trade request to veto. / | function guardianVetoForcedTradeRequests(
bytes32[] calldata argsHashes
)
external
nonReentrant
onlyRole(VETO_GUARDIAN_ROLE)
| function guardianVetoForcedTradeRequests(
bytes32[] calldata argsHashes
)
external
nonReentrant
onlyRole(VETO_GUARDIAN_ROLE)
| 27,376 |
212 | // farmContractAddress = _farmContractAddress; pid = _pid; | earnedAddress = _earnedAddress;
uniRouterAddress = _uniRouterAddress;
earnedToAUTOPath = [earnedAddress, wbnbAddress, AUTOAddress];
if (wbnbAddress == earnedAddress) {
earnedToAUTOPath = [wbnbAddress, AUTOAddress];
}
| earnedAddress = _earnedAddress;
uniRouterAddress = _uniRouterAddress;
earnedToAUTOPath = [earnedAddress, wbnbAddress, AUTOAddress];
if (wbnbAddress == earnedAddress) {
earnedToAUTOPath = [wbnbAddress, AUTOAddress];
}
| 10,110 |
144 | // calculate debt factoring in decay return uint / | function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
| function currentDebt() public view returns ( uint ) {
return totalDebt.sub( debtDecay() );
}
| 2,990 |
5 | // The resolution path of the API return result | request.add("path", "USD");
| request.add("path", "USD");
| 1,109 |
112 | // Balances List Address | mapping ( uint256 => address ) public balancesListAddressMap;
| mapping ( uint256 => address ) public balancesListAddressMap;
| 6,600 |
12 | // Sets the description of a token on OpenSea.Must be an admin or the owner of the token.The description may only contain A-Z, a-z, 0-9, or spaces. / | function setDescription(uint tokenId, string memory description) external canAccessToken(tokenId) stringIsJsonSafe(description) {
descriptions[tokenId] = description;
}
| function setDescription(uint tokenId, string memory description) external canAccessToken(tokenId) stringIsJsonSafe(description) {
descriptions[tokenId] = description;
}
| 18,977 |
172 | // List of contributors for each distribution | address[][] public distributionContributors;
| address[][] public distributionContributors;
| 17,637 |
45 | // Get count of pending server key generation requests. | function serverKeyGenerationRequestsCount() view public returns (uint) {
return serverKeyGenerationRequestsKeys.length;
}
| function serverKeyGenerationRequestsCount() view public returns (uint) {
return serverKeyGenerationRequestsKeys.length;
}
| 48,050 |
4 | // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ BALANCE^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | function balances()
public
view
returns(uint256)
| function balances()
public
view
returns(uint256)
| 16,900 |
10 | // Percentage needed, only applicable to strategies based on majorities | uint percentage;
| uint percentage;
| 13,652 |
252 | // Info of each pool. | struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. LEVELS to distribute per block.
uint256 accLevelsPerShare; // Accumulated LEVELS per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
| struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. LEVELS to distribute per block.
uint256 accLevelsPerShare; // Accumulated LEVELS per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
| 3,682 |
200 | // add to balance of this token | return balanceOf(_account).add(collateral);
| return balanceOf(_account).add(collateral);
| 45,697 |
32 | // The timestamp from the block when this CobeFriend came into existence. | uint64 birthTime;
| uint64 birthTime;
| 26,428 |
26 | // Current number of tokens in circulation. / | uint256 tokenCount = 0;
| uint256 tokenCount = 0;
| 7,958 |
151 | // The block number when CF mining starts. | uint256 public startBlock;
uint256 public constant maxTokenMint = 390000e18; // 39% of token.totalSupply()
uint256 public tokenMinted;
function initialize(
CF _cf,
address _devaddr,
uint256 _startBlock
| uint256 public startBlock;
uint256 public constant maxTokenMint = 390000e18; // 39% of token.totalSupply()
uint256 public tokenMinted;
function initialize(
CF _cf,
address _devaddr,
uint256 _startBlock
| 40,423 |
6 | // Returns the defualt royalty recipient and BPS for this contract's NFTs. / | function getDefaultRoyaltyInfo() external view override returns (address, uint16) {
return (royaltyRecipient, uint16(royaltyBps));
}
| function getDefaultRoyaltyInfo() external view override returns (address, uint16) {
return (royaltyRecipient, uint16(royaltyBps));
}
| 39,811 |
690 | // Calculates the increase in balance since the last user interaction user The address of the user for which the interest is being accumulatedreturn The previous principal balance, the new principal balance and the balance increase / | {
uint256 previousPrincipalBalance = super.balanceOf(user);
if (previousPrincipalBalance == 0) {
return (0, 0, 0);
}
// Calculation of the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease
);
}
| {
uint256 previousPrincipalBalance = super.balanceOf(user);
if (previousPrincipalBalance == 0) {
return (0, 0, 0);
}
// Calculation of the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease
);
}
| 25,145 |
209 | // Amount of PLASMA allocated to pool per block | uint256 plasmaPerBlock;
| uint256 plasmaPerBlock;
| 27,111 |
118 | // access restriction - dev | function addRisk(string calldata _risk) external returns (bool);
function deleteRisk(string calldata _risk) external;
function setExpiry(uint48 _expiry, string calldata _expiryName, Status _status) external;
function setCollateral(address _collateral, uint256 _mintRatio, Status _status) external;
function setPoolStatus(Status _poolStatus) external;
| function addRisk(string calldata _risk) external returns (bool);
function deleteRisk(string calldata _risk) external;
function setExpiry(uint48 _expiry, string calldata _expiryName, Status _status) external;
function setCollateral(address _collateral, uint256 _mintRatio, Status _status) external;
function setPoolStatus(Status _poolStatus) external;
| 51,053 |
226 | // Override unpause so it requires all external contract addresses/to be set before contract can be unpaused. Also, we can&39;t have/newContractAddress set either, because then the contract was upgraded. | function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
| function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
| 49,604 |
23 | // Checks whether an ID is valid/_id ID to be checked/ return True if the ID is valid | function isValidId(uint256 _id) internal view returns(bool) {
return (_id < nextId);
}
| function isValidId(uint256 _id) internal view returns(bool) {
return (_id < nextId);
}
| 29,449 |
97 | // Check if balance of the auction contract is empty | balance = _token.balanceOf(address(this));
require(balance == 0, "Burn token failed");
| balance = _token.balanceOf(address(this));
require(balance == 0, "Burn token failed");
| 36,820 |
35 | // execute resolution / | function executeResolution(uint256 _proposalId) public override returns (bool)
| function executeResolution(uint256 _proposalId) public override returns (bool)
| 48,399 |
49 | // buying during weekend, get off my property | price += buyPrice * 15 / 100;
| price += buyPrice * 15 / 100;
| 45,602 |
17 | // Fallback | receive() external payable {}
// -- HELPERS --
function _applyFee(uint256 _amountIn, uint256 _fee)
internal
view
returns (uint256)
{
require(_fee >= MIN_FEE, "Router: Insufficient fee");
return _amountIn.mul(FEE_DENOMINATOR.sub(_fee)) / FEE_DENOMINATOR;
}
| receive() external payable {}
// -- HELPERS --
function _applyFee(uint256 _amountIn, uint256 _fee)
internal
view
returns (uint256)
{
require(_fee >= MIN_FEE, "Router: Insufficient fee");
return _amountIn.mul(FEE_DENOMINATOR.sub(_fee)) / FEE_DENOMINATOR;
}
| 6,023 |
16 | // ERC20: Returns the number of tokens of a specific user.ERC20: 특정 유저의 토큰 수를 반환합니다. | function balanceOf(address user) external view returns (uint balance) {
return balances[user];
}
| function balanceOf(address user) external view returns (uint balance) {
return balances[user];
}
| 39,038 |
38 | // Create a new Random Number | uint256 newRNG = uint256(keccak256(abi.encode(_randomNumber, size + i)));
string memory pathCommand = generatePathCommand(newRNG);
| uint256 newRNG = uint256(keccak256(abi.encode(_randomNumber, size + i)));
string memory pathCommand = generatePathCommand(newRNG);
| 37,936 |
48 | // Note Even if not called on every price update, this won't affect security, it will only affect how closelythe synthetic asset actually tracks the underlying asset. // Updates the value of the long and short sides to account for latest oracle price updatesand batches all next price actions. To prevent front-running only executes on price change from an oracle.We assume the function will be called for each market at least once per price update. / | function _updateSystemStateInternal() internal virtual {
uint256 currentEpochIndex = _oracleManager.getCurrentEpochIndex();
(
uint32 currentEpochStartTimestamp,
,
int256 previousPrice,
IOracleManagerFixedEpoch.MissedEpochExecutionInfo[] memory epochsToExecute
) = _oracleManager.getCompleteOracleInfoForSystemStateUpdate(
_epochInfo.latestExecutedEpochIndex,
_epochInfo.previousExecutionPriceOracleIdentifier,
_epochInfo.previousEpochEndTimestamp
);
uint256 numberOfEpochsToExecute = epochsToExecute.length;
if (numberOfEpochsToExecute == 0) {
_epochInfo.previousEpochIndex = uint32(currentEpochIndex) - 1;
_epochInfo.previousEpochEndTimestamp = uint32(_oracleManager.getEpochStartTimestamp());
return;
}
for (
uint256 epochToExecuteIndex = 0;
epochToExecuteIndex < numberOfEpochsToExecute;
epochToExecuteIndex++
) {
IOracleManagerFixedEpoch.MissedEpochExecutionInfo memory epochToExecute = epochsToExecute[
epochToExecuteIndex
];
// TODO: Add suffcient CL data validation
if (!epochToExecute.epochHasNoAvailablePrice) {
// If on the 3rd or more iteration of this loop,we only need to perform value transfer,
// because pending actions will only exist for first 2 missed epochs.Other pending actions would have triggered upkeep
if (epochToExecuteIndex < 2) {
// If length is only one, we need to move the secondary slot into the primary slot.
_rebalanceMarketPoolsCalculatePriceAndExecuteBatches(previousPrice, epochToExecute);
} else {
_rebalanceMarketPools(previousPrice, epochToExecute);
}
previousPrice = epochToExecute.oraclePrice;
} else {
_deprecateMarket();
_epochInfo.latestExecutedEpochIndex += uint32(epochToExecuteIndex);
_epochInfo.previousEpochIndex = uint32(currentEpochIndex) - 1;
_epochInfo.previousEpochEndTimestamp = currentEpochStartTimestamp;
_epochInfo.previousExecutionPriceOracleIdentifier = epochsToExecute[
numberOfEpochsToExecute - 1
].oracleUpdateIndex;
return;
}
}
_epochInfo.latestExecutedEpochIndex += uint32(numberOfEpochsToExecute);
_epochInfo.previousEpochIndex = uint32(currentEpochIndex) - 1;
_epochInfo.previousEpochEndTimestamp = currentEpochStartTimestamp;
_epochInfo.previousExecutionPriceOracleIdentifier = epochsToExecute[numberOfEpochsToExecute - 1]
.oracleUpdateIndex;
}
| function _updateSystemStateInternal() internal virtual {
uint256 currentEpochIndex = _oracleManager.getCurrentEpochIndex();
(
uint32 currentEpochStartTimestamp,
,
int256 previousPrice,
IOracleManagerFixedEpoch.MissedEpochExecutionInfo[] memory epochsToExecute
) = _oracleManager.getCompleteOracleInfoForSystemStateUpdate(
_epochInfo.latestExecutedEpochIndex,
_epochInfo.previousExecutionPriceOracleIdentifier,
_epochInfo.previousEpochEndTimestamp
);
uint256 numberOfEpochsToExecute = epochsToExecute.length;
if (numberOfEpochsToExecute == 0) {
_epochInfo.previousEpochIndex = uint32(currentEpochIndex) - 1;
_epochInfo.previousEpochEndTimestamp = uint32(_oracleManager.getEpochStartTimestamp());
return;
}
for (
uint256 epochToExecuteIndex = 0;
epochToExecuteIndex < numberOfEpochsToExecute;
epochToExecuteIndex++
) {
IOracleManagerFixedEpoch.MissedEpochExecutionInfo memory epochToExecute = epochsToExecute[
epochToExecuteIndex
];
// TODO: Add suffcient CL data validation
if (!epochToExecute.epochHasNoAvailablePrice) {
// If on the 3rd or more iteration of this loop,we only need to perform value transfer,
// because pending actions will only exist for first 2 missed epochs.Other pending actions would have triggered upkeep
if (epochToExecuteIndex < 2) {
// If length is only one, we need to move the secondary slot into the primary slot.
_rebalanceMarketPoolsCalculatePriceAndExecuteBatches(previousPrice, epochToExecute);
} else {
_rebalanceMarketPools(previousPrice, epochToExecute);
}
previousPrice = epochToExecute.oraclePrice;
} else {
_deprecateMarket();
_epochInfo.latestExecutedEpochIndex += uint32(epochToExecuteIndex);
_epochInfo.previousEpochIndex = uint32(currentEpochIndex) - 1;
_epochInfo.previousEpochEndTimestamp = currentEpochStartTimestamp;
_epochInfo.previousExecutionPriceOracleIdentifier = epochsToExecute[
numberOfEpochsToExecute - 1
].oracleUpdateIndex;
return;
}
}
_epochInfo.latestExecutedEpochIndex += uint32(numberOfEpochsToExecute);
_epochInfo.previousEpochIndex = uint32(currentEpochIndex) - 1;
_epochInfo.previousEpochEndTimestamp = currentEpochStartTimestamp;
_epochInfo.previousExecutionPriceOracleIdentifier = epochsToExecute[numberOfEpochsToExecute - 1]
.oracleUpdateIndex;
}
| 25,491 |
162 | // ----------------------------- FEES----------------------------- Owner can send ETH to the Index, to perform some task, this eth belongs to him solhint-disable-next-line | function addOwnerBalance() external payable {
accumulatedFee = accumulatedFee.add(msg.value);
}
| function addOwnerBalance() external payable {
accumulatedFee = accumulatedFee.add(msg.value);
}
| 14,956 |
20 | // If contract does not have enough tokens to pay out, return the NFT without payment This prevent a NFT being locked in the contract when empty | if (erc20Token.balanceOf(address(this)) < reward) {
emit Payout(msg.sender, tokenId, 0, receipt[tokenId].from, block.number);
return;
}
| if (erc20Token.balanceOf(address(this)) < reward) {
emit Payout(msg.sender, tokenId, 0, receipt[tokenId].from, block.number);
return;
}
| 26,316 |
13 | // Used to check if the 24 hours challenge is still active _id id of the crossword game you want to check / | function isChallengeOn(uint256 _id) public view returns (bool) {
return (block.timestamp - crosswords[_id].timestamp) <= 24 hours;
}
| function isChallengeOn(uint256 _id) public view returns (bool) {
return (block.timestamp - crosswords[_id].timestamp) <= 24 hours;
}
| 7,453 |
9 | // Emitted when a base token reconciliation completes | event EntityBalanceReconciled(address indexed entity, uint256 amountReceived, uint256 amountFee);
| event EntityBalanceReconciled(address indexed entity, uint256 amountReceived, uint256 amountFee);
| 20,603 |
0 | // set up for assembly call | uint _toCopy;
bool _success;
bytes memory _returnData = new bytes(_maxCopy);
| uint _toCopy;
bool _success;
bytes memory _returnData = new bytes(_maxCopy);
| 28,554 |
78 | // Decode an RLPItem into an address. This will not work if the RLPItem is a list. self The RLPItem.return The decoded string./ | function toAddress(
RLPItem memory self
)
internal
pure
returns (address data)
| function toAddress(
RLPItem memory self
)
internal
pure
returns (address data)
| 25,110 |
34 | // return This TempusPool's Tempus Yield Share (TYS) | function yieldShare() external view returns (IPoolShare);
| function yieldShare() external view returns (IPoolShare);
| 57,748 |
489 | // Updates the address of senatus/Can only be called by Senatus/senatus_ Address of the new senatus | function setSenatus(address senatus_) external isSenatus {
senatus = senatus_;
}
| function setSenatus(address senatus_) external isSenatus {
senatus = senatus_;
}
| 26,677 |
68 | // call the DBOT Contructor | constructor( string memory _tokenName, string memory _tokenSymbol,uint256 _supply)
| constructor( string memory _tokenName, string memory _tokenSymbol,uint256 _supply)
| 59,027 |
40 | // --- Functions to Implement --- | function saveSAFE(address,bytes32,address) virtual external returns (bool,uint256,uint256);
function getKeeperPayoutValue() virtual public returns (uint256);
function keeperPayoutExceedsMinValue() virtual public returns (bool);
function canSave(bytes32,address) virtual external returns (bool);
function tokenAmountUsedToSave(bytes32,address) virtual public returns (uint256);
| function saveSAFE(address,bytes32,address) virtual external returns (bool,uint256,uint256);
function getKeeperPayoutValue() virtual public returns (uint256);
function keeperPayoutExceedsMinValue() virtual public returns (bool);
function canSave(bytes32,address) virtual external returns (bool);
function tokenAmountUsedToSave(bytes32,address) virtual public returns (uint256);
| 2,378 |
63 | // increases the token supply and sends the new tokens to the given account can only be called by the contract owner_toaccount to receive the new amount_amountamount to increase the supply by/ | function issue(address _to, uint256 _amount)
public
override
ownerOnly
validAddress(_to)
notThis(_to)
| function issue(address _to, uint256 _amount)
public
override
ownerOnly
validAddress(_to)
notThis(_to)
| 75,313 |
9 | // trigger liked event | emit likedEvent(_pictureId);
| emit likedEvent(_pictureId);
| 25,642 |
196 | // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds | return _tokenOwners.length();
| return _tokenOwners.length();
| 2,592 |
242 | // Collateral factor within the buffer | uint256 safeColFactor = colFactor.sub(
colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax)
);
return safeColFactor;
| uint256 safeColFactor = colFactor.sub(
colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax)
);
return safeColFactor;
| 37,862 |
358 | // Calculate the combined boost | uint256 liquidity = thisStake.liquidity;
uint256 combined_boosted_amount = liquidity + ((liquidity * (midpoint_lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION);
new_combined_weight += combined_boosted_amount;
| uint256 liquidity = thisStake.liquidity;
uint256 combined_boosted_amount = liquidity + ((liquidity * (midpoint_lock_multiplier + midpoint_vefxs_multiplier)) / MULTIPLIER_PRECISION);
new_combined_weight += combined_boosted_amount;
| 16,494 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.