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 |
|---|---|---|---|---|
30 | // NOLINTNEXTLINE: timestamp. | require(activation_time <= block.timestamp, "UPGRADE_NOT_ENABLED_YET");
bytes32 init_vector_hash = initializationHash[newImplementation];
require(init_vector_hash == keccak256(abi.encode(data, finalize)), "CHANGED_INITIALIZER");
setImplementation(newImplementation);
| require(activation_time <= block.timestamp, "UPGRADE_NOT_ENABLED_YET");
bytes32 init_vector_hash = initializationHash[newImplementation];
require(init_vector_hash == keccak256(abi.encode(data, finalize)), "CHANGED_INITIALIZER");
setImplementation(newImplementation);
| 56,035 |
1 | // The address of the Kiosk Market Token contract. | KioskMarketToken public KMT;
| KioskMarketToken public KMT;
| 34,808 |
124 | // withdraw liq. and get info how much we got out | (uint256 amountA, uint256 amountB) = _withdrawLiquidity(_uniData);
| (uint256 amountA, uint256 amountB) = _withdrawLiquidity(_uniData);
| 24,094 |
45 | // Function to distribute tokens to the list of addresses by the provided amount / | function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) {
require(amount > 0
&& addresses.length > 0
&& frozenAccount[msg.sender] == false
&& now > unlockUnixTime[msg.sender]);
amount = amount.mul(1e8);
uint256 totalAmount = amount.mul(addresses.length);
require(balanceOf[msg.sender] >= totalAmount);
for (uint j = 0; j < addresses.length; j++) {
require(addresses[j] != 0x0
&& frozenAccount[addresses[j]] == false
&& now > unlockUnixTime[addresses[j]]);
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount);
Transfer(msg.sender, addresses[j], amount);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
| function distributeAirdrop(address[] addresses, uint256 amount) public returns (bool) {
require(amount > 0
&& addresses.length > 0
&& frozenAccount[msg.sender] == false
&& now > unlockUnixTime[msg.sender]);
amount = amount.mul(1e8);
uint256 totalAmount = amount.mul(addresses.length);
require(balanceOf[msg.sender] >= totalAmount);
for (uint j = 0; j < addresses.length; j++) {
require(addresses[j] != 0x0
&& frozenAccount[addresses[j]] == false
&& now > unlockUnixTime[addresses[j]]);
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount);
Transfer(msg.sender, addresses[j], amount);
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
return true;
}
| 8,995 |
40 | // Transfer BEAN to treasury address dont already in beanfinace |
emit LotteryNumberDrawn(
currentLotteryId,
finalNumber,
numberAddressesInPreviousBracket
);
|
emit LotteryNumberDrawn(
currentLotteryId,
finalNumber,
numberAddressesInPreviousBracket
);
| 12,468 |
38 | // Convert tokens spent (e.g. 10,000,000 USDC = $10) to tokens bought (e.g. 8.13e18) at a price of $1.23/NCT convert an integer value of tokens spent to an integer value of tokens bought | return (spent * 10 ** sales[saleId].decimals ) / (sales[saleId].price);
| return (spent * 10 ** sales[saleId].decimals ) / (sales[saleId].price);
| 36,118 |
186 | // getVotingFor(): returns the points _proxy can vote asNote: only useful for clients, as Solidity does not currentlysupport returning dynamic arrays. | function getVotingFor(address _proxy)
view
external
returns (uint32[] vfor)
| function getVotingFor(address _proxy)
view
external
returns (uint32[] vfor)
| 19,575 |
0 | // private state variable | uint private data;
| uint private data;
| 28,775 |
69 | // IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F);Pancake |
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap
|
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap
| 10,952 |
28 | // This contract implements a simple keeper. It borrows ETH from the/ KeeperDAO liquidity pool, and immediately returns all of the borrowed ETH,/ plus some amount of "profit" from its own balance. Instead of returning/ profits from their own balances, keeper contracts will usually engage in/ arbitrage or liquidations to earn profits that can be returned. | contract HelloWorld {
/// @dev Owner of the contract.
address public owner;
/// @dev Address of the KeeperDAO borrow proxy. This will be the
/// `msg.sender` for calls to the `helloCallback` function.
address public borrowProxy;
/// @dev Address of the KeeperDAO liquidity pool. This is will be the
/// address to which the `helloCallback` function must return all bororwed
/// assets (and all excess profits).
address payable public liquidityPool;
/// @dev This modifier restricts the caller of a function to the owner of
/// this contract.
modifier onlyOwner {
if (msg.sender == owner) {
_;
}
}
/// @dev This modifier restricts the caller of a function to the KeeperDAO
/// borrow proxy.
modifier onlyBorrowProxy {
if (msg.sender == borrowProxy) {
_;
}
}
constructor() public {
owner = msg.sender;
}
function() external payable {
// Do nothing.
}
/// @dev Set the owner of this contract. This function can only be called by
/// the current owner.
///
/// @param _newOwner The new owner of this contract.
function setOwner(address _newOwner) external onlyOwner {
owner = _newOwner;
}
/// @dev Set the borrow proxy expected by this contract. This function can
/// only be called by the current owner.
///
/// @param _newBorrowProxy The new borrow proxy expected by this contract.
function setBorrowProxy(address _newBorrowProxy) external onlyOwner {
borrowProxy = _newBorrowProxy;
}
/// @dev Set the liquidity pool used by this contract. This function can
/// only be called by the current owner.
///
/// @param _newLiquidityPool The new liquidity pool used by this contract.
/// It must be a payable address, because this contract needs to be able to
/// return borrowed assets and profits to the liquidty pool.
function setLiquidityPool(address payable _newLiquidityPool)
external
onlyOwner
{
liquidityPool = _newLiquidityPool;
}
/// @dev This function is the entry point of this keeper. An off-chain bot
/// will call this function whenever it decides that it wants to borrow from
/// this KeeperDAO liquidity pool. This function is similar to what you
/// would expect in a "real" keeper implementation: it accepts paramters
/// telling it what / how much to borrow, and which callback on this
/// contract should be called once the borrowed funds have been transferred.
function hello(uint256 _amountToBorrow, uint256 _amountOfProfitToReturn)
external
onlyOwner
{
require(_amountOfProfitToReturn > 0, "profit is zero");
require(
address(this).balance > _amountOfProfitToReturn,
"balance is too low"
);
// The liquidity pool is guarded from re-entrance, so we can only call
// this function once per transaction.
LiquidityPool(liquidityPool).borrow(
// Address of the token we want to borrow. Using this address
// means that we want to borrow ETH.
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE),
// The amount of WEI that we will borrow. We have to return at least
// more than this amount.
_amountToBorrow,
// Encode the callback into calldata. This will be used to call a
// function on this contract.
abi.encodeWithSelector(
// Function selector of the callback function.
this.helloCallback.selector,
// First parameter of the callback.
_amountToBorrow,
// Second parameter of the callback.
_amountOfProfitToReturn
// Third paramter, fourth parameter, and so on (our callback
// only has two paramters).
)
);
}
/// @dev This is the callback function that implements our custom keeper
/// logic. We do not need to call this function directly; it will be called
/// by the KeeperDAO borrow proxy when we call borrow on the KeeperDAO
/// liquidity pool. In fact, usually, this function should be restricted so
/// that is can only be called by the KeeperDAO borrow proxy.
///
/// Just before this callback is called by the KeeperDAO borrow proxy, all
/// of the assets that we want to borrow will be transferred to this
/// contract. In this callback, we can do whatever we want with these
/// assets; we can arbitrage between DEXs, liquidity positions on Compound,
/// and so on. The only requirement is that at least more than the borrowed
/// assets is returned.
///
/// For example, imagine that we wanted borrowed 1 ETH. Before this callback
/// is called, the KeeperDAO liquidity pool will have transferred 1 ETH to
/// this contract. This callback can then do whatever it wants with that ETH.
/// However, before the callback returns, it must return at least more than
/// 1 ETH to the KeeperDAO liquidity pool (even if it is only returning
/// 1 ETH + 1 WEI).
///
/// In our example, we will not implement a complicated keeper strategy. We
/// will simply return all of the borrowed ETH, plus a non-zero amount of
/// profit. The amount of profit is explicitly specified by the owner of
/// this contract when they initiate the borrow. Of course, this strategy
/// does not generate profit by interacting with other protocols (like most
/// keepers do). Instead, it just uses its own balance to return profits to
/// KeeperDAO.
function helloCallback(
uint256 _amountBorrowed,
uint256 _amountOfProfitToReturn
) external onlyBorrowProxy {
assert(
address(this).balance >= _amountOfProfitToReturn + _amountBorrowed
);
assert(_amountOfProfitToReturn > 0);
// Notice that assets are transferred back to the liquidity pool, not to
// the borrow proxy.
liquidityPool.call.value(_amountBorrowed + _amountOfProfitToReturn)("");
}
}
| contract HelloWorld {
/// @dev Owner of the contract.
address public owner;
/// @dev Address of the KeeperDAO borrow proxy. This will be the
/// `msg.sender` for calls to the `helloCallback` function.
address public borrowProxy;
/// @dev Address of the KeeperDAO liquidity pool. This is will be the
/// address to which the `helloCallback` function must return all bororwed
/// assets (and all excess profits).
address payable public liquidityPool;
/// @dev This modifier restricts the caller of a function to the owner of
/// this contract.
modifier onlyOwner {
if (msg.sender == owner) {
_;
}
}
/// @dev This modifier restricts the caller of a function to the KeeperDAO
/// borrow proxy.
modifier onlyBorrowProxy {
if (msg.sender == borrowProxy) {
_;
}
}
constructor() public {
owner = msg.sender;
}
function() external payable {
// Do nothing.
}
/// @dev Set the owner of this contract. This function can only be called by
/// the current owner.
///
/// @param _newOwner The new owner of this contract.
function setOwner(address _newOwner) external onlyOwner {
owner = _newOwner;
}
/// @dev Set the borrow proxy expected by this contract. This function can
/// only be called by the current owner.
///
/// @param _newBorrowProxy The new borrow proxy expected by this contract.
function setBorrowProxy(address _newBorrowProxy) external onlyOwner {
borrowProxy = _newBorrowProxy;
}
/// @dev Set the liquidity pool used by this contract. This function can
/// only be called by the current owner.
///
/// @param _newLiquidityPool The new liquidity pool used by this contract.
/// It must be a payable address, because this contract needs to be able to
/// return borrowed assets and profits to the liquidty pool.
function setLiquidityPool(address payable _newLiquidityPool)
external
onlyOwner
{
liquidityPool = _newLiquidityPool;
}
/// @dev This function is the entry point of this keeper. An off-chain bot
/// will call this function whenever it decides that it wants to borrow from
/// this KeeperDAO liquidity pool. This function is similar to what you
/// would expect in a "real" keeper implementation: it accepts paramters
/// telling it what / how much to borrow, and which callback on this
/// contract should be called once the borrowed funds have been transferred.
function hello(uint256 _amountToBorrow, uint256 _amountOfProfitToReturn)
external
onlyOwner
{
require(_amountOfProfitToReturn > 0, "profit is zero");
require(
address(this).balance > _amountOfProfitToReturn,
"balance is too low"
);
// The liquidity pool is guarded from re-entrance, so we can only call
// this function once per transaction.
LiquidityPool(liquidityPool).borrow(
// Address of the token we want to borrow. Using this address
// means that we want to borrow ETH.
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE),
// The amount of WEI that we will borrow. We have to return at least
// more than this amount.
_amountToBorrow,
// Encode the callback into calldata. This will be used to call a
// function on this contract.
abi.encodeWithSelector(
// Function selector of the callback function.
this.helloCallback.selector,
// First parameter of the callback.
_amountToBorrow,
// Second parameter of the callback.
_amountOfProfitToReturn
// Third paramter, fourth parameter, and so on (our callback
// only has two paramters).
)
);
}
/// @dev This is the callback function that implements our custom keeper
/// logic. We do not need to call this function directly; it will be called
/// by the KeeperDAO borrow proxy when we call borrow on the KeeperDAO
/// liquidity pool. In fact, usually, this function should be restricted so
/// that is can only be called by the KeeperDAO borrow proxy.
///
/// Just before this callback is called by the KeeperDAO borrow proxy, all
/// of the assets that we want to borrow will be transferred to this
/// contract. In this callback, we can do whatever we want with these
/// assets; we can arbitrage between DEXs, liquidity positions on Compound,
/// and so on. The only requirement is that at least more than the borrowed
/// assets is returned.
///
/// For example, imagine that we wanted borrowed 1 ETH. Before this callback
/// is called, the KeeperDAO liquidity pool will have transferred 1 ETH to
/// this contract. This callback can then do whatever it wants with that ETH.
/// However, before the callback returns, it must return at least more than
/// 1 ETH to the KeeperDAO liquidity pool (even if it is only returning
/// 1 ETH + 1 WEI).
///
/// In our example, we will not implement a complicated keeper strategy. We
/// will simply return all of the borrowed ETH, plus a non-zero amount of
/// profit. The amount of profit is explicitly specified by the owner of
/// this contract when they initiate the borrow. Of course, this strategy
/// does not generate profit by interacting with other protocols (like most
/// keepers do). Instead, it just uses its own balance to return profits to
/// KeeperDAO.
function helloCallback(
uint256 _amountBorrowed,
uint256 _amountOfProfitToReturn
) external onlyBorrowProxy {
assert(
address(this).balance >= _amountOfProfitToReturn + _amountBorrowed
);
assert(_amountOfProfitToReturn > 0);
// Notice that assets are transferred back to the liquidity pool, not to
// the borrow proxy.
liquidityPool.call.value(_amountBorrowed + _amountOfProfitToReturn)("");
}
}
| 21,150 |
0 | // Emited when contract is upgraded | event ContractUpgrade(address newContract);
| event ContractUpgrade(address newContract);
| 22,528 |
20 | // Unpauses a campaign_campaignId id of the campaign / | function unpauseCampaign(uint256 _campaignId) external override onlyOwner {
Campaign storage _campaign = _campaigns[_campaignId];
require(_campaign.state == CampaignState.Paused, "ReferralLink: Invalid campaign id");
_campaign.state = CampaignState.Valid;
emit CampaignStateChanged(_campaignId, CampaignState.Valid);
}
| function unpauseCampaign(uint256 _campaignId) external override onlyOwner {
Campaign storage _campaign = _campaigns[_campaignId];
require(_campaign.state == CampaignState.Paused, "ReferralLink: Invalid campaign id");
_campaign.state = CampaignState.Valid;
emit CampaignStateChanged(_campaignId, CampaignState.Valid);
}
| 23,151 |
71 | // put offer into the sorted list | function _sort(
uint id, //maker (ask) id
uint pos //position to insert into
)
internal
| function _sort(
uint id, //maker (ask) id
uint pos //position to insert into
)
internal
| 19,380 |
2 | // Data about users. | struct UserInfo {
uint256 periodsClaimed; // How many vesting periods the user has already claimed.
uint256 totalClaimable; // How many tokens the user is entitled to.
}
| struct UserInfo {
uint256 periodsClaimed; // How many vesting periods the user has already claimed.
uint256 totalClaimable; // How many tokens the user is entitled to.
}
| 27,316 |
21 | // Add a number to a base value. Detect overflows by checking the result is larger/than the original base value. | function safeIncrement(uint256 base, uint256 increment) private pure returns (uint256) {
uint256 result = base + increment;
if (result < base) revert();
return result;
}
| function safeIncrement(uint256 base, uint256 increment) private pure returns (uint256) {
uint256 result = base + increment;
if (result < base) revert();
return result;
}
| 10,136 |
0 | // controller version number | uint256 public constant VERSION_V2 = 2;
| uint256 public constant VERSION_V2 = 2;
| 47,256 |
12 | // require(oraclers[_delegatedTo].tokensLocked != uint256(0), "Delegated to has to have oracled already"); | oraclers[_delegatedTo].oraclesDelegatedByOthers = oraclers[_delegatedTo].oraclesDelegatedByOthers.add(_tokenAmount);
| oraclers[_delegatedTo].oraclesDelegatedByOthers = oraclers[_delegatedTo].oraclesDelegatedByOthers.add(_tokenAmount);
| 45,498 |
9 | // Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix. | IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0);
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap);
address[] memory path;
if (useEthPath) {
path = new address[](3);
path[0] = assetToSwapFrom;
path[1] = WETH_ADDRESS;
path[2] = assetToSwapTo;
} else {
| IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0);
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap);
address[] memory path;
if (useEthPath) {
path = new address[](3);
path[0] = assetToSwapFrom;
path[1] = WETH_ADDRESS;
path[2] = assetToSwapTo;
} else {
| 20,008 |
257 | // This contract implements the liquidity protection mechanism. / | contract LiquidityProtection is TokenHandler, Utils, Owned, ReentrancyGuard, Time {
using SafeMath for uint256;
using Math for *;
struct ProtectedLiquidity {
address provider; // liquidity provider
IDSToken poolToken; // pool token address
IERC20Token reserveToken; // reserve token address
uint256 poolAmount; // pool token amount
uint256 reserveAmount; // reserve token amount
uint256 reserveRateN; // rate of 1 protected reserve token in units of the other reserve token (numerator)
uint256 reserveRateD; // rate of 1 protected reserve token in units of the other reserve token (denominator)
uint256 timestamp; // timestamp
}
// various rates between the two reserve tokens. the rate is of 1 unit of the protected reserve token in units of the other reserve token
struct PackedRates {
uint128 addSpotRateN; // spot rate of 1 A in units of B when liquidity was added (numerator)
uint128 addSpotRateD; // spot rate of 1 A in units of B when liquidity was added (denominator)
uint128 removeSpotRateN; // spot rate of 1 A in units of B when liquidity is removed (numerator)
uint128 removeSpotRateD; // spot rate of 1 A in units of B when liquidity is removed (denominator)
uint128 removeAverageRateN; // average rate of 1 A in units of B when liquidity is removed (numerator)
uint128 removeAverageRateD; // average rate of 1 A in units of B when liquidity is removed (denominator)
}
IERC20Token internal constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
uint32 internal constant PPM_RESOLUTION = 1000000;
uint256 internal constant MAX_UINT128 = 2**128 - 1;
uint256 internal constant MAX_UINT256 = uint256(-1);
ILiquidityProtectionSettings public immutable settings;
ILiquidityProtectionStore public immutable store;
IERC20Token public immutable networkToken;
ITokenGovernance public immutable networkTokenGovernance;
IERC20Token public immutable govToken;
ITokenGovernance public immutable govTokenGovernance;
ICheckpointStore public immutable lastRemoveCheckpointStore;
// true if the contract is currently adding/removing liquidity from a converter, used for accepting ETH
bool private updatingLiquidity = false;
/**
* @dev initializes a new LiquidityProtection contract
*
* @param _settings liquidity protection settings
* @param _store liquidity protection store
* @param _networkTokenGovernance network token governance
* @param _govTokenGovernance governance token governance
* @param _lastRemoveCheckpointStore last liquidity removal/unprotection checkpoints store
*/
constructor(
ILiquidityProtectionSettings _settings,
ILiquidityProtectionStore _store,
ITokenGovernance _networkTokenGovernance,
ITokenGovernance _govTokenGovernance,
ICheckpointStore _lastRemoveCheckpointStore
)
public
validAddress(address(_settings))
validAddress(address(_store))
validAddress(address(_networkTokenGovernance))
validAddress(address(_govTokenGovernance))
notThis(address(_settings))
notThis(address(_store))
notThis(address(_networkTokenGovernance))
notThis(address(_govTokenGovernance))
{
settings = _settings;
store = _store;
networkTokenGovernance = _networkTokenGovernance;
networkToken = IERC20Token(address(_networkTokenGovernance.token()));
govTokenGovernance = _govTokenGovernance;
govToken = IERC20Token(address(_govTokenGovernance.token()));
lastRemoveCheckpointStore = _lastRemoveCheckpointStore;
}
// ensures that the contract is currently removing liquidity from a converter
modifier updatingLiquidityOnly() {
_updatingLiquidityOnly();
_;
}
// error message binary size optimization
function _updatingLiquidityOnly() internal view {
require(updatingLiquidity, "ERR_NOT_UPDATING_LIQUIDITY");
}
// ensures that the portion is valid
modifier validPortion(uint32 _portion) {
_validPortion(_portion);
_;
}
// error message binary size optimization
function _validPortion(uint32 _portion) internal pure {
require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION");
}
// ensures that the pool is supported
modifier poolSupported(IConverterAnchor _poolAnchor) {
_poolSupported(_poolAnchor);
_;
}
// error message binary size optimization
function _poolSupported(IConverterAnchor _poolAnchor) internal view {
require(settings.isPoolSupported(_poolAnchor), "ERR_POOL_NOT_SUPPORTED");
}
// ensures that the pool is whitelisted
modifier poolWhitelisted(IConverterAnchor _poolAnchor) {
_poolWhitelisted(_poolAnchor);
_;
}
// error message binary size optimization
function _poolWhitelisted(IConverterAnchor _poolAnchor) internal view {
require(settings.isPoolWhitelisted(_poolAnchor), "ERR_POOL_NOT_WHITELISTED");
}
/**
* @dev accept ETH
* used when removing liquidity from ETH converters
*/
receive() external payable updatingLiquidityOnly() {}
/**
* @dev transfers the ownership of the store
* can only be called by the contract owner
*
* @param _newOwner the new owner of the store
*/
function transferStoreOwnership(address _newOwner) external ownerOnly {
store.transferOwnership(_newOwner);
}
/**
* @dev accepts the ownership of the store
* can only be called by the contract owner
*/
function acceptStoreOwnership() external ownerOnly {
store.acceptOwnership();
}
/**
* @dev adds protection to existing pool tokens
* also mints new governance tokens for the caller
*
* @param _poolAnchor anchor of the pool
* @param _amount amount of pool tokens to protect
*/
function protectLiquidity(IConverterAnchor _poolAnchor, uint256 _amount)
external
protected
poolSupported(_poolAnchor)
poolWhitelisted(_poolAnchor)
greaterThanZero(_amount)
{
// get the converter
IConverter converter = IConverter(payable(ownedBy(_poolAnchor)));
// save a local copy of `networkToken`
IERC20Token networkTokenLocal = networkToken;
// protect both reserves
IDSToken poolToken = IDSToken(address(_poolAnchor));
protectLiquidity(poolToken, converter, networkTokenLocal, 0, _amount / 2);
protectLiquidity(poolToken, converter, networkTokenLocal, 1, _amount - _amount / 2);
// transfer the pool tokens from the caller directly to the store
safeTransferFrom(poolToken, msg.sender, address(store), _amount);
}
/**
* @dev cancels the protection and returns the pool tokens to the caller
* also burns governance tokens from the caller
* must be called with the indices of both the base token and the network token protections
*
* @param _id1 id in the caller's list of protected liquidity
* @param _id2 matching id in the caller's list of protected liquidity
*/
function unprotectLiquidity(uint256 _id1, uint256 _id2) external protected {
require(_id1 != _id2, "ERR_SAME_ID");
ProtectedLiquidity memory liquidity1 = protectedLiquidity(_id1, msg.sender);
ProtectedLiquidity memory liquidity2 = protectedLiquidity(_id2, msg.sender);
// save a local copy of `networkToken`
IERC20Token networkTokenLocal = networkToken;
// verify that the two protected liquidities were added together (using `protect`)
require(
liquidity1.poolToken == liquidity2.poolToken &&
liquidity1.reserveToken != liquidity2.reserveToken &&
(liquidity1.reserveToken == networkTokenLocal || liquidity2.reserveToken == networkTokenLocal) &&
liquidity1.timestamp == liquidity2.timestamp &&
liquidity1.poolAmount <= liquidity2.poolAmount.add(1) &&
liquidity2.poolAmount <= liquidity1.poolAmount.add(1),
"ERR_PROTECTIONS_MISMATCH"
);
// verify that the two protected liquidities are not removed on the same block in which they were added
require(liquidity1.timestamp < time(), "ERR_TOO_EARLY");
// burn the governance tokens from the caller. we need to transfer the tokens to the contract itself, since only
// token holders can burn their tokens
uint256 amount =
liquidity1.reserveToken == networkTokenLocal ? liquidity1.reserveAmount : liquidity2.reserveAmount;
safeTransferFrom(govToken, msg.sender, address(this), amount);
govTokenGovernance.burn(amount);
// update last liquidity removal checkpoint
lastRemoveCheckpointStore.addCheckpoint(msg.sender);
// remove the two protected liquidities from the provider
store.removeProtectedLiquidity(_id1);
store.removeProtectedLiquidity(_id2);
// transfer the pool tokens back to the caller
store.withdrawTokens(liquidity1.poolToken, msg.sender, liquidity1.poolAmount.add(liquidity2.poolAmount));
}
/**
* @dev adds protected liquidity to a pool for a specific recipient
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _reserveToken reserve token to add to the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addLiquidityFor(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _reserveToken,
uint256 _amount
)
external
payable
protected
validAddress(_owner)
poolSupported(_poolAnchor)
poolWhitelisted(_poolAnchor)
greaterThanZero(_amount)
returns (uint256)
{
return addLiquidity(_owner, _poolAnchor, _reserveToken, _amount);
}
/**
* @dev adds protected liquidity to a pool
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param _poolAnchor anchor of the pool
* @param _reserveToken reserve token to add to the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addLiquidity(
IConverterAnchor _poolAnchor,
IERC20Token _reserveToken,
uint256 _amount
)
external
payable
protected
poolSupported(_poolAnchor)
poolWhitelisted(_poolAnchor)
greaterThanZero(_amount)
returns (uint256)
{
return addLiquidity(msg.sender, _poolAnchor, _reserveToken, _amount);
}
/**
* @dev adds protected liquidity to a pool for a specific recipient
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _reserveToken reserve token to add to the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addLiquidity(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _reserveToken,
uint256 _amount
) private returns (uint256) {
// save a local copy of `networkToken`
IERC20Token networkTokenLocal = networkToken;
if (_reserveToken == networkTokenLocal) {
require(msg.value == 0, "ERR_ETH_AMOUNT_MISMATCH");
return addNetworkTokenLiquidity(_owner, _poolAnchor, networkTokenLocal, _amount);
}
// verify that ETH was passed with the call if needed
uint256 val = _reserveToken == ETH_RESERVE_ADDRESS ? _amount : 0;
require(msg.value == val, "ERR_ETH_AMOUNT_MISMATCH");
return addBaseTokenLiquidity(_owner, _poolAnchor, _reserveToken, networkTokenLocal, _amount);
}
/**
* @dev adds protected network token liquidity to a pool
* also mints new governance tokens for the caller
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _networkToken the network reserve token of the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addNetworkTokenLiquidity(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _networkToken,
uint256 _amount
) internal returns (uint256) {
IDSToken poolToken = IDSToken(address(_poolAnchor));
// get the rate between the pool token and the reserve
Fraction memory poolRate = poolTokenRate(poolToken, _networkToken);
// calculate the amount of pool tokens based on the amount of reserve tokens
uint256 poolTokenAmount = _amount.mul(poolRate.d).div(poolRate.n);
// remove the pool tokens from the system's ownership (will revert if not enough tokens are available)
store.decSystemBalance(poolToken, poolTokenAmount);
// add protected liquidity for the recipient
uint256 id = addProtectedLiquidity(_owner, poolToken, _networkToken, poolTokenAmount, _amount);
// burns the network tokens from the caller. we need to transfer the tokens to the contract itself, since only
// token holders can burn their tokens
safeTransferFrom(_networkToken, msg.sender, address(this), _amount);
networkTokenGovernance.burn(_amount);
settings.decNetworkTokensMinted(_poolAnchor, _amount);
// mint governance tokens to the recipient
govTokenGovernance.mint(_owner, _amount);
return id;
}
/**
* @dev adds protected base token liquidity to a pool
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _baseToken the base reserve token of the pool
* @param _networkToken the network reserve token of the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addBaseTokenLiquidity(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _baseToken,
IERC20Token _networkToken,
uint256 _amount
) internal returns (uint256) {
IDSToken poolToken = IDSToken(address(_poolAnchor));
// get the reserve balances
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor)));
(uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) =
converterReserveBalances(converter, _baseToken, _networkToken);
require(reserveBalanceNetwork >= settings.minNetworkTokenLiquidityForMinting(), "ERR_NOT_ENOUGH_LIQUIDITY");
// calculate and mint the required amount of network tokens for adding liquidity
uint256 newNetworkLiquidityAmount = _amount.mul(reserveBalanceNetwork).div(reserveBalanceBase);
// verify network token minting limit
uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor);
if (mintingLimit == 0) {
mintingLimit = settings.defaultNetworkTokenMintingLimit();
}
uint256 newNetworkTokensMinted = settings.networkTokensMinted(_poolAnchor).add(newNetworkLiquidityAmount);
require(newNetworkTokensMinted <= mintingLimit, "ERR_MAX_AMOUNT_REACHED");
// issue new network tokens to the system
networkTokenGovernance.mint(address(this), newNetworkLiquidityAmount);
settings.incNetworkTokensMinted(_poolAnchor, newNetworkLiquidityAmount);
// transfer the base tokens from the caller and approve the converter
ensureAllowance(_networkToken, address(converter), newNetworkLiquidityAmount);
if (_baseToken != ETH_RESERVE_ADDRESS) {
safeTransferFrom(_baseToken, msg.sender, address(this), _amount);
ensureAllowance(_baseToken, address(converter), _amount);
}
// add liquidity
addLiquidity(converter, _baseToken, _networkToken, _amount, newNetworkLiquidityAmount, msg.value);
// transfer the new pool tokens to the store
uint256 poolTokenAmount = poolToken.balanceOf(address(this));
safeTransfer(poolToken, address(store), poolTokenAmount);
// the system splits the pool tokens with the caller
// increase the system's pool token balance and add protected liquidity for the caller
store.incSystemBalance(poolToken, poolTokenAmount - poolTokenAmount / 2); // account for rounding errors
return addProtectedLiquidity(_owner, poolToken, _baseToken, poolTokenAmount / 2, _amount);
}
/**
* @dev returns the expected/actual amounts the provider will receive for removing liquidity
* it's also possible to provide the remove liquidity time to get an estimation
* for the return at that given point
*
* @param _id protected liquidity id
* @param _portion portion of liquidity to remove, in PPM
* @param _removeTimestamp time at which the liquidity is removed
* @return expected return amount in the reserve token
* @return actual return amount in the reserve token
* @return compensation in the network token
*/
function removeLiquidityReturn(
uint256 _id,
uint32 _portion,
uint256 _removeTimestamp
)
external
view
validPortion(_portion)
returns (
uint256,
uint256,
uint256
)
{
ProtectedLiquidity memory liquidity = protectedLiquidity(_id);
// verify input
require(liquidity.provider != address(0), "ERR_INVALID_ID");
require(_removeTimestamp >= liquidity.timestamp, "ERR_INVALID_TIMESTAMP");
// calculate the portion of the liquidity to remove
if (_portion != PPM_RESOLUTION) {
liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION;
liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION;
}
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates =
packRates(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.reserveRateN,
liquidity.reserveRateD,
false
);
uint256 targetAmount =
removeLiquidityTargetAmount(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
packedRates,
liquidity.timestamp,
_removeTimestamp
);
// for network token, the return amount is identical to the target amount
if (liquidity.reserveToken == networkToken) {
return (targetAmount, targetAmount, 0);
}
// handle base token return
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2);
// limit the amount of pool tokens by the amount the system/caller holds
uint256 availableBalance = store.systemBalance(liquidity.poolToken).add(liquidity.poolAmount);
poolAmount = poolAmount > availableBalance ? availableBalance : poolAmount;
// calculate the base token amount received by liquidating the pool tokens
// note that the amount is divided by 2 since the pool amount represents both reserves
uint256 baseAmount = poolAmount.mul(poolRate.n / 2).div(poolRate.d);
uint256 networkAmount = getNetworkCompensation(targetAmount, baseAmount, packedRates);
return (targetAmount, baseAmount, networkAmount);
}
/**
* @dev removes protected liquidity from a pool
* also burns governance tokens from the caller if the caller removes network tokens
*
* @param _id id in the caller's list of protected liquidity
* @param _portion portion of liquidity to remove, in PPM
*/
function removeLiquidity(uint256 _id, uint32 _portion) external validPortion(_portion) protected {
ProtectedLiquidity memory liquidity = protectedLiquidity(_id, msg.sender);
// save a local copy of `networkToken`
IERC20Token networkTokenLocal = networkToken;
// verify that the pool is whitelisted
_poolWhitelisted(liquidity.poolToken);
// verify that the protected liquidity is not removed on the same block in which it was added
require(liquidity.timestamp < time(), "ERR_TOO_EARLY");
if (_portion == PPM_RESOLUTION) {
// remove the protected liquidity from the provider
store.removeProtectedLiquidity(_id);
} else {
// remove a portion of the protected liquidity from the provider
uint256 fullPoolAmount = liquidity.poolAmount;
uint256 fullReserveAmount = liquidity.reserveAmount;
liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION;
liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION;
store.updateProtectedLiquidityAmounts(
_id,
fullPoolAmount - liquidity.poolAmount,
fullReserveAmount - liquidity.reserveAmount
);
}
// update last liquidity removal checkpoint
lastRemoveCheckpointStore.addCheckpoint(msg.sender);
// add the pool tokens to the system
store.incSystemBalance(liquidity.poolToken, liquidity.poolAmount);
// if removing network token liquidity, burn the governance tokens from the caller. we need to transfer the
// tokens to the contract itself, since only token holders can burn their tokens
if (liquidity.reserveToken == networkTokenLocal) {
safeTransferFrom(govToken, msg.sender, address(this), liquidity.reserveAmount);
govTokenGovernance.burn(liquidity.reserveAmount);
}
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates =
packRates(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.reserveRateN,
liquidity.reserveRateD,
true
);
// get the target token amount
uint256 targetAmount =
removeLiquidityTargetAmount(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
packedRates,
liquidity.timestamp,
time()
);
// remove network token liquidity
if (liquidity.reserveToken == networkTokenLocal) {
// mint network tokens for the caller and lock them
networkTokenGovernance.mint(address(store), targetAmount);
settings.incNetworkTokensMinted(liquidity.poolToken, targetAmount);
lockTokens(msg.sender, targetAmount);
return;
}
// remove base token liquidity
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2);
// limit the amount of pool tokens by the amount the system holds
uint256 systemBalance = store.systemBalance(liquidity.poolToken);
poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount;
// withdraw the pool tokens from the store
store.decSystemBalance(liquidity.poolToken, poolAmount);
store.withdrawTokens(liquidity.poolToken, address(this), poolAmount);
// remove liquidity
removeLiquidity(liquidity.poolToken, poolAmount, liquidity.reserveToken, networkTokenLocal);
// transfer the base tokens to the caller
uint256 baseBalance;
if (liquidity.reserveToken == ETH_RESERVE_ADDRESS) {
baseBalance = address(this).balance;
msg.sender.transfer(baseBalance);
} else {
baseBalance = liquidity.reserveToken.balanceOf(address(this));
safeTransfer(liquidity.reserveToken, msg.sender, baseBalance);
}
// compensate the caller with network tokens if still needed
uint256 delta = getNetworkCompensation(targetAmount, baseBalance, packedRates);
if (delta > 0) {
// check if there's enough network token balance, otherwise mint more
uint256 networkBalance = networkTokenLocal.balanceOf(address(this));
if (networkBalance < delta) {
networkTokenGovernance.mint(address(this), delta - networkBalance);
}
// lock network tokens for the caller
safeTransfer(networkTokenLocal, address(store), delta);
lockTokens(msg.sender, delta);
}
// if the contract still holds network tokens, burn them
uint256 networkBalance = networkTokenLocal.balanceOf(address(this));
if (networkBalance > 0) {
networkTokenGovernance.burn(networkBalance);
settings.decNetworkTokensMinted(liquidity.poolToken, networkBalance);
}
}
/**
* @dev returns the amount the provider will receive for removing liquidity
* it's also possible to provide the remove liquidity rate & time to get an estimation
* for the return at that given point
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _poolAmount pool token amount when the liquidity was added
* @param _reserveAmount reserve token amount that was added
* @param _packedRates see `struct PackedRates`
* @param _addTimestamp time at which the liquidity was added
* @param _removeTimestamp time at which the liquidity is removed
* @return amount received for removing liquidity
*/
function removeLiquidityTargetAmount(
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount,
PackedRates memory _packedRates,
uint256 _addTimestamp,
uint256 _removeTimestamp
) internal view returns (uint256) {
// get the rate between the pool token and the reserve token
Fraction memory poolRate = poolTokenRate(_poolToken, _reserveToken);
// get the rate between the reserves upon adding liquidity and now
Fraction memory addSpotRate = Fraction({ n: _packedRates.addSpotRateN, d: _packedRates.addSpotRateD });
Fraction memory removeSpotRate = Fraction({ n: _packedRates.removeSpotRateN, d: _packedRates.removeSpotRateD });
Fraction memory removeAverageRate =
Fraction({ n: _packedRates.removeAverageRateN, d: _packedRates.removeAverageRateD });
// calculate the protected amount of reserve tokens plus accumulated fee before compensation
uint256 total = protectedAmountPlusFee(_poolAmount, poolRate, addSpotRate, removeSpotRate);
// calculate the impermanent loss
Fraction memory loss = impLoss(addSpotRate, removeAverageRate);
// calculate the protection level
Fraction memory level = protectionLevel(_addTimestamp, _removeTimestamp);
// calculate the compensation amount
return compensationAmount(_reserveAmount, Math.max(_reserveAmount, total), loss, level);
}
/**
* @dev allows the caller to claim network token balance that is no longer locked
* note that the function can revert if the range is too large
*
* @param _startIndex start index in the caller's list of locked balances
* @param _endIndex end index in the caller's list of locked balances (exclusive)
*/
function claimBalance(uint256 _startIndex, uint256 _endIndex) external protected {
// get the locked balances from the store
(uint256[] memory amounts, uint256[] memory expirationTimes) =
store.lockedBalanceRange(msg.sender, _startIndex, _endIndex);
uint256 totalAmount = 0;
uint256 length = amounts.length;
assert(length == expirationTimes.length);
// 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;
}
// remove the locked balance item
store.removeLockedBalance(msg.sender, _startIndex + index);
totalAmount = totalAmount.add(amounts[index]);
}
if (totalAmount > 0) {
// transfer the tokens to the caller in a single call
store.withdrawTokens(networkToken, msg.sender, totalAmount);
}
}
/**
* @dev returns the ROI for removing liquidity in the current state after providing liquidity with the given args
* the function assumes full protection is in effect
* return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _reserveAmount reserve token amount that was added
* @param _poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator)
* @param _poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator)
* @param _reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator)
* @param _reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator)
* @return ROI in PPM
*/
function poolROI(
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _reserveAmount,
uint256 _poolRateN,
uint256 _poolRateD,
uint256 _reserveRateN,
uint256 _reserveRateD
) external view returns (uint256) {
// calculate the amount of pool tokens based on the amount of reserve tokens
uint256 poolAmount = _reserveAmount.mul(_poolRateD).div(_poolRateN);
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates = packRates(_poolToken, _reserveToken, _reserveRateN, _reserveRateD, false);
// get the current return
uint256 protectedReturn =
removeLiquidityTargetAmount(
_poolToken,
_reserveToken,
poolAmount,
_reserveAmount,
packedRates,
time().sub(settings.maxProtectionDelay()),
time()
);
// calculate the ROI as the ratio between the current fully protected return and the initial amount
return protectedReturn.mul(PPM_RESOLUTION).div(_reserveAmount);
}
/**
* @dev utility to protect existing liquidity
* also mints new governance tokens for the caller when protecting the network token reserve
*
* @param _poolAnchor pool anchor
* @param _converter pool converter
* @param _networkToken the network reserve token of the pool
* @param _reserveIndex index of the reserve to protect
* @param _poolAmount amount of pool tokens to protect
*/
function protectLiquidity(
IDSToken _poolAnchor,
IConverter _converter,
IERC20Token _networkToken,
uint256 _reserveIndex,
uint256 _poolAmount
) internal {
// get the reserves token
IERC20Token reserveToken = _converter.connectorTokens(_reserveIndex);
// get the pool token rate
IDSToken poolToken = IDSToken(address(_poolAnchor));
Fraction memory poolRate = poolTokenRate(poolToken, reserveToken);
// calculate the reserve balance based on the amount provided and the pool token rate
uint256 reserveAmount = _poolAmount.mul(poolRate.n).div(poolRate.d);
// protect the liquidity
addProtectedLiquidity(msg.sender, poolToken, reserveToken, _poolAmount, reserveAmount);
// for network token liquidity, mint governance tokens to the caller
if (reserveToken == _networkToken) {
govTokenGovernance.mint(msg.sender, reserveAmount);
}
}
/**
* @dev adds protected liquidity for the caller to the store
*
* @param _provider protected liquidity provider
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _poolAmount amount of pool tokens to protect
* @param _reserveAmount amount of reserve tokens to protect
* @return new protected liquidity id
*/
function addProtectedLiquidity(
address _provider,
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount
) internal returns (uint256) {
Fraction memory rate = reserveTokenAverageRate(_poolToken, _reserveToken, true);
return
store.addProtectedLiquidity(
_provider,
_poolToken,
_reserveToken,
_poolAmount,
_reserveAmount,
rate.n,
rate.d,
time()
);
}
/**
* @dev locks network tokens for the provider and emits the tokens locked event
*
* @param _provider tokens provider
* @param _amount amount of network tokens
*/
function lockTokens(address _provider, uint256 _amount) internal {
uint256 expirationTime = time().add(settings.lockDuration());
store.addLockedBalance(_provider, _amount, expirationTime);
}
/**
* @dev returns the rate of 1 pool token in reserve token units
*
* @param _poolToken pool token
* @param _reserveToken reserve token
*/
function poolTokenRate(IDSToken _poolToken, IERC20Token _reserveToken) internal view virtual returns (Fraction memory) {
// get the pool token supply
uint256 poolTokenSupply = _poolToken.totalSupply();
// get the reserve balance
IConverter converter = IConverter(payable(ownedBy(_poolToken)));
uint256 reserveBalance = converter.getConnectorBalance(_reserveToken);
// for standard pools, 50% of the pool supply value equals the value of each reserve
return Fraction({ n: reserveBalance.mul(2), d: poolTokenSupply });
}
/**
* @dev returns the average rate of 1 reserve token in the other reserve token units
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _validateAverageRate true to validate the average rate; false otherwise
*/
function reserveTokenAverageRate(
IDSToken _poolToken,
IERC20Token _reserveToken,
bool _validateAverageRate
) internal view returns (Fraction memory) {
(, , uint256 averageRateN, uint256 averageRateD) =
reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate);
return Fraction(averageRateN, averageRateD);
}
/**
* @dev returns the spot rate and average rate of 1 reserve token in the other reserve token units
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _validateAverageRate true to validate the average rate; false otherwise
*/
function reserveTokenRates(
IDSToken _poolToken,
IERC20Token _reserveToken,
bool _validateAverageRate
)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken)));
IERC20Token otherReserve = converter.connectorTokens(0);
if (otherReserve == _reserveToken) {
otherReserve = converter.connectorTokens(1);
}
(uint256 spotRateN, uint256 spotRateD) = converterReserveBalances(converter, otherReserve, _reserveToken);
(uint256 averageRateN, uint256 averageRateD) = converter.recentAverageRate(_reserveToken);
require(
!_validateAverageRate ||
averageRateInRange(
spotRateN,
spotRateD,
averageRateN,
averageRateD,
settings.averageRateMaxDeviation()
),
"ERR_INVALID_RATE"
);
return (spotRateN, spotRateD, averageRateN, averageRateD);
}
/**
* @dev returns the various rates between the reserves
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _addSpotRateN add spot rate numerator
* @param _addSpotRateD add spot rate denominator
* @param _validateAverageRate true to validate the average rate; false otherwise
* @return see `struct PackedRates`
*/
function packRates(
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _addSpotRateN,
uint256 _addSpotRateD,
bool _validateAverageRate
) internal view returns (PackedRates memory) {
(uint256 removeSpotRateN, uint256 removeSpotRateD, uint256 removeAverageRateN, uint256 removeAverageRateD) =
reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate);
require(
(_addSpotRateN <= MAX_UINT128 && _addSpotRateD <= MAX_UINT128) &&
(removeSpotRateN <= MAX_UINT128 && removeSpotRateD <= MAX_UINT128) &&
(removeAverageRateN <= MAX_UINT128 && removeAverageRateD <= MAX_UINT128),
"ERR_INVALID_RATE"
);
return
PackedRates({
addSpotRateN: uint128(_addSpotRateN),
addSpotRateD: uint128(_addSpotRateD),
removeSpotRateN: uint128(removeSpotRateN),
removeSpotRateD: uint128(removeSpotRateD),
removeAverageRateN: uint128(removeAverageRateN),
removeAverageRateD: uint128(removeAverageRateD)
});
}
/**
* @dev returns whether or not the deviation of the average rate from the spot rate is within range
* for example, if the maximum permitted deviation is 5%, then return `95/100 <= average/spot <= 100/95`
*
* @param _spotRateN spot rate numerator
* @param _spotRateD spot rate denominator
* @param _averageRateN average rate numerator
* @param _averageRateD average rate denominator
* @param _maxDeviation the maximum permitted deviation of the average rate from the spot rate
*/
function averageRateInRange(
uint256 _spotRateN,
uint256 _spotRateD,
uint256 _averageRateN,
uint256 _averageRateD,
uint32 _maxDeviation
) internal pure returns (bool) {
uint256 min =
_spotRateN.mul(_averageRateD).mul(PPM_RESOLUTION - _maxDeviation).mul(PPM_RESOLUTION - _maxDeviation);
uint256 mid = _spotRateD.mul(_averageRateN).mul(PPM_RESOLUTION - _maxDeviation).mul(PPM_RESOLUTION);
uint256 max = _spotRateN.mul(_averageRateD).mul(PPM_RESOLUTION).mul(PPM_RESOLUTION);
return min <= mid && mid <= max;
}
/**
* @dev utility to add liquidity to a converter
*
* @param _converter converter
* @param _reserveToken1 reserve token 1
* @param _reserveToken2 reserve token 2
* @param _reserveAmount1 reserve amount 1
* @param _reserveAmount2 reserve amount 2
* @param _value ETH amount to add
*/
function addLiquidity(
ILiquidityPoolConverter _converter,
IERC20Token _reserveToken1,
IERC20Token _reserveToken2,
uint256 _reserveAmount1,
uint256 _reserveAmount2,
uint256 _value
) internal {
// ensure that the contract can receive ETH
updatingLiquidity = true;
IERC20Token[] memory reserveTokens = new IERC20Token[](2);
uint256[] memory amounts = new uint256[](2);
reserveTokens[0] = _reserveToken1;
reserveTokens[1] = _reserveToken2;
amounts[0] = _reserveAmount1;
amounts[1] = _reserveAmount2;
_converter.addLiquidity{ value: _value }(reserveTokens, amounts, 1);
// ensure that the contract can receive ETH
updatingLiquidity = false;
}
/**
* @dev utility to remove liquidity from a converter
*
* @param _poolToken pool token of the converter
* @param _poolAmount amount of pool tokens to remove
* @param _reserveToken1 reserve token 1
* @param _reserveToken2 reserve token 2
*/
function removeLiquidity(
IDSToken _poolToken,
uint256 _poolAmount,
IERC20Token _reserveToken1,
IERC20Token _reserveToken2
) internal {
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken)));
// ensure that the contract can receive ETH
updatingLiquidity = true;
IERC20Token[] memory reserveTokens = new IERC20Token[](2);
uint256[] memory minReturns = new uint256[](2);
reserveTokens[0] = _reserveToken1;
reserveTokens[1] = _reserveToken2;
minReturns[0] = 1;
minReturns[1] = 1;
converter.removeLiquidity(_poolAmount, reserveTokens, minReturns);
// ensure that the contract can receive ETH
updatingLiquidity = false;
}
/**
* @dev returns a protected liquidity from the store
*
* @param _id protected liquidity id
* @return protected liquidity
*/
function protectedLiquidity(uint256 _id) internal view returns (ProtectedLiquidity memory) {
ProtectedLiquidity memory liquidity;
(
liquidity.provider,
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
liquidity.reserveRateN,
liquidity.reserveRateD,
liquidity.timestamp
) = store.protectedLiquidity(_id);
return liquidity;
}
/**
* @dev returns a protected liquidity from the store
*
* @param _id protected liquidity id
* @param _provider authorized provider
* @return protected liquidity
*/
function protectedLiquidity(uint256 _id, address _provider) internal view returns (ProtectedLiquidity memory) {
ProtectedLiquidity memory liquidity = protectedLiquidity(_id);
require(liquidity.provider == _provider, "ERR_ACCESS_DENIED");
return liquidity;
}
/**
* @dev returns the protected amount of reserve tokens plus accumulated fee before compensation
*
* @param _poolAmount pool token amount when the liquidity was added
* @param _poolRate rate of 1 pool token in the related reserve token units
* @param _addRate rate of 1 reserve token in the other reserve token units when the liquidity was added
* @param _removeRate rate of 1 reserve token in the other reserve token units when the liquidity is removed
* @return protected amount of reserve tokens plus accumulated fee = sqrt(_removeRate / _addRate) * _poolRate * _poolAmount
*/
function protectedAmountPlusFee(
uint256 _poolAmount,
Fraction memory _poolRate,
Fraction memory _addRate,
Fraction memory _removeRate
) internal pure returns (uint256) {
uint256 n = Math.ceilSqrt(_addRate.d.mul(_removeRate.n)).mul(_poolRate.n);
uint256 d = Math.floorSqrt(_addRate.n.mul(_removeRate.d)).mul(_poolRate.d);
uint256 x = n * _poolAmount;
if (x / n == _poolAmount) {
return x / d;
}
(uint256 hi, uint256 lo) = n > _poolAmount ? (n, _poolAmount) : (_poolAmount, n);
(uint256 p, uint256 q) = Math.reducedRatio(hi, d, MAX_UINT256 / lo);
uint256 min = (hi / d).mul(lo);
if (q > 0) {
return Math.max(min, p * lo / q);
}
return min;
}
/**
* @dev returns the impermanent loss incurred due to the change in rates between the reserve tokens
*
* @param _prevRate previous rate between the reserves
* @param _newRate new rate between the reserves
* @return impermanent loss (as a ratio)
*/
function impLoss(Fraction memory _prevRate, Fraction memory _newRate) internal pure returns (Fraction memory) {
uint256 ratioN = _newRate.n.mul(_prevRate.d);
uint256 ratioD = _newRate.d.mul(_prevRate.n);
uint256 prod = ratioN * ratioD;
uint256 root = prod / ratioN == ratioD ? Math.floorSqrt(prod) : Math.floorSqrt(ratioN) * Math.floorSqrt(ratioD);
uint256 sum = ratioN.add(ratioD);
// the arithmetic below is safe because `x + y >= sqrt(x * y) * 2`
if (sum % 2 == 0) {
sum /= 2;
return Fraction({ n: sum - root, d: sum });
}
return Fraction({ n: sum - root * 2, d: sum });
}
/**
* @dev returns the protection level based on the timestamp and protection delays
*
* @param _addTimestamp time at which the liquidity was added
* @param _removeTimestamp time at which the liquidity is removed
* @return protection level (as a ratio)
*/
function protectionLevel(uint256 _addTimestamp, uint256 _removeTimestamp) internal view returns (Fraction memory) {
uint256 timeElapsed = _removeTimestamp.sub(_addTimestamp);
uint256 minProtectionDelay = settings.minProtectionDelay();
uint256 maxProtectionDelay = settings.maxProtectionDelay();
if (timeElapsed < minProtectionDelay) {
return Fraction({ n: 0, d: 1 });
}
if (timeElapsed >= maxProtectionDelay) {
return Fraction({ n: 1, d: 1 });
}
return Fraction({ n: timeElapsed, d: maxProtectionDelay });
}
/**
* @dev returns the compensation amount based on the impermanent loss and the protection level
*
* @param _amount protected amount in units of the reserve token
* @param _total amount plus fee in units of the reserve token
* @param _loss protection level (as a ratio between 0 and 1)
* @param _level impermanent loss (as a ratio between 0 and 1)
* @return compensation amount
*/
function compensationAmount(
uint256 _amount,
uint256 _total,
Fraction memory _loss,
Fraction memory _level
) internal pure returns (uint256) {
uint256 levelN = _level.n.mul(_amount);
uint256 levelD = _level.d;
uint256 maxVal = Math.max(Math.max(levelN, levelD), _total);
(uint256 lossN, uint256 lossD) = Math.reducedRatio(_loss.n, _loss.d, MAX_UINT256 / maxVal);
return _total.mul(lossD.sub(lossN)).div(lossD).add(lossN.mul(levelN).div(lossD.mul(levelD)));
}
function getNetworkCompensation(
uint256 _targetAmount,
uint256 _baseAmount,
PackedRates memory _packedRates
) internal view returns (uint256) {
if (_targetAmount <= _baseAmount) {
return 0;
}
// calculate the delta in network tokens
uint256 delta =
(_targetAmount - _baseAmount).mul(_packedRates.removeAverageRateN).div(_packedRates.removeAverageRateD);
// the delta might be very small due to precision loss
// in which case no compensation will take place (gas optimization)
if (delta >= settings.minNetworkCompensation()) {
return delta;
}
return 0;
}
/**
* @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't.
* note that we use the non standard erc-20 interface in which `approve` has no return value so that
* this function will work for both standard and non standard tokens
*
* @param _token token to check the allowance in
* @param _spender approved address
* @param _value allowance amount
*/
function ensureAllowance(
IERC20Token _token,
address _spender,
uint256 _value
) private {
uint256 allowance = _token.allowance(address(this), _spender);
if (allowance < _value) {
if (allowance > 0) safeApprove(_token, _spender, 0);
safeApprove(_token, _spender, _value);
}
}
// utility to get the reserve balances
function converterReserveBalances(
IConverter _converter,
IERC20Token _reserveToken1,
IERC20Token _reserveToken2
) private view returns (uint256, uint256) {
return (_converter.getConnectorBalance(_reserveToken1), _converter.getConnectorBalance(_reserveToken2));
}
// utility to get the owner
function ownedBy(IOwned _owned) private view returns (address) {
return _owned.owner();
}
}
| contract LiquidityProtection is TokenHandler, Utils, Owned, ReentrancyGuard, Time {
using SafeMath for uint256;
using Math for *;
struct ProtectedLiquidity {
address provider; // liquidity provider
IDSToken poolToken; // pool token address
IERC20Token reserveToken; // reserve token address
uint256 poolAmount; // pool token amount
uint256 reserveAmount; // reserve token amount
uint256 reserveRateN; // rate of 1 protected reserve token in units of the other reserve token (numerator)
uint256 reserveRateD; // rate of 1 protected reserve token in units of the other reserve token (denominator)
uint256 timestamp; // timestamp
}
// various rates between the two reserve tokens. the rate is of 1 unit of the protected reserve token in units of the other reserve token
struct PackedRates {
uint128 addSpotRateN; // spot rate of 1 A in units of B when liquidity was added (numerator)
uint128 addSpotRateD; // spot rate of 1 A in units of B when liquidity was added (denominator)
uint128 removeSpotRateN; // spot rate of 1 A in units of B when liquidity is removed (numerator)
uint128 removeSpotRateD; // spot rate of 1 A in units of B when liquidity is removed (denominator)
uint128 removeAverageRateN; // average rate of 1 A in units of B when liquidity is removed (numerator)
uint128 removeAverageRateD; // average rate of 1 A in units of B when liquidity is removed (denominator)
}
IERC20Token internal constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
uint32 internal constant PPM_RESOLUTION = 1000000;
uint256 internal constant MAX_UINT128 = 2**128 - 1;
uint256 internal constant MAX_UINT256 = uint256(-1);
ILiquidityProtectionSettings public immutable settings;
ILiquidityProtectionStore public immutable store;
IERC20Token public immutable networkToken;
ITokenGovernance public immutable networkTokenGovernance;
IERC20Token public immutable govToken;
ITokenGovernance public immutable govTokenGovernance;
ICheckpointStore public immutable lastRemoveCheckpointStore;
// true if the contract is currently adding/removing liquidity from a converter, used for accepting ETH
bool private updatingLiquidity = false;
/**
* @dev initializes a new LiquidityProtection contract
*
* @param _settings liquidity protection settings
* @param _store liquidity protection store
* @param _networkTokenGovernance network token governance
* @param _govTokenGovernance governance token governance
* @param _lastRemoveCheckpointStore last liquidity removal/unprotection checkpoints store
*/
constructor(
ILiquidityProtectionSettings _settings,
ILiquidityProtectionStore _store,
ITokenGovernance _networkTokenGovernance,
ITokenGovernance _govTokenGovernance,
ICheckpointStore _lastRemoveCheckpointStore
)
public
validAddress(address(_settings))
validAddress(address(_store))
validAddress(address(_networkTokenGovernance))
validAddress(address(_govTokenGovernance))
notThis(address(_settings))
notThis(address(_store))
notThis(address(_networkTokenGovernance))
notThis(address(_govTokenGovernance))
{
settings = _settings;
store = _store;
networkTokenGovernance = _networkTokenGovernance;
networkToken = IERC20Token(address(_networkTokenGovernance.token()));
govTokenGovernance = _govTokenGovernance;
govToken = IERC20Token(address(_govTokenGovernance.token()));
lastRemoveCheckpointStore = _lastRemoveCheckpointStore;
}
// ensures that the contract is currently removing liquidity from a converter
modifier updatingLiquidityOnly() {
_updatingLiquidityOnly();
_;
}
// error message binary size optimization
function _updatingLiquidityOnly() internal view {
require(updatingLiquidity, "ERR_NOT_UPDATING_LIQUIDITY");
}
// ensures that the portion is valid
modifier validPortion(uint32 _portion) {
_validPortion(_portion);
_;
}
// error message binary size optimization
function _validPortion(uint32 _portion) internal pure {
require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION");
}
// ensures that the pool is supported
modifier poolSupported(IConverterAnchor _poolAnchor) {
_poolSupported(_poolAnchor);
_;
}
// error message binary size optimization
function _poolSupported(IConverterAnchor _poolAnchor) internal view {
require(settings.isPoolSupported(_poolAnchor), "ERR_POOL_NOT_SUPPORTED");
}
// ensures that the pool is whitelisted
modifier poolWhitelisted(IConverterAnchor _poolAnchor) {
_poolWhitelisted(_poolAnchor);
_;
}
// error message binary size optimization
function _poolWhitelisted(IConverterAnchor _poolAnchor) internal view {
require(settings.isPoolWhitelisted(_poolAnchor), "ERR_POOL_NOT_WHITELISTED");
}
/**
* @dev accept ETH
* used when removing liquidity from ETH converters
*/
receive() external payable updatingLiquidityOnly() {}
/**
* @dev transfers the ownership of the store
* can only be called by the contract owner
*
* @param _newOwner the new owner of the store
*/
function transferStoreOwnership(address _newOwner) external ownerOnly {
store.transferOwnership(_newOwner);
}
/**
* @dev accepts the ownership of the store
* can only be called by the contract owner
*/
function acceptStoreOwnership() external ownerOnly {
store.acceptOwnership();
}
/**
* @dev adds protection to existing pool tokens
* also mints new governance tokens for the caller
*
* @param _poolAnchor anchor of the pool
* @param _amount amount of pool tokens to protect
*/
function protectLiquidity(IConverterAnchor _poolAnchor, uint256 _amount)
external
protected
poolSupported(_poolAnchor)
poolWhitelisted(_poolAnchor)
greaterThanZero(_amount)
{
// get the converter
IConverter converter = IConverter(payable(ownedBy(_poolAnchor)));
// save a local copy of `networkToken`
IERC20Token networkTokenLocal = networkToken;
// protect both reserves
IDSToken poolToken = IDSToken(address(_poolAnchor));
protectLiquidity(poolToken, converter, networkTokenLocal, 0, _amount / 2);
protectLiquidity(poolToken, converter, networkTokenLocal, 1, _amount - _amount / 2);
// transfer the pool tokens from the caller directly to the store
safeTransferFrom(poolToken, msg.sender, address(store), _amount);
}
/**
* @dev cancels the protection and returns the pool tokens to the caller
* also burns governance tokens from the caller
* must be called with the indices of both the base token and the network token protections
*
* @param _id1 id in the caller's list of protected liquidity
* @param _id2 matching id in the caller's list of protected liquidity
*/
function unprotectLiquidity(uint256 _id1, uint256 _id2) external protected {
require(_id1 != _id2, "ERR_SAME_ID");
ProtectedLiquidity memory liquidity1 = protectedLiquidity(_id1, msg.sender);
ProtectedLiquidity memory liquidity2 = protectedLiquidity(_id2, msg.sender);
// save a local copy of `networkToken`
IERC20Token networkTokenLocal = networkToken;
// verify that the two protected liquidities were added together (using `protect`)
require(
liquidity1.poolToken == liquidity2.poolToken &&
liquidity1.reserveToken != liquidity2.reserveToken &&
(liquidity1.reserveToken == networkTokenLocal || liquidity2.reserveToken == networkTokenLocal) &&
liquidity1.timestamp == liquidity2.timestamp &&
liquidity1.poolAmount <= liquidity2.poolAmount.add(1) &&
liquidity2.poolAmount <= liquidity1.poolAmount.add(1),
"ERR_PROTECTIONS_MISMATCH"
);
// verify that the two protected liquidities are not removed on the same block in which they were added
require(liquidity1.timestamp < time(), "ERR_TOO_EARLY");
// burn the governance tokens from the caller. we need to transfer the tokens to the contract itself, since only
// token holders can burn their tokens
uint256 amount =
liquidity1.reserveToken == networkTokenLocal ? liquidity1.reserveAmount : liquidity2.reserveAmount;
safeTransferFrom(govToken, msg.sender, address(this), amount);
govTokenGovernance.burn(amount);
// update last liquidity removal checkpoint
lastRemoveCheckpointStore.addCheckpoint(msg.sender);
// remove the two protected liquidities from the provider
store.removeProtectedLiquidity(_id1);
store.removeProtectedLiquidity(_id2);
// transfer the pool tokens back to the caller
store.withdrawTokens(liquidity1.poolToken, msg.sender, liquidity1.poolAmount.add(liquidity2.poolAmount));
}
/**
* @dev adds protected liquidity to a pool for a specific recipient
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _reserveToken reserve token to add to the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addLiquidityFor(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _reserveToken,
uint256 _amount
)
external
payable
protected
validAddress(_owner)
poolSupported(_poolAnchor)
poolWhitelisted(_poolAnchor)
greaterThanZero(_amount)
returns (uint256)
{
return addLiquidity(_owner, _poolAnchor, _reserveToken, _amount);
}
/**
* @dev adds protected liquidity to a pool
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param _poolAnchor anchor of the pool
* @param _reserveToken reserve token to add to the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addLiquidity(
IConverterAnchor _poolAnchor,
IERC20Token _reserveToken,
uint256 _amount
)
external
payable
protected
poolSupported(_poolAnchor)
poolWhitelisted(_poolAnchor)
greaterThanZero(_amount)
returns (uint256)
{
return addLiquidity(msg.sender, _poolAnchor, _reserveToken, _amount);
}
/**
* @dev adds protected liquidity to a pool for a specific recipient
* also mints new governance tokens for the caller if the caller adds network tokens
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _reserveToken reserve token to add to the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addLiquidity(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _reserveToken,
uint256 _amount
) private returns (uint256) {
// save a local copy of `networkToken`
IERC20Token networkTokenLocal = networkToken;
if (_reserveToken == networkTokenLocal) {
require(msg.value == 0, "ERR_ETH_AMOUNT_MISMATCH");
return addNetworkTokenLiquidity(_owner, _poolAnchor, networkTokenLocal, _amount);
}
// verify that ETH was passed with the call if needed
uint256 val = _reserveToken == ETH_RESERVE_ADDRESS ? _amount : 0;
require(msg.value == val, "ERR_ETH_AMOUNT_MISMATCH");
return addBaseTokenLiquidity(_owner, _poolAnchor, _reserveToken, networkTokenLocal, _amount);
}
/**
* @dev adds protected network token liquidity to a pool
* also mints new governance tokens for the caller
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _networkToken the network reserve token of the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addNetworkTokenLiquidity(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _networkToken,
uint256 _amount
) internal returns (uint256) {
IDSToken poolToken = IDSToken(address(_poolAnchor));
// get the rate between the pool token and the reserve
Fraction memory poolRate = poolTokenRate(poolToken, _networkToken);
// calculate the amount of pool tokens based on the amount of reserve tokens
uint256 poolTokenAmount = _amount.mul(poolRate.d).div(poolRate.n);
// remove the pool tokens from the system's ownership (will revert if not enough tokens are available)
store.decSystemBalance(poolToken, poolTokenAmount);
// add protected liquidity for the recipient
uint256 id = addProtectedLiquidity(_owner, poolToken, _networkToken, poolTokenAmount, _amount);
// burns the network tokens from the caller. we need to transfer the tokens to the contract itself, since only
// token holders can burn their tokens
safeTransferFrom(_networkToken, msg.sender, address(this), _amount);
networkTokenGovernance.burn(_amount);
settings.decNetworkTokensMinted(_poolAnchor, _amount);
// mint governance tokens to the recipient
govTokenGovernance.mint(_owner, _amount);
return id;
}
/**
* @dev adds protected base token liquidity to a pool
*
* @param _owner protected liquidity owner
* @param _poolAnchor anchor of the pool
* @param _baseToken the base reserve token of the pool
* @param _networkToken the network reserve token of the pool
* @param _amount amount of tokens to add to the pool
* @return new protected liquidity id
*/
function addBaseTokenLiquidity(
address _owner,
IConverterAnchor _poolAnchor,
IERC20Token _baseToken,
IERC20Token _networkToken,
uint256 _amount
) internal returns (uint256) {
IDSToken poolToken = IDSToken(address(_poolAnchor));
// get the reserve balances
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolAnchor)));
(uint256 reserveBalanceBase, uint256 reserveBalanceNetwork) =
converterReserveBalances(converter, _baseToken, _networkToken);
require(reserveBalanceNetwork >= settings.minNetworkTokenLiquidityForMinting(), "ERR_NOT_ENOUGH_LIQUIDITY");
// calculate and mint the required amount of network tokens for adding liquidity
uint256 newNetworkLiquidityAmount = _amount.mul(reserveBalanceNetwork).div(reserveBalanceBase);
// verify network token minting limit
uint256 mintingLimit = settings.networkTokenMintingLimits(_poolAnchor);
if (mintingLimit == 0) {
mintingLimit = settings.defaultNetworkTokenMintingLimit();
}
uint256 newNetworkTokensMinted = settings.networkTokensMinted(_poolAnchor).add(newNetworkLiquidityAmount);
require(newNetworkTokensMinted <= mintingLimit, "ERR_MAX_AMOUNT_REACHED");
// issue new network tokens to the system
networkTokenGovernance.mint(address(this), newNetworkLiquidityAmount);
settings.incNetworkTokensMinted(_poolAnchor, newNetworkLiquidityAmount);
// transfer the base tokens from the caller and approve the converter
ensureAllowance(_networkToken, address(converter), newNetworkLiquidityAmount);
if (_baseToken != ETH_RESERVE_ADDRESS) {
safeTransferFrom(_baseToken, msg.sender, address(this), _amount);
ensureAllowance(_baseToken, address(converter), _amount);
}
// add liquidity
addLiquidity(converter, _baseToken, _networkToken, _amount, newNetworkLiquidityAmount, msg.value);
// transfer the new pool tokens to the store
uint256 poolTokenAmount = poolToken.balanceOf(address(this));
safeTransfer(poolToken, address(store), poolTokenAmount);
// the system splits the pool tokens with the caller
// increase the system's pool token balance and add protected liquidity for the caller
store.incSystemBalance(poolToken, poolTokenAmount - poolTokenAmount / 2); // account for rounding errors
return addProtectedLiquidity(_owner, poolToken, _baseToken, poolTokenAmount / 2, _amount);
}
/**
* @dev returns the expected/actual amounts the provider will receive for removing liquidity
* it's also possible to provide the remove liquidity time to get an estimation
* for the return at that given point
*
* @param _id protected liquidity id
* @param _portion portion of liquidity to remove, in PPM
* @param _removeTimestamp time at which the liquidity is removed
* @return expected return amount in the reserve token
* @return actual return amount in the reserve token
* @return compensation in the network token
*/
function removeLiquidityReturn(
uint256 _id,
uint32 _portion,
uint256 _removeTimestamp
)
external
view
validPortion(_portion)
returns (
uint256,
uint256,
uint256
)
{
ProtectedLiquidity memory liquidity = protectedLiquidity(_id);
// verify input
require(liquidity.provider != address(0), "ERR_INVALID_ID");
require(_removeTimestamp >= liquidity.timestamp, "ERR_INVALID_TIMESTAMP");
// calculate the portion of the liquidity to remove
if (_portion != PPM_RESOLUTION) {
liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION;
liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION;
}
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates =
packRates(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.reserveRateN,
liquidity.reserveRateD,
false
);
uint256 targetAmount =
removeLiquidityTargetAmount(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
packedRates,
liquidity.timestamp,
_removeTimestamp
);
// for network token, the return amount is identical to the target amount
if (liquidity.reserveToken == networkToken) {
return (targetAmount, targetAmount, 0);
}
// handle base token return
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2);
// limit the amount of pool tokens by the amount the system/caller holds
uint256 availableBalance = store.systemBalance(liquidity.poolToken).add(liquidity.poolAmount);
poolAmount = poolAmount > availableBalance ? availableBalance : poolAmount;
// calculate the base token amount received by liquidating the pool tokens
// note that the amount is divided by 2 since the pool amount represents both reserves
uint256 baseAmount = poolAmount.mul(poolRate.n / 2).div(poolRate.d);
uint256 networkAmount = getNetworkCompensation(targetAmount, baseAmount, packedRates);
return (targetAmount, baseAmount, networkAmount);
}
/**
* @dev removes protected liquidity from a pool
* also burns governance tokens from the caller if the caller removes network tokens
*
* @param _id id in the caller's list of protected liquidity
* @param _portion portion of liquidity to remove, in PPM
*/
function removeLiquidity(uint256 _id, uint32 _portion) external validPortion(_portion) protected {
ProtectedLiquidity memory liquidity = protectedLiquidity(_id, msg.sender);
// save a local copy of `networkToken`
IERC20Token networkTokenLocal = networkToken;
// verify that the pool is whitelisted
_poolWhitelisted(liquidity.poolToken);
// verify that the protected liquidity is not removed on the same block in which it was added
require(liquidity.timestamp < time(), "ERR_TOO_EARLY");
if (_portion == PPM_RESOLUTION) {
// remove the protected liquidity from the provider
store.removeProtectedLiquidity(_id);
} else {
// remove a portion of the protected liquidity from the provider
uint256 fullPoolAmount = liquidity.poolAmount;
uint256 fullReserveAmount = liquidity.reserveAmount;
liquidity.poolAmount = liquidity.poolAmount.mul(_portion) / PPM_RESOLUTION;
liquidity.reserveAmount = liquidity.reserveAmount.mul(_portion) / PPM_RESOLUTION;
store.updateProtectedLiquidityAmounts(
_id,
fullPoolAmount - liquidity.poolAmount,
fullReserveAmount - liquidity.reserveAmount
);
}
// update last liquidity removal checkpoint
lastRemoveCheckpointStore.addCheckpoint(msg.sender);
// add the pool tokens to the system
store.incSystemBalance(liquidity.poolToken, liquidity.poolAmount);
// if removing network token liquidity, burn the governance tokens from the caller. we need to transfer the
// tokens to the contract itself, since only token holders can burn their tokens
if (liquidity.reserveToken == networkTokenLocal) {
safeTransferFrom(govToken, msg.sender, address(this), liquidity.reserveAmount);
govTokenGovernance.burn(liquidity.reserveAmount);
}
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates =
packRates(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.reserveRateN,
liquidity.reserveRateD,
true
);
// get the target token amount
uint256 targetAmount =
removeLiquidityTargetAmount(
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
packedRates,
liquidity.timestamp,
time()
);
// remove network token liquidity
if (liquidity.reserveToken == networkTokenLocal) {
// mint network tokens for the caller and lock them
networkTokenGovernance.mint(address(store), targetAmount);
settings.incNetworkTokensMinted(liquidity.poolToken, targetAmount);
lockTokens(msg.sender, targetAmount);
return;
}
// remove base token liquidity
// calculate the amount of pool tokens required for liquidation
// note that the amount is doubled since it's not possible to liquidate one reserve only
Fraction memory poolRate = poolTokenRate(liquidity.poolToken, liquidity.reserveToken);
uint256 poolAmount = targetAmount.mul(poolRate.d).div(poolRate.n / 2);
// limit the amount of pool tokens by the amount the system holds
uint256 systemBalance = store.systemBalance(liquidity.poolToken);
poolAmount = poolAmount > systemBalance ? systemBalance : poolAmount;
// withdraw the pool tokens from the store
store.decSystemBalance(liquidity.poolToken, poolAmount);
store.withdrawTokens(liquidity.poolToken, address(this), poolAmount);
// remove liquidity
removeLiquidity(liquidity.poolToken, poolAmount, liquidity.reserveToken, networkTokenLocal);
// transfer the base tokens to the caller
uint256 baseBalance;
if (liquidity.reserveToken == ETH_RESERVE_ADDRESS) {
baseBalance = address(this).balance;
msg.sender.transfer(baseBalance);
} else {
baseBalance = liquidity.reserveToken.balanceOf(address(this));
safeTransfer(liquidity.reserveToken, msg.sender, baseBalance);
}
// compensate the caller with network tokens if still needed
uint256 delta = getNetworkCompensation(targetAmount, baseBalance, packedRates);
if (delta > 0) {
// check if there's enough network token balance, otherwise mint more
uint256 networkBalance = networkTokenLocal.balanceOf(address(this));
if (networkBalance < delta) {
networkTokenGovernance.mint(address(this), delta - networkBalance);
}
// lock network tokens for the caller
safeTransfer(networkTokenLocal, address(store), delta);
lockTokens(msg.sender, delta);
}
// if the contract still holds network tokens, burn them
uint256 networkBalance = networkTokenLocal.balanceOf(address(this));
if (networkBalance > 0) {
networkTokenGovernance.burn(networkBalance);
settings.decNetworkTokensMinted(liquidity.poolToken, networkBalance);
}
}
/**
* @dev returns the amount the provider will receive for removing liquidity
* it's also possible to provide the remove liquidity rate & time to get an estimation
* for the return at that given point
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _poolAmount pool token amount when the liquidity was added
* @param _reserveAmount reserve token amount that was added
* @param _packedRates see `struct PackedRates`
* @param _addTimestamp time at which the liquidity was added
* @param _removeTimestamp time at which the liquidity is removed
* @return amount received for removing liquidity
*/
function removeLiquidityTargetAmount(
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount,
PackedRates memory _packedRates,
uint256 _addTimestamp,
uint256 _removeTimestamp
) internal view returns (uint256) {
// get the rate between the pool token and the reserve token
Fraction memory poolRate = poolTokenRate(_poolToken, _reserveToken);
// get the rate between the reserves upon adding liquidity and now
Fraction memory addSpotRate = Fraction({ n: _packedRates.addSpotRateN, d: _packedRates.addSpotRateD });
Fraction memory removeSpotRate = Fraction({ n: _packedRates.removeSpotRateN, d: _packedRates.removeSpotRateD });
Fraction memory removeAverageRate =
Fraction({ n: _packedRates.removeAverageRateN, d: _packedRates.removeAverageRateD });
// calculate the protected amount of reserve tokens plus accumulated fee before compensation
uint256 total = protectedAmountPlusFee(_poolAmount, poolRate, addSpotRate, removeSpotRate);
// calculate the impermanent loss
Fraction memory loss = impLoss(addSpotRate, removeAverageRate);
// calculate the protection level
Fraction memory level = protectionLevel(_addTimestamp, _removeTimestamp);
// calculate the compensation amount
return compensationAmount(_reserveAmount, Math.max(_reserveAmount, total), loss, level);
}
/**
* @dev allows the caller to claim network token balance that is no longer locked
* note that the function can revert if the range is too large
*
* @param _startIndex start index in the caller's list of locked balances
* @param _endIndex end index in the caller's list of locked balances (exclusive)
*/
function claimBalance(uint256 _startIndex, uint256 _endIndex) external protected {
// get the locked balances from the store
(uint256[] memory amounts, uint256[] memory expirationTimes) =
store.lockedBalanceRange(msg.sender, _startIndex, _endIndex);
uint256 totalAmount = 0;
uint256 length = amounts.length;
assert(length == expirationTimes.length);
// 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;
}
// remove the locked balance item
store.removeLockedBalance(msg.sender, _startIndex + index);
totalAmount = totalAmount.add(amounts[index]);
}
if (totalAmount > 0) {
// transfer the tokens to the caller in a single call
store.withdrawTokens(networkToken, msg.sender, totalAmount);
}
}
/**
* @dev returns the ROI for removing liquidity in the current state after providing liquidity with the given args
* the function assumes full protection is in effect
* return value is in PPM and can be larger than PPM_RESOLUTION for positive ROI, 1M = 0% ROI
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _reserveAmount reserve token amount that was added
* @param _poolRateN rate of 1 pool token in reserve token units when the liquidity was added (numerator)
* @param _poolRateD rate of 1 pool token in reserve token units when the liquidity was added (denominator)
* @param _reserveRateN rate of 1 reserve token in the other reserve token units when the liquidity was added (numerator)
* @param _reserveRateD rate of 1 reserve token in the other reserve token units when the liquidity was added (denominator)
* @return ROI in PPM
*/
function poolROI(
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _reserveAmount,
uint256 _poolRateN,
uint256 _poolRateD,
uint256 _reserveRateN,
uint256 _reserveRateD
) external view returns (uint256) {
// calculate the amount of pool tokens based on the amount of reserve tokens
uint256 poolAmount = _reserveAmount.mul(_poolRateD).div(_poolRateN);
// get the various rates between the reserves upon adding liquidity and now
PackedRates memory packedRates = packRates(_poolToken, _reserveToken, _reserveRateN, _reserveRateD, false);
// get the current return
uint256 protectedReturn =
removeLiquidityTargetAmount(
_poolToken,
_reserveToken,
poolAmount,
_reserveAmount,
packedRates,
time().sub(settings.maxProtectionDelay()),
time()
);
// calculate the ROI as the ratio between the current fully protected return and the initial amount
return protectedReturn.mul(PPM_RESOLUTION).div(_reserveAmount);
}
/**
* @dev utility to protect existing liquidity
* also mints new governance tokens for the caller when protecting the network token reserve
*
* @param _poolAnchor pool anchor
* @param _converter pool converter
* @param _networkToken the network reserve token of the pool
* @param _reserveIndex index of the reserve to protect
* @param _poolAmount amount of pool tokens to protect
*/
function protectLiquidity(
IDSToken _poolAnchor,
IConverter _converter,
IERC20Token _networkToken,
uint256 _reserveIndex,
uint256 _poolAmount
) internal {
// get the reserves token
IERC20Token reserveToken = _converter.connectorTokens(_reserveIndex);
// get the pool token rate
IDSToken poolToken = IDSToken(address(_poolAnchor));
Fraction memory poolRate = poolTokenRate(poolToken, reserveToken);
// calculate the reserve balance based on the amount provided and the pool token rate
uint256 reserveAmount = _poolAmount.mul(poolRate.n).div(poolRate.d);
// protect the liquidity
addProtectedLiquidity(msg.sender, poolToken, reserveToken, _poolAmount, reserveAmount);
// for network token liquidity, mint governance tokens to the caller
if (reserveToken == _networkToken) {
govTokenGovernance.mint(msg.sender, reserveAmount);
}
}
/**
* @dev adds protected liquidity for the caller to the store
*
* @param _provider protected liquidity provider
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _poolAmount amount of pool tokens to protect
* @param _reserveAmount amount of reserve tokens to protect
* @return new protected liquidity id
*/
function addProtectedLiquidity(
address _provider,
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount
) internal returns (uint256) {
Fraction memory rate = reserveTokenAverageRate(_poolToken, _reserveToken, true);
return
store.addProtectedLiquidity(
_provider,
_poolToken,
_reserveToken,
_poolAmount,
_reserveAmount,
rate.n,
rate.d,
time()
);
}
/**
* @dev locks network tokens for the provider and emits the tokens locked event
*
* @param _provider tokens provider
* @param _amount amount of network tokens
*/
function lockTokens(address _provider, uint256 _amount) internal {
uint256 expirationTime = time().add(settings.lockDuration());
store.addLockedBalance(_provider, _amount, expirationTime);
}
/**
* @dev returns the rate of 1 pool token in reserve token units
*
* @param _poolToken pool token
* @param _reserveToken reserve token
*/
function poolTokenRate(IDSToken _poolToken, IERC20Token _reserveToken) internal view virtual returns (Fraction memory) {
// get the pool token supply
uint256 poolTokenSupply = _poolToken.totalSupply();
// get the reserve balance
IConverter converter = IConverter(payable(ownedBy(_poolToken)));
uint256 reserveBalance = converter.getConnectorBalance(_reserveToken);
// for standard pools, 50% of the pool supply value equals the value of each reserve
return Fraction({ n: reserveBalance.mul(2), d: poolTokenSupply });
}
/**
* @dev returns the average rate of 1 reserve token in the other reserve token units
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _validateAverageRate true to validate the average rate; false otherwise
*/
function reserveTokenAverageRate(
IDSToken _poolToken,
IERC20Token _reserveToken,
bool _validateAverageRate
) internal view returns (Fraction memory) {
(, , uint256 averageRateN, uint256 averageRateD) =
reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate);
return Fraction(averageRateN, averageRateD);
}
/**
* @dev returns the spot rate and average rate of 1 reserve token in the other reserve token units
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _validateAverageRate true to validate the average rate; false otherwise
*/
function reserveTokenRates(
IDSToken _poolToken,
IERC20Token _reserveToken,
bool _validateAverageRate
)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken)));
IERC20Token otherReserve = converter.connectorTokens(0);
if (otherReserve == _reserveToken) {
otherReserve = converter.connectorTokens(1);
}
(uint256 spotRateN, uint256 spotRateD) = converterReserveBalances(converter, otherReserve, _reserveToken);
(uint256 averageRateN, uint256 averageRateD) = converter.recentAverageRate(_reserveToken);
require(
!_validateAverageRate ||
averageRateInRange(
spotRateN,
spotRateD,
averageRateN,
averageRateD,
settings.averageRateMaxDeviation()
),
"ERR_INVALID_RATE"
);
return (spotRateN, spotRateD, averageRateN, averageRateD);
}
/**
* @dev returns the various rates between the reserves
*
* @param _poolToken pool token
* @param _reserveToken reserve token
* @param _addSpotRateN add spot rate numerator
* @param _addSpotRateD add spot rate denominator
* @param _validateAverageRate true to validate the average rate; false otherwise
* @return see `struct PackedRates`
*/
function packRates(
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _addSpotRateN,
uint256 _addSpotRateD,
bool _validateAverageRate
) internal view returns (PackedRates memory) {
(uint256 removeSpotRateN, uint256 removeSpotRateD, uint256 removeAverageRateN, uint256 removeAverageRateD) =
reserveTokenRates(_poolToken, _reserveToken, _validateAverageRate);
require(
(_addSpotRateN <= MAX_UINT128 && _addSpotRateD <= MAX_UINT128) &&
(removeSpotRateN <= MAX_UINT128 && removeSpotRateD <= MAX_UINT128) &&
(removeAverageRateN <= MAX_UINT128 && removeAverageRateD <= MAX_UINT128),
"ERR_INVALID_RATE"
);
return
PackedRates({
addSpotRateN: uint128(_addSpotRateN),
addSpotRateD: uint128(_addSpotRateD),
removeSpotRateN: uint128(removeSpotRateN),
removeSpotRateD: uint128(removeSpotRateD),
removeAverageRateN: uint128(removeAverageRateN),
removeAverageRateD: uint128(removeAverageRateD)
});
}
/**
* @dev returns whether or not the deviation of the average rate from the spot rate is within range
* for example, if the maximum permitted deviation is 5%, then return `95/100 <= average/spot <= 100/95`
*
* @param _spotRateN spot rate numerator
* @param _spotRateD spot rate denominator
* @param _averageRateN average rate numerator
* @param _averageRateD average rate denominator
* @param _maxDeviation the maximum permitted deviation of the average rate from the spot rate
*/
function averageRateInRange(
uint256 _spotRateN,
uint256 _spotRateD,
uint256 _averageRateN,
uint256 _averageRateD,
uint32 _maxDeviation
) internal pure returns (bool) {
uint256 min =
_spotRateN.mul(_averageRateD).mul(PPM_RESOLUTION - _maxDeviation).mul(PPM_RESOLUTION - _maxDeviation);
uint256 mid = _spotRateD.mul(_averageRateN).mul(PPM_RESOLUTION - _maxDeviation).mul(PPM_RESOLUTION);
uint256 max = _spotRateN.mul(_averageRateD).mul(PPM_RESOLUTION).mul(PPM_RESOLUTION);
return min <= mid && mid <= max;
}
/**
* @dev utility to add liquidity to a converter
*
* @param _converter converter
* @param _reserveToken1 reserve token 1
* @param _reserveToken2 reserve token 2
* @param _reserveAmount1 reserve amount 1
* @param _reserveAmount2 reserve amount 2
* @param _value ETH amount to add
*/
function addLiquidity(
ILiquidityPoolConverter _converter,
IERC20Token _reserveToken1,
IERC20Token _reserveToken2,
uint256 _reserveAmount1,
uint256 _reserveAmount2,
uint256 _value
) internal {
// ensure that the contract can receive ETH
updatingLiquidity = true;
IERC20Token[] memory reserveTokens = new IERC20Token[](2);
uint256[] memory amounts = new uint256[](2);
reserveTokens[0] = _reserveToken1;
reserveTokens[1] = _reserveToken2;
amounts[0] = _reserveAmount1;
amounts[1] = _reserveAmount2;
_converter.addLiquidity{ value: _value }(reserveTokens, amounts, 1);
// ensure that the contract can receive ETH
updatingLiquidity = false;
}
/**
* @dev utility to remove liquidity from a converter
*
* @param _poolToken pool token of the converter
* @param _poolAmount amount of pool tokens to remove
* @param _reserveToken1 reserve token 1
* @param _reserveToken2 reserve token 2
*/
function removeLiquidity(
IDSToken _poolToken,
uint256 _poolAmount,
IERC20Token _reserveToken1,
IERC20Token _reserveToken2
) internal {
ILiquidityPoolConverter converter = ILiquidityPoolConverter(payable(ownedBy(_poolToken)));
// ensure that the contract can receive ETH
updatingLiquidity = true;
IERC20Token[] memory reserveTokens = new IERC20Token[](2);
uint256[] memory minReturns = new uint256[](2);
reserveTokens[0] = _reserveToken1;
reserveTokens[1] = _reserveToken2;
minReturns[0] = 1;
minReturns[1] = 1;
converter.removeLiquidity(_poolAmount, reserveTokens, minReturns);
// ensure that the contract can receive ETH
updatingLiquidity = false;
}
/**
* @dev returns a protected liquidity from the store
*
* @param _id protected liquidity id
* @return protected liquidity
*/
function protectedLiquidity(uint256 _id) internal view returns (ProtectedLiquidity memory) {
ProtectedLiquidity memory liquidity;
(
liquidity.provider,
liquidity.poolToken,
liquidity.reserveToken,
liquidity.poolAmount,
liquidity.reserveAmount,
liquidity.reserveRateN,
liquidity.reserveRateD,
liquidity.timestamp
) = store.protectedLiquidity(_id);
return liquidity;
}
/**
* @dev returns a protected liquidity from the store
*
* @param _id protected liquidity id
* @param _provider authorized provider
* @return protected liquidity
*/
function protectedLiquidity(uint256 _id, address _provider) internal view returns (ProtectedLiquidity memory) {
ProtectedLiquidity memory liquidity = protectedLiquidity(_id);
require(liquidity.provider == _provider, "ERR_ACCESS_DENIED");
return liquidity;
}
/**
* @dev returns the protected amount of reserve tokens plus accumulated fee before compensation
*
* @param _poolAmount pool token amount when the liquidity was added
* @param _poolRate rate of 1 pool token in the related reserve token units
* @param _addRate rate of 1 reserve token in the other reserve token units when the liquidity was added
* @param _removeRate rate of 1 reserve token in the other reserve token units when the liquidity is removed
* @return protected amount of reserve tokens plus accumulated fee = sqrt(_removeRate / _addRate) * _poolRate * _poolAmount
*/
function protectedAmountPlusFee(
uint256 _poolAmount,
Fraction memory _poolRate,
Fraction memory _addRate,
Fraction memory _removeRate
) internal pure returns (uint256) {
uint256 n = Math.ceilSqrt(_addRate.d.mul(_removeRate.n)).mul(_poolRate.n);
uint256 d = Math.floorSqrt(_addRate.n.mul(_removeRate.d)).mul(_poolRate.d);
uint256 x = n * _poolAmount;
if (x / n == _poolAmount) {
return x / d;
}
(uint256 hi, uint256 lo) = n > _poolAmount ? (n, _poolAmount) : (_poolAmount, n);
(uint256 p, uint256 q) = Math.reducedRatio(hi, d, MAX_UINT256 / lo);
uint256 min = (hi / d).mul(lo);
if (q > 0) {
return Math.max(min, p * lo / q);
}
return min;
}
/**
* @dev returns the impermanent loss incurred due to the change in rates between the reserve tokens
*
* @param _prevRate previous rate between the reserves
* @param _newRate new rate between the reserves
* @return impermanent loss (as a ratio)
*/
function impLoss(Fraction memory _prevRate, Fraction memory _newRate) internal pure returns (Fraction memory) {
uint256 ratioN = _newRate.n.mul(_prevRate.d);
uint256 ratioD = _newRate.d.mul(_prevRate.n);
uint256 prod = ratioN * ratioD;
uint256 root = prod / ratioN == ratioD ? Math.floorSqrt(prod) : Math.floorSqrt(ratioN) * Math.floorSqrt(ratioD);
uint256 sum = ratioN.add(ratioD);
// the arithmetic below is safe because `x + y >= sqrt(x * y) * 2`
if (sum % 2 == 0) {
sum /= 2;
return Fraction({ n: sum - root, d: sum });
}
return Fraction({ n: sum - root * 2, d: sum });
}
/**
* @dev returns the protection level based on the timestamp and protection delays
*
* @param _addTimestamp time at which the liquidity was added
* @param _removeTimestamp time at which the liquidity is removed
* @return protection level (as a ratio)
*/
function protectionLevel(uint256 _addTimestamp, uint256 _removeTimestamp) internal view returns (Fraction memory) {
uint256 timeElapsed = _removeTimestamp.sub(_addTimestamp);
uint256 minProtectionDelay = settings.minProtectionDelay();
uint256 maxProtectionDelay = settings.maxProtectionDelay();
if (timeElapsed < minProtectionDelay) {
return Fraction({ n: 0, d: 1 });
}
if (timeElapsed >= maxProtectionDelay) {
return Fraction({ n: 1, d: 1 });
}
return Fraction({ n: timeElapsed, d: maxProtectionDelay });
}
/**
* @dev returns the compensation amount based on the impermanent loss and the protection level
*
* @param _amount protected amount in units of the reserve token
* @param _total amount plus fee in units of the reserve token
* @param _loss protection level (as a ratio between 0 and 1)
* @param _level impermanent loss (as a ratio between 0 and 1)
* @return compensation amount
*/
function compensationAmount(
uint256 _amount,
uint256 _total,
Fraction memory _loss,
Fraction memory _level
) internal pure returns (uint256) {
uint256 levelN = _level.n.mul(_amount);
uint256 levelD = _level.d;
uint256 maxVal = Math.max(Math.max(levelN, levelD), _total);
(uint256 lossN, uint256 lossD) = Math.reducedRatio(_loss.n, _loss.d, MAX_UINT256 / maxVal);
return _total.mul(lossD.sub(lossN)).div(lossD).add(lossN.mul(levelN).div(lossD.mul(levelD)));
}
function getNetworkCompensation(
uint256 _targetAmount,
uint256 _baseAmount,
PackedRates memory _packedRates
) internal view returns (uint256) {
if (_targetAmount <= _baseAmount) {
return 0;
}
// calculate the delta in network tokens
uint256 delta =
(_targetAmount - _baseAmount).mul(_packedRates.removeAverageRateN).div(_packedRates.removeAverageRateD);
// the delta might be very small due to precision loss
// in which case no compensation will take place (gas optimization)
if (delta >= settings.minNetworkCompensation()) {
return delta;
}
return 0;
}
/**
* @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't.
* note that we use the non standard erc-20 interface in which `approve` has no return value so that
* this function will work for both standard and non standard tokens
*
* @param _token token to check the allowance in
* @param _spender approved address
* @param _value allowance amount
*/
function ensureAllowance(
IERC20Token _token,
address _spender,
uint256 _value
) private {
uint256 allowance = _token.allowance(address(this), _spender);
if (allowance < _value) {
if (allowance > 0) safeApprove(_token, _spender, 0);
safeApprove(_token, _spender, _value);
}
}
// utility to get the reserve balances
function converterReserveBalances(
IConverter _converter,
IERC20Token _reserveToken1,
IERC20Token _reserveToken2
) private view returns (uint256, uint256) {
return (_converter.getConnectorBalance(_reserveToken1), _converter.getConnectorBalance(_reserveToken2));
}
// utility to get the owner
function ownedBy(IOwned _owned) private view returns (address) {
return _owned.owner();
}
}
| 14,130 |
199 | // CUSDC | _cToken,
_keeper
)
| _cToken,
_keeper
)
| 55,343 |
40 | // do redeem | filledAmount = min(
min(takerOrderInfo.balances[opposite], posFilledAmount),
makerOrderInfo.balances[side]
);
| filledAmount = min(
min(takerOrderInfo.balances[opposite], posFilledAmount),
makerOrderInfo.balances[side]
);
| 8,254 |
96 | // Total rewards accumulated since contract deployment. | uint256 public totalRewards;
| uint256 public totalRewards;
| 24,571 |
61 | // function to get staked amount, earned amount and reward amount of user based on address | function getUserInfoByAddress(address addr) external view returns (uint256 staked, uint256 earned, uint256 reward) {
require(addr != address(0), "Invalid Address, Pleae Try Again!!!");
uint256[] memory tokenStakingIds = _tokenStakingId[addr];
for (uint i = 0; i < tokenStakingIds.length; i++) {
uint256 stakingId = tokenStakingIds[i];
if (_finalTokenStakeWithdraw[stakingId] == 0) {
staked += _usersTokens[stakingId];
for (uint j = 0; j < categories.length; j++) {
if (_tokenTotalDays[stakingId] == categories[j].period) {
if(block.timestamp >= _tokenStakingEndTime[stakingId]) {
reward += getTokenRewardDetailsByStakingId(stakingId);
} else {
reward += getTokenPenaltyDetailByStakingId(stakingId);
}
break;
}
}
}
earned += _finalTokenStakeWithdraw[tokenStakingIds[i]];
}
}
| function getUserInfoByAddress(address addr) external view returns (uint256 staked, uint256 earned, uint256 reward) {
require(addr != address(0), "Invalid Address, Pleae Try Again!!!");
uint256[] memory tokenStakingIds = _tokenStakingId[addr];
for (uint i = 0; i < tokenStakingIds.length; i++) {
uint256 stakingId = tokenStakingIds[i];
if (_finalTokenStakeWithdraw[stakingId] == 0) {
staked += _usersTokens[stakingId];
for (uint j = 0; j < categories.length; j++) {
if (_tokenTotalDays[stakingId] == categories[j].period) {
if(block.timestamp >= _tokenStakingEndTime[stakingId]) {
reward += getTokenRewardDetailsByStakingId(stakingId);
} else {
reward += getTokenPenaltyDetailByStakingId(stakingId);
}
break;
}
}
}
earned += _finalTokenStakeWithdraw[tokenStakingIds[i]];
}
}
| 13,458 |
270 | // Change number of users in old team | teams[oldTeamId].numberUsers = teams[oldTeamId].numberUsers.sub(1);
| teams[oldTeamId].numberUsers = teams[oldTeamId].numberUsers.sub(1);
| 1,478 |
196 | // Total amount of withdrawals pending. | uint256 public totalPending;
mapping (address => WithdrawalRequest) public withdrawals;
| uint256 public totalPending;
mapping (address => WithdrawalRequest) public withdrawals;
| 2,659 |
88 | // IGeyser/return staking token for this Geyser / | function stakingToken() external virtual view returns (address);
| function stakingToken() external virtual view returns (address);
| 41,997 |
55 | // Update baseAmounts | _baseAmounts[_msgSender()] = _baseAmounts[_msgSender()].add(baseAmountForSale);
| _baseAmounts[_msgSender()] = _baseAmounts[_msgSender()].add(baseAmountForSale);
| 15,494 |
3 | // withdraw migrated wsEXO and unmigrated gEXO | function clear() external onlyOwner {
wsEXO.safeTransfer(msg.sender, wsEXO.balanceOf(address(this)));
gEXO.safeTransfer(msg.sender, gEXO.balanceOf(address(this)));
}
| function clear() external onlyOwner {
wsEXO.safeTransfer(msg.sender, wsEXO.balanceOf(address(this)));
gEXO.safeTransfer(msg.sender, gEXO.balanceOf(address(this)));
}
| 25,362 |
36 | // Require that votes in favor of proposal are greater or equal to minimalQuorum | require(proposal.forVotes >= membersRegistry.getMinimalQuorum());
for (uint i = 0; i < proposal.targets.length; i++) {
bytes memory callData;
if (bytes(proposal.signatures[i]).length == 0) {
callData = proposal.calldatas[i];
} else {
| require(proposal.forVotes >= membersRegistry.getMinimalQuorum());
for (uint i = 0; i < proposal.targets.length; i++) {
bytes memory callData;
if (bytes(proposal.signatures[i]).length == 0) {
callData = proposal.calldatas[i];
} else {
| 44,766 |
19 | // Ensure the rhash has not been used before to prevent replay attacks. | require(
keccak256(abi.encodePacked(iNetwork)) ==
keccak256(abi.encodePacked(network)),
"FluentStable: Invalid network"
);
| require(
keccak256(abi.encodePacked(iNetwork)) ==
keccak256(abi.encodePacked(network)),
"FluentStable: Invalid network"
);
| 33,363 |
149 | // validator configurationreturn validator validator contractreturn gasLimit gas limit for validate calls / | function validatorConfig()
external
view
| function validatorConfig()
external
view
| 35,966 |
49 | // considering replace input address with path | address[] memory path=new address[](2);
path[0]=tokenIn;
path[1]=tokenOut;
| address[] memory path=new address[](2);
path[0]=tokenIn;
path[1]=tokenOut;
| 1,411 |
56 | // struct for returning type of getAllInvestors | struct Investments {
address investor;
uint256[] amounts;
uint256[] tokens;
}
| struct Investments {
address investor;
uint256[] amounts;
uint256[] tokens;
}
| 18,318 |
268 | // This is check claimable for non cliff vesting./_poolId : Pool Id from which pool user want to check./_user : User address for which user want to check claimables./ return returning the claimable amount of the user from non cliff vesting. | function nonCliffClaimable(uint256 _poolId, address _user)
public
view
returns (uint256)
| function nonCliffClaimable(uint256 _poolId, address _user)
public
view
returns (uint256)
| 19,307 |
147 | // reward calculations | uint256 private totalRewardPoints;
uint256 public rewardsDistributed;
uint256 public rewardsWithdrawn;
uint256 public totalRewardsDistributed;
mapping(address => StakeDeposit) private _stakeDeposits;
| uint256 private totalRewardPoints;
uint256 public rewardsDistributed;
uint256 public rewardsWithdrawn;
uint256 public totalRewardsDistributed;
mapping(address => StakeDeposit) private _stakeDeposits;
| 73,476 |
14 | // This function refunds the seller, i.e./ pays back the locked funds of the seller. | function refundSeller()
public
onlySeller
inState(State.Release)
| function refundSeller()
public
onlySeller
inState(State.Release)
| 22,029 |
118 | // LemonToken with Governance. | contract LemonToken is ERC20("LemonToken", "LEMON"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Burn some lemon, reduce total circulation.
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "LEMON::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "LEMON::delegateBySig: invalid nonce");
require(now <= expiry, "LEMON::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "LEMON::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying LEMONs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "LEMON::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | contract LemonToken is ERC20("LemonToken", "LEMON"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Burn some lemon, reduce total circulation.
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "LEMON::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "LEMON::delegateBySig: invalid nonce");
require(now <= expiry, "LEMON::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "LEMON::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying LEMONs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "LEMON::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | 30,790 |
98 | // arg[1] = exp.length @ + 0x20 | mstore(add(freemem, 0x20), el)
| mstore(add(freemem, 0x20), el)
| 9,722 |
174 | // 新队伍ID | uint256 _tID = round_[rID_].tID_;
| uint256 _tID = round_[rID_].tID_;
| 67,458 |
9 | // Step 7: one final time, swap the remaining base tokens (in WP) for PTs and YTs and send to user. So at the end of YTC, user gets PT and YT and no base tokens. | (uint256 pt, uint256 yt) = tranche.prefundedDeposit(msg.sender);
return (pt, yt+ytBalance);
| (uint256 pt, uint256 yt) = tranche.prefundedDeposit(msg.sender);
return (pt, yt+ytBalance);
| 28,223 |
276 | // OwnedUpgradeabilityStorage This contract keeps track of the upgradeability owner / | contract OwnedUpgradeabilityStorage {
// Current implementation
address internal _implementation;
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
}
| contract OwnedUpgradeabilityStorage {
// Current implementation
address internal _implementation;
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
}
| 20,817 |
34 | // Increments the number of total and pending votes for `group`. group The validator group to vote for. value The amount of gold to use to vote. lesser The group receiving fewer votes than `group`, or 0 if `group` has thefewest votes of any validator group. greater The group receiving more votes than `group`, or 0 if `group` has themost votes of any validator group.return True upon success. Fails if `group` is empty or not a validator group. / | function vote(address group, uint256 value, address lesser, address greater)
external
nonReentrant
returns (bool)
| function vote(address group, uint256 value, address lesser, address greater)
external
nonReentrant
returns (bool)
| 18,190 |
117 | // Returns timestamp at which accumulated M26s have last been claimed for a {tokenIndex}. / | function lastClaim(uint256 tokenIndex) public view returns (uint256) {
require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet");
uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : _emissionStartTimestamp;
return lastClaimed;
}
| function lastClaim(uint256 tokenIndex) public view returns (uint256) {
require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address");
require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet");
uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? uint256(_lastClaim[tokenIndex]) : _emissionStartTimestamp;
return lastClaimed;
}
| 64,614 |
153 | // Not enough of pool token exists on this contract, some must be staked in Gauge, unstake difference | ICurveGauge(crvGaugeAddress).withdraw(
withdrawPTokens.sub(contractPTokens)
);
| ICurveGauge(crvGaugeAddress).withdraw(
withdrawPTokens.sub(contractPTokens)
);
| 44,853 |
51 | // return percentages for ETH and token1000 = 1% | uint internal period1RPWeth;
uint internal period2RPWeth;
uint internal period3RPWeth;
uint internal period4RPWeth;
uint internal period1RPToken;
uint internal period2RPToken;
uint internal period3RPToken;
uint internal period4RPToken;
| uint internal period1RPWeth;
uint internal period2RPWeth;
uint internal period3RPWeth;
uint internal period4RPWeth;
uint internal period1RPToken;
uint internal period2RPToken;
uint internal period3RPToken;
uint internal period4RPToken;
| 21,004 |
143 | // add liquidity of nfts when liquidity already added on Elastic Pool/only can call by nfts's owner/calculate reward earned, update stakeInfo, mint an amount of farmingToken to msg.sender/fId farm's id/rangeId rangeId of deposited nfts/nftIds nfts to add liquidity | function addLiquidity(uint256 fId, uint256 rangeId, uint256[] calldata nftIds) external;
| function addLiquidity(uint256 fId, uint256 rangeId, uint256[] calldata nftIds) external;
| 4,122 |
20 | // there was a deposit in the `epochId - 1` epoch => we have a checkpoint for the current epoch | else if (checkpoints[last].epochId == currentEpoch) {
checkpoints[last].startBalance = balances[msg.sender][tokenAddress];
checkpoints[last].newDeposits = 0;
checkpoints[last].multiplier = BASE_MULTIPLIER;
poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size.sub(amount);
}
| else if (checkpoints[last].epochId == currentEpoch) {
checkpoints[last].startBalance = balances[msg.sender][tokenAddress];
checkpoints[last].newDeposits = 0;
checkpoints[last].multiplier = BASE_MULTIPLIER;
poolSize[tokenAddress][currentEpoch].size = poolSize[tokenAddress][currentEpoch].size.sub(amount);
}
| 38,392 |
10 | // Calculate file ID from file hash | function getFileId(string memory _md5, string memory _sha256, string memory _sha512) public pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes(_md5), bytes(_sha256), bytes(_sha512)));
}
| function getFileId(string memory _md5, string memory _sha256, string memory _sha512) public pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes(_md5), bytes(_sha256), bytes(_sha512)));
}
| 29,321 |
168 | // Emits {Freeze} event. Requirements: - the caller must have the `WHITELIST_ROLE`. / | function freeze(address addr) external virtual onlyWhitelister {
frozen[addr] = true;
emit Freeze(addr);
}
| function freeze(address addr) external virtual onlyWhitelister {
frozen[addr] = true;
emit Freeze(addr);
}
| 18,783 |
2 | // mapping for tokenID => Categories | mapping(uint => uint64) public mintedCategories;
| mapping(uint => uint64) public mintedCategories;
| 2,624 |
6 | // Revert with an error when an ERC20 token transfer returns a falsey value.tokenThe token for which the ERC20 transfer was attempted. from The source of the attempted ERC20 transfer. to The recipient of the attempted ERC20 transfer. amount The amount for the attempted ERC20 transfer. / | error BadReturnValueFromERC20OnTransfer(
| error BadReturnValueFromERC20OnTransfer(
| 29,656 |
129 | // Used by topWizard to vary the cap on claim price. | function setMaximumClaimPriceWei(uint _maximumClaimPriceWei) {
externalEnter();
setMaximumClaimPriceWeiRP(_maximumClaimPriceWei);
externalLeave();
}
| function setMaximumClaimPriceWei(uint _maximumClaimPriceWei) {
externalEnter();
setMaximumClaimPriceWeiRP(_maximumClaimPriceWei);
externalLeave();
}
| 42,403 |
5 | // return The generator of E2. / | function G2() private pure returns (E2Point memory) {
return
E2Point({
x: [
11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781
],
y: [
4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930
]
});
}
| function G2() private pure returns (E2Point memory) {
return
E2Point({
x: [
11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781
],
y: [
4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930
]
});
}
| 30,611 |
1,086 | // initialize Schain | schainsInternal.initializeSchain(name, from, lifetime, deposit);
schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from);
| schainsInternal.initializeSchain(name, from, lifetime, deposit);
schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from);
| 29,179 |
101 | // update investor's received tokens balance | investors[_investor].receivedTokens = investors[_investor].receivedTokens.add(_amount);
| investors[_investor].receivedTokens = investors[_investor].receivedTokens.add(_amount);
| 53,023 |
11 | // An event emitted when a proposal has been queued in the Timelock | event ProposalQueued(uint256 id, uint256 eta);
| event ProposalQueued(uint256 id, uint256 eta);
| 877 |
35 | // add user lock records or add to current | userLocks[_account][_token].push(
LockedBalance({
amount: lockAmount,
boosted: boostedAmount,
unlockTime: 0
})
| userLocks[_account][_token].push(
LockedBalance({
amount: lockAmount,
boosted: boostedAmount,
unlockTime: 0
})
| 34,501 |
70 | // permit | IUniswapV2ERC20(address(stakingToken)).permit(msg.sender, address(this), amount, deadline, v, r, s);
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, amount);
| IUniswapV2ERC20(address(stakingToken)).permit(msg.sender, address(this), amount, deadline, v, r, s);
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, amount);
| 1,022 |
0 | // Internals / | function safeAdd(uint256 a, uint256 b) internal pure returns(uint256) {
if ( b > 0 ) {
assert( a + b > a );
}
return a + b;
}
| function safeAdd(uint256 a, uint256 b) internal pure returns(uint256) {
if ( b > 0 ) {
assert( a + b > a );
}
return a + b;
}
| 16,713 |
3 | // Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. // The next contract where the tokens will be migrated. // How many tokens we have upgraded by now. //Upgrade states. - NotAllowed: The child contract has not reached a condition where the upgrade can bgun- WaitingForAgent: Token allows upgrade, but we don't have a new agent yet- ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet- Upgrading: Upgrade agent is set and the balance holders can upgrade their | enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
/**
* Do not allow construction without upgrade master set.
*/
constructor(address _upgradeMaster) public {
upgradeMaster = _upgradeMaster;
}
| enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
/**
* Do not allow construction without upgrade master set.
*/
constructor(address _upgradeMaster) public {
upgradeMaster = _upgradeMaster;
}
| 11,857 |
27 | // notarizeDeposit If the ledger is trying to deposit on behalf of a root key holder,this method is called to ensure the deposit can be notarized. A deposit notarization is an examination of what an authorized deposit needs to contain: the ledger/provider pair was previously registeredwith the root key holder.The caller is required to be the ledger.provider the provider that is trying to depositkeyIdkey to deposit the funds toarnasset resource hash of the withdrawn asset amount the amount of that asset withdrawn.return the valid trust Id for the key / | function notarizeDeposit(address provider, uint256 keyId, bytes32 arn, uint256 amount) external returns (uint256) {
// we need a trusted provider. Since the trust was provided by the root key,
// we will allow deposits for it even if it's not root.
uint256 trustId = requireTrustedActor(keyId, provider, COLLATERAL_PROVIDER);
emit notaryDepositApproval(msg.sender, provider, trustId, keyId, arn, amount);
return trustId;
}
| function notarizeDeposit(address provider, uint256 keyId, bytes32 arn, uint256 amount) external returns (uint256) {
// we need a trusted provider. Since the trust was provided by the root key,
// we will allow deposits for it even if it's not root.
uint256 trustId = requireTrustedActor(keyId, provider, COLLATERAL_PROVIDER);
emit notaryDepositApproval(msg.sender, provider, trustId, keyId, arn, amount);
return trustId;
}
| 10,856 |
80 | // Writes a byte to the buffer. Resizes if doing so would exceed thecapacity of the buffer.buf The buffer to append to.off The offset to write the byte at.data The data to append. return The original buffer, for chaining./ | function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
| function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off >= buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
| 20,005 |
2 | // Transfers ownership to the address specified. addr Specifies the address of the new owner. Throws if called by any account other than the owner. / | function transferOwnership (address addr) public onlyOwner {
require(addr != address(0), "non-zero address required");
emit OwnershipTransferred(_owner, addr);
_owner = addr;
}
| function transferOwnership (address addr) public onlyOwner {
require(addr != address(0), "non-zero address required");
emit OwnershipTransferred(_owner, addr);
_owner = addr;
}
| 27,082 |
91 | // PUBLIC / Add a new erc20 token to the pool. Can only be called by the owner. | function add(
uint256 _tokenPerBlock,
IERC20 _token,
bool _withUpdate
| function add(
uint256 _tokenPerBlock,
IERC20 _token,
bool _withUpdate
| 14,050 |
56 | // Called by a pauser to pause, triggers stopped state. / | function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
| function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
| 6,199 |
32 | // Safe Satisfi transfer function, just in case if rounding error causes pool to not have enough | function safeSatisfiTransfer(address _to, uint256 _SatisfiAmt) internal {
uint256 SatisfiBal = IBEP20(newSatisfiToken).balanceOf(address(this));
if (_SatisfiAmt > SatisfiBal) {
IBEP20(newSatisfiToken).transfer(_to, SatisfiBal);
} else {
IBEP20(newSatisfiToken).transfer(_to, _SatisfiAmt);
}
}
| function safeSatisfiTransfer(address _to, uint256 _SatisfiAmt) internal {
uint256 SatisfiBal = IBEP20(newSatisfiToken).balanceOf(address(this));
if (_SatisfiAmt > SatisfiBal) {
IBEP20(newSatisfiToken).transfer(_to, SatisfiBal);
} else {
IBEP20(newSatisfiToken).transfer(_to, _SatisfiAmt);
}
}
| 43,672 |
28 | // Sets the address of the proxy admin. newAdmin Address of the new proxy admin. / | function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
| function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
| 7,776 |
2 | // Function to transfer tokens to the developer address | function transferToDeveloper(uint256 amount) public onlyOwner {
require(developerAddress != address(0), "Developer address not set");
require(amount <= balanceOf(address(this)), "Insufficient contract balance");
_transfer(address(this), developerAddress, amount);
}
| function transferToDeveloper(uint256 amount) public onlyOwner {
require(developerAddress != address(0), "Developer address not set");
require(amount <= balanceOf(address(this)), "Insufficient contract balance");
_transfer(address(this), developerAddress, amount);
}
| 27,335 |
16 | // if no price limit has been specified, cache the output amount for comparison in the swap callback | if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;
uint256 gasBefore = gasleft();
try
pool.swap(
address(this), // address(0) might cause issues with some tokens
zeroForOne,
-params.amount.toInt256(),
params.sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: params.sqrtPriceLimitX96,
| if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;
uint256 gasBefore = gasleft();
try
pool.swap(
address(this), // address(0) might cause issues with some tokens
zeroForOne,
-params.amount.toInt256(),
params.sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: params.sqrtPriceLimitX96,
| 16,982 |
35 | // Bonuses state | struct Bonus {
uint256 amount;
uint256 finishTimestamp;
}
| struct Bonus {
uint256 amount;
uint256 finishTimestamp;
}
| 11,330 |
1 | // NFT data related to NFTs in this contract that are for sale. nftContractThe NFT contract address. nftTokenIdThe NFT token ID. nftPriceThe NFT price in OST. / | struct NFT {
address nftContract;
uint64 nftTokenId;
uint128 nftPrice;
}
| struct NFT {
address nftContract;
uint64 nftTokenId;
uint128 nftPrice;
}
| 18,713 |
3 | // @inheritdoc IAMulticall | function multicall(bytes[] calldata data) public override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
| function multicall(bytes[] calldata data) public override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
| 32,504 |
11 | // Contract Owner Specific Functions | function setCost(uint _newCost) public onlyOwner(){
cost = _newCost;
}
| function setCost(uint _newCost) public onlyOwner(){
cost = _newCost;
}
| 10,100 |
21 | // End of Bezier curve control point | int256 x2 = currentPoint.x - diff;
string memory curve = string(
abi.encodePacked(
"C ",
toStringSigned(x1),
" ",
toStringSigned(prevPoint.y),
", ",
toStringSigned(x2),
| int256 x2 = currentPoint.x - diff;
string memory curve = string(
abi.encodePacked(
"C ",
toStringSigned(x1),
" ",
toStringSigned(prevPoint.y),
", ",
toStringSigned(x2),
| 18,957 |
80 | // Transfers Governance of the contract to a new account (`newGovernor`).Can only be called by the current Governor. Must be claimed for this to complete _newGovernor Address of the new Governor / | function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
| function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
| 5,152 |
44 | // Function called by the sender, receiver or a delegate, with all the needed/ signatures to close the channel and settle immediately./_receiver_address The address that receives tokens./_open_block_number The block number at which a channel between the/ sender and receiver was created./_balance The amount of tokens owed by the sender to the receiver./_balance_msg_sig The balance message signed by the sender./_closing_sig The receiver's signed balance message, containing the sender's address. | function cooperativeClose(
address _receiver_address,
uint32 _open_block_number,
uint192 _balance,
bytes _balance_msg_sig,
bytes _closing_sig)
external
| function cooperativeClose(
address _receiver_address,
uint32 _open_block_number,
uint192 _balance,
bytes _balance_msg_sig,
bytes _closing_sig)
external
| 21,830 |
193 | // Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order Internal only makerToken Token that the reserve wishes to sell takerToken Token that the reserve wishes to buy price Price as a ratio of takerAmount:makerAmount times 10^18 amount Amount to decrement in ESD / | function _updateOrder(address makerToken, address takerToken, uint256 price, uint256 amount) internal {
_state.orders[makerToken][takerToken] = ReserveTypes.Order({price: Decimal.D256({value: price}), amount: amount});
}
| function _updateOrder(address makerToken, address takerToken, uint256 price, uint256 amount) internal {
_state.orders[makerToken][takerToken] = ReserveTypes.Order({price: Decimal.D256({value: price}), amount: amount});
}
| 63,131 |
28 | // Trade ETH to ERC20 | function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold);
| function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold);
| 5,584 |
219 | // Transfers underlying tokens from {msg.sender} to the contract and/ mints wrapper tokens./amount The amount of wrapper tokens to mint./ return The amount of underlying tokens deposited. | function mint(uint256 amount) external returns (uint256);
| function mint(uint256 amount) external returns (uint256);
| 52,877 |
0 | // BalancerSharedPoolPriceProvider constructor. _pool Balancer pool address. _isPeggedToEth For each token, true if it is pegged to ETH (token order determined by pool.getFinalTokens()). _decimals Number of decimals for each token (token order determined by pool.getFinalTokens()). _priceOracle Aave price oracle. _maxPriceDeviation Threshold of spot prices deviation: 10ˆ16 represents a 1% deviation. / | constructor(
BPoolV2 _pool,
BVaultV2 _vault,
bool[] memory _isPeggedToEth,
uint8[] memory _decimals,
IPriceOracle _priceOracle,
uint256 _maxPriceDeviation,
uint256 _K,
uint256 _powerPrecision,
uint256[][] memory _approximationMatrix
| constructor(
BPoolV2 _pool,
BVaultV2 _vault,
bool[] memory _isPeggedToEth,
uint8[] memory _decimals,
IPriceOracle _priceOracle,
uint256 _maxPriceDeviation,
uint256 _K,
uint256 _powerPrecision,
uint256[][] memory _approximationMatrix
| 34,779 |
0 | // will switch to true when initialized (prevents re-initialization) | bool public initialized = false;
| bool public initialized = false;
| 46,547 |
79 | // The ledger at a particular version/version The version of the ledger to query/ return The ledger at the specified version | function getLedgerOfVersion(Version version)
external
view
returns (Ledger memory)
| function getLedgerOfVersion(Version version)
external
view
returns (Ledger memory)
| 22,837 |
128 | // Accounts address=>balance | mapping(address=>Account) accounts;
| mapping(address=>Account) accounts;
| 55,891 |
14 | // Modifier to ensure the caller is an admin. / | modifier onlyAdmin() {
if (!ICre8ors(cre8orsNFTContractAddress).isAdmin(msg.sender)) {
revert IERC721Drop.Access_OnlyAdmin();
}
_;
}
| modifier onlyAdmin() {
if (!ICre8ors(cre8orsNFTContractAddress).isAdmin(msg.sender)) {
revert IERC721Drop.Access_OnlyAdmin();
}
_;
}
| 16,610 |
67 | // Compute the reflected and net reflected transferred amounts and the net transferred amount from a given amount of ETRNL. trueAmount The specified amount of ETRNLreturn The reflected amount, the net reflected transfer amount, the actual net transfer amount, and the total reflected fees / | function getValues(uint256 trueAmount, bool takeFee) private view returns (uint256, uint256, uint256) {
uint256 liquidityRate = eternalStorage.getUint(entity, liquidityProvisionRate);
uint256 deflationRate = eternalStorage.getUint(entity, burnRate);
uint256 fundRate = eternalStorage.getUint(entity, fundingRate);
uint256 rewardRate = eternalStorage.getUint(entity, redistributionRate);
uint256 feeRate = takeFee ? (liquidityRate + deflationRate + fundRate + rewardRate) : 0;
// Calculate the total fees and transfered amount after fees
uint256 totalFees = (trueAmount * feeRate) / 100000;
uint256 netTransferAmount = trueAmount - totalFees;
// Calculate the reflected amount, reflected total fees and reflected amount after fees
uint256 currentRate = getReflectionRate();
uint256 reflectedAmount = trueAmount * currentRate;
uint256 reflectedTotalFees = totalFees * currentRate;
uint256 netReflectedTransferAmount = reflectedAmount - reflectedTotalFees;
return (reflectedAmount, netReflectedTransferAmount, netTransferAmount);
}
| function getValues(uint256 trueAmount, bool takeFee) private view returns (uint256, uint256, uint256) {
uint256 liquidityRate = eternalStorage.getUint(entity, liquidityProvisionRate);
uint256 deflationRate = eternalStorage.getUint(entity, burnRate);
uint256 fundRate = eternalStorage.getUint(entity, fundingRate);
uint256 rewardRate = eternalStorage.getUint(entity, redistributionRate);
uint256 feeRate = takeFee ? (liquidityRate + deflationRate + fundRate + rewardRate) : 0;
// Calculate the total fees and transfered amount after fees
uint256 totalFees = (trueAmount * feeRate) / 100000;
uint256 netTransferAmount = trueAmount - totalFees;
// Calculate the reflected amount, reflected total fees and reflected amount after fees
uint256 currentRate = getReflectionRate();
uint256 reflectedAmount = trueAmount * currentRate;
uint256 reflectedTotalFees = totalFees * currentRate;
uint256 netReflectedTransferAmount = reflectedAmount - reflectedTotalFees;
return (reflectedAmount, netReflectedTransferAmount, netTransferAmount);
}
| 47,066 |
2 | // function: 查询请求parameters:queryId:请求id 回调时会原值返回callbackAddr :回调合约地址callbackFUN:回调合约函数,如getResponse(bytes32,uint64,uint256/bytes), 其中getResponse表示回调方法名,可自定义; bytes32类型参数指请求id,回调时会原值返回; uint64类型参数表示oracle服务状态码,1表示成功,0表示失败; 第三个参数表示Oracle服务回调结果,类型支持uint256/bytes两种 | * queryData :请求数据 json格式{"url":"https://ethgasstation.info/api/ethgasAPI.json","responseParams":["fast"]}
* return value :true 发起请求成功;false 发起请求失败
*/
function query(bytes32 queryId, address callbackAddr, string calldata callbackFUN, bytes calldata queryData) external payable returns(bool);
} | * queryData :请求数据 json格式{"url":"https://ethgasstation.info/api/ethgasAPI.json","responseParams":["fast"]}
* return value :true 发起请求成功;false 发起请求失败
*/
function query(bytes32 queryId, address callbackAddr, string calldata callbackFUN, bytes calldata queryData) external payable returns(bool);
} | 25,801 |
50 | // Burning tokens on funding wallet | balances[address(nWallets[index])] = 0;
| balances[address(nWallets[index])] = 0;
| 32,703 |
26 | // If sender votes no and voted yes before | resolution.yesVotesTotal -= votingPower;
| resolution.yesVotesTotal -= votingPower;
| 8,779 |
0 | // declare ERC standard details/ | string public name = "Gaia Token";
string public symbol = "GAT";
uint256 public decimals = 0;
| string public name = "Gaia Token";
string public symbol = "GAT";
uint256 public decimals = 0;
| 38,852 |
11 | // Remove the last admin, since it's double present | admins.pop();
| admins.pop();
| 43,092 |
83 | // in theory Q2 <= targetQuoteTokenAmount however when amount is close to 0, precision problems may cause Q2 > targetQuoteTokenAmount | return
DODOMath._SolveQuadraticFunctionForTrade(
state.Q0,
state.Q0,
payBaseAmount,
state.i,
state.K
);
| return
DODOMath._SolveQuadraticFunctionForTrade(
state.Q0,
state.Q0,
payBaseAmount,
state.i,
state.K
);
| 14,102 |
1 | // Constants set in ConstructorERC-20 Token we are staking | IERC20 immutable token;
| IERC20 immutable token;
| 6,330 |
138 | // Credits | event CreditsAdded(uint time, address indexed user, uint32 indexed id, uint amount);
event CreditsUsed(uint time, address indexed user, uint32 indexed id, uint amount);
event CreditsCashedout(uint time, address indexed user, uint amount);
constructor(address _registry)
Bankrollable(_registry)
UsingAdmin(_registry)
public
| event CreditsAdded(uint time, address indexed user, uint32 indexed id, uint amount);
event CreditsUsed(uint time, address indexed user, uint32 indexed id, uint amount);
event CreditsCashedout(uint time, address indexed user, uint amount);
constructor(address _registry)
Bankrollable(_registry)
UsingAdmin(_registry)
public
| 39,015 |
82 | // Remove the specified account from the blacklist. / | function disableBlacklist(address account) public onlyOwner {
require(blacklist[account], "ERC20: Account is not blacklisted");
blacklist[account] = false;
}
| function disableBlacklist(address account) public onlyOwner {
require(blacklist[account], "ERC20: Account is not blacklisted");
blacklist[account] = false;
}
| 3,772 |
70 | // List of agents that are allowed to create new tokens //Create new tokens and allocate them to an address.. Only callably by a crowdsale contract (mint agent). / | function mint(address receiver, uint amount) onlyMintAgent canMint public {
totalSupply = safeAdd(totalSupply, amount);
balances[receiver] = safeAdd(balances[receiver], amount);
// This will make the mint transaction apper in EtherScan.io
// We can remove this after there is a standardized minting event
Transfer(0, receiver, amount);
}
| function mint(address receiver, uint amount) onlyMintAgent canMint public {
totalSupply = safeAdd(totalSupply, amount);
balances[receiver] = safeAdd(balances[receiver], amount);
// This will make the mint transaction apper in EtherScan.io
// We can remove this after there is a standardized minting event
Transfer(0, receiver, amount);
}
| 36,583 |
48 | // Whether `a` is greater than or equal to `b`. a a FixedPoint.Signed. b a FixedPoint.Signed.return True if `a >= b`, or False. / | function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
| function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
| 19,192 |
12 | // Register retirement events. This function can only be called by a TC02 contract/ to register retirement events so they can be directly linked to an NFT mint./retiringEntity The entity that has retired TCO2 and is eligible to mint an NFT./projectVintageTokenId The vintage id of the TCO2 that is retired./amount The amount of the TCO2 that is retired./isLegacy Whether this event registration was executed by using the legacy retired/ amount in the TCO2 contract or utilizes the new retirement event design./ The function can either be only called by a valid TCO2 contract. | function registerEvent(
address retiringEntity,
uint256 projectVintageTokenId,
uint256 amount,
bool isLegacy
| function registerEvent(
address retiringEntity,
uint256 projectVintageTokenId,
uint256 amount,
bool isLegacy
| 24,854 |
0 | // This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}./ The beacon address. / | address immutable public beacon;
| address immutable public beacon;
| 33,420 |
5 | // Emitted when a fiAsset supply update is executed.// fiAsset The fiAsset with updated supply./ assetsThe new total supply./ yield The amount of yield added. | event TotalSupplyUpdated(address indexed fiAsset, uint256 assets, uint256 yield);
| event TotalSupplyUpdated(address indexed fiAsset, uint256 assets, uint256 yield);
| 21,185 |
6 | // Virtual range data set, ordering not guaranteed because removal just replaces position with last item and decreases collection size- data stored after range end. - range is readonly, data after can be altered./ | constructor(bytes32 _name, uint16 _start, uint16 _end, address _registry, uint16 _traitId) {
name = _name;
start = _start;
end = _end;
actualSize = _end - _start + 1;
traitId = _traitId;
ECRegistry = IECRegistry(_registry);
}
| constructor(bytes32 _name, uint16 _start, uint16 _end, address _registry, uint16 _traitId) {
name = _name;
start = _start;
end = _end;
actualSize = _end - _start + 1;
traitId = _traitId;
ECRegistry = IECRegistry(_registry);
}
| 72,037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.