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
203
// oods_coefficients[174]/ mload(add(context, 0x6f80)), Read the next element.
let columnValue := mulmod(mload(add(compositionQueryResponses, 0x20)), kMontgomeryRInv, PRIME)
let columnValue := mulmod(mload(add(compositionQueryResponses, 0x20)), kMontgomeryRInv, PRIME)
28,932
2
// Calls an external contract with arbitrary data and parse the return value into an address. externalContract The address of the contract to call. callData The data to send to the contract.return contractAddress The address of the contract returned by the call. /
function callAndReturnContractAddress(address externalContract, bytes calldata callData) internal returns (address payable contractAddress)
function callAndReturnContractAddress(address externalContract, bytes calldata callData) internal returns (address payable contractAddress)
11,722
9
// Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significandof a number with 18 decimals precision. /
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); }
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); }
26,621
0
// Swap./callArgs The args needed for swapping./amountETH ETH amount. If swap ETH for other token, amountETH is the amount to swap./ Else amountETH is 0.
function swap(bytes memory callArgs, uint256 amountETH) external onlyDelegation { (bool success, bytes memory returnData) = oneInchRouter.call{ value: amountETH }(callArgs);
function swap(bytes memory callArgs, uint256 amountETH) external onlyDelegation { (bool success, bytes memory returnData) = oneInchRouter.call{ value: amountETH }(callArgs);
13,313
15
// Raising event
emit Withdraw(tokensToSend, block.timestamp);
emit Withdraw(tokensToSend, block.timestamp);
27,176
0
// Main token smart contract
contract JEWToken is ERC20Mintable { string public constant name = "JEW"; string public constant symbol = "JEW"; uint8 public constant decimals = 2; }
contract JEWToken is ERC20Mintable { string public constant name = "JEW"; string public constant symbol = "JEW"; uint8 public constant decimals = 2; }
12,463
1,206
// 605
entry "rubberily" : ENG_ADVERB
entry "rubberily" : ENG_ADVERB
21,441
81
// LayerZero endpoint will invoke this function to deliver the message on the destination_srcChainId - the source endpoint identifier_srcAddress - the source sending contract address from the source chain_nonce - the ordered message nonce_payload - the signed payload is the UA bytes has encoded to be sent
function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
2,721
0
// delete ๆ“ไฝœ็ฌฆๅฏไปฅ็”จไบŽ ไปปไฝ•ๅ˜้‡(mapping้™คๅค–), ๅฐ†ๅ…ถ่ฎพ็ฝฎๆˆ้ป˜่ฎคๅ€ผ delete ๅˆ ้™ค ่ฎพ็ฝฎๆˆ้ป˜่ฎคๅ€ผ
function delStr() public { delete str1; }
function delStr() public { delete str1; }
43,902
4
// Initializes the contract setting the deployer as the initial owner./
constructor() { _transferOwnership(_msgSender()); }
constructor() { _transferOwnership(_msgSender()); }
8,339
2
// Mapping storing the signer address for a given collection
mapping(address collection => address signer) private signerPerCollection;
mapping(address collection => address signer) private signerPerCollection;
13,935
23
// Freeze used bounty company
function pay_Bounty(address _address, uint _sum_pay ) onlyOwner public { transfer(_address, _sum_pay); Freeze(_address, 1); }
function pay_Bounty(address _address, uint _sum_pay ) onlyOwner public { transfer(_address, _sum_pay); Freeze(_address, 1); }
48,284
22
// Assigns ownership of a specific Kitty to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal { // since the number of kittens is capped to 2^32 // there is no way to overflow this ownershipTokenCount[_to]++; // transfer ownership kittyIndexToOwner[_tokenId] = _to; // When creating new kittens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the kitten is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete kittyIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); }
function _transfer(address _from, address _to, uint256 _tokenId) internal { // since the number of kittens is capped to 2^32 // there is no way to overflow this ownershipTokenCount[_to]++; // transfer ownership kittyIndexToOwner[_tokenId] = _to; // When creating new kittens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // once the kitten is transferred also clear sire allowances delete sireAllowedToAddress[_tokenId]; // clear any previously approved ownership exchange delete kittyIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); }
49,713
65
// mint and distribute short and long position tokens to our caller
PositionToken(LONG_POSITION_TOKEN).mintAndSendToken(qtyToMint, minter); PositionToken(SHORT_POSITION_TOKEN).mintAndSendToken(qtyToMint, minter);
PositionToken(LONG_POSITION_TOKEN).mintAndSendToken(qtyToMint, minter); PositionToken(SHORT_POSITION_TOKEN).mintAndSendToken(qtyToMint, minter);
15,801
11
// Amount the contract borrowed
int256 public minted_sum_historical = 0; int256 public burned_sum_historical = 0;
int256 public minted_sum_historical = 0; int256 public burned_sum_historical = 0;
6,380
150
// A Yieldspace AMM implementation for pools which provide liquidity and trading of fyTokens vs base tokens./ The base tokens in this implementation are converted to ERC4626 compliant tokenized vault shares./ See whitepaper and derived formulas: https:hackmd.io/lRZ4mgdrRgOpxZQXqKYlFwUseful terminology:base - Example: DAI. The underlying token of the fyToken. Sometimes referred to as "asset" or "base".shares - Example: yvDAI. Upon receipt, base is deposited (wrapped) in a tokenized vault.c - Current price of shares in terms of base (in 64.64 bit)mu - also called c0 is the initial c of shares at contract deploymentReserves are tracked in sharesmu for consistency./ Pool.sol/ Uses ABDK
contract Pool is PoolEvents, IPool, ERC20Permit, AccessControl { /* LIBRARIES *****************************************************************************************************************/ using WDiv for uint256; using RDiv for uint256; using Math64x64 for int128; using Math64x64 for uint256; using CastU128I128 for uint128; using CastU128U104 for uint128; using CastU256U104 for uint256; using CastU256U128 for uint256; using CastU256I256 for uint256; using MinimalTransferHelper for IMaturingToken; using MinimalTransferHelper for IERC20Like; /* MODIFIERS *****************************************************************************************************************/ /// Trading can only be done before maturity. modifier beforeMaturity() { if (block.timestamp >= maturity) revert AfterMaturity(); _; } /* IMMUTABLES *****************************************************************************************************************/ /// The fyToken for the corresponding base token. Ex. yvDAI's fyToken will be fyDAI. Even though we convert base /// in this contract to a wrapped tokenized vault (e.g. Yearn Vault Dai), the fyToken is still payable in /// the base token upon maturity. IMaturingToken public immutable fyToken; /// This pool accepts a pair of base and fyToken tokens. /// When these are deposited into a tokenized vault they become shares. /// It is an ERC20 token. IERC20Like public immutable baseToken; /// Decimals of base tokens (fyToken, lp token, and usually the sharesToken). uint256 public immutable baseDecimals; /// When base comes into this contract it is deposited into a 3rd party tokenized vault in return for shares. /// @dev For most of this contract, only the ERC20 functionality of the shares token is required. As such, shares /// are cast as "IERC20Like" and when that 4626 functionality is needed, they are recast as IERC4626. /// This wei, modules for non-4626 compliant base tokens can import this contract and override 4626 specific fn's. IERC20Like public immutable sharesToken; /// Time stretch == 1 / seconds in x years where x varies per contract (64.64) int128 public immutable ts; /// The normalization coefficient, the initial c value or price per 1 share of base (64.64) int128 public immutable mu; /// Pool's maturity date (not 64.64) uint32 public immutable maturity; /// Used to scale up to 18 decimals (not 64.64) uint96 public immutable scaleFactor; /* STRUCTS *****************************************************************************************************************/ struct Cache { uint16 g1Fee; uint104 sharesCached; uint104 fyTokenCached; uint32 blockTimestampLast; } /* STORAGE *****************************************************************************************************************/ // The following 4 vars use one storage slot and can be retrieved in a Cache struct with getCache() /// This number is used to calculate the fees for buying/selling fyTokens. /// @dev This is a fp4 that represents a ratio out 1, where 1 is represented by 10000. uint16 public g1Fee; /// Shares reserves, cached. uint104 internal sharesCached; /// fyToken reserves, cached. uint104 internal fyTokenCached; /// block.timestamp of last time reserve caches were updated. uint32 internal blockTimestampLast; /// This is a LAGGING, time weighted sum of the fyToken:shares reserves ratio measured in ratio seconds. /// @dev Footgun ๐Ÿ”ซ alert! Be careful, this number is probably not what you need and it should normally be /// considered with blockTimestampLast. For consumption as a TWAR observation, use currentCumulativeRatio(). /// In future pools, this function's visibility may be changed to internal. /// @return a fixed point factor with 27 decimals (ray). uint256 public cumulativeRatioLast; /* CONSTRUCTOR FUNCTIONS *****************************************************************************************************************/ constructor( address sharesToken_, // address of shares token address fyToken_, // address of fyToken int128 ts_, // time stretch(64.64) uint16 g1Fee_ // fees (in bps) when buying fyToken ) ERC20Permit( string(abi.encodePacked(IERC20Like(fyToken_).name(), " LP")), string(abi.encodePacked(IERC20Like(fyToken_).symbol(), "LP")), IERC20Like(fyToken_).decimals() ) { /* __ __ __ ___ __ __ ___ __ __ / ` / \ |\ | /__` | |__) | | / ` | / \ |__) \__, \__/ | \| .__/ | | \ \__/ \__, | \__/ | \ */ // Set maturity with check to make sure its not 2107 yet. uint256 maturity_ = IMaturingToken(fyToken_).maturity(); if (maturity_ > uint256(type(uint32).max)) revert MaturityOverflow(); maturity = uint32(maturity_); // Set sharesToken. sharesToken = IERC20Like(sharesToken_); // Cache baseToken to save loads of SLOADs. IERC20Like baseToken_ = _getBaseAsset(sharesToken_); // Call approve hook for sharesToken. _approveSharesToken(baseToken_, sharesToken_); // NOTE: LP tokens, baseToken and fyToken should have the same decimals. Within this core contract, it is // presumed that sharesToken also has the same decimals. If this is not the case, a separate module must be // used to overwrite _getSharesBalance() and other affected functions (see PoolEuler.sol for example). baseDecimals = baseToken_.decimals(); // Set other immutables. baseToken = baseToken_; fyToken = IMaturingToken(fyToken_); ts = ts_; scaleFactor = uint96(10**(18 - uint96(baseDecimals))); // No more than 18 decimals allowed, reverts on underflow. // Set mu with check for 0. if ((mu = _getC()) == 0) { revert MuCannotBeZero(); } // Set g1Fee state variable with out of bounds check. if ((g1Fee = g1Fee_) > 10000) revert InvalidFee(g1Fee_); emit FeesSet(g1Fee_); } /// This is used by the constructor to give max approval to sharesToken. /// @dev This should be overridden by modules if needed. function _approveSharesToken(IERC20Like baseToken_, address sharesToken_) internal virtual { bool success = baseToken_.approve(sharesToken_, type(uint256).max); if (!success) { revert ApproveFailed(); } } /// This is used by the constructor to set the base token as immutable. /// @dev This should be overridden by modules. /// We use the IERC20Like interface, but this should be an ERC20 asset per EIP4626. function _getBaseAsset(address sharesToken_) internal virtual returns (IERC20Like) { return IERC20Like(address(IERC4626(sharesToken_).asset())); } /* LIQUIDITY FUNCTIONS โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ mint, new life. gm! โ”‚ โ”‚ buy, sell, mint more, trade, trade -- stop โ”‚ โ”‚ mature, burn. gg~ โ”‚ โ”‚ โ”‚ โ”‚ "Watashinojinsei (My Life)" - haiku by Poolie โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ *****************************************************************************************************************/ /*mint v ___ \ / |_ \_/ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” | | โ”‚ โ”‚ ` _......._ ' gm! \โ”‚ โ”‚/ .-:::::::::::-. โ”‚ \โ”‚ โ”‚/ ` : __ ____ : / โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”‚ mint โ”‚ :: / / / __ \:: โ”‚ โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ–ถ _ :: / / / /_/ /:: _ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”‚ โ”‚ :: / /___/ ____/ :: โ”‚ /โ”‚ โ”‚\ ::/_____/_/ :: /โ”‚ โ”‚\ ' : : ` B A S E โ”‚ \(^o^)/ โ”‚ `-:::::::::::-' โ”‚ Pool.sol โ”‚ , `'''''''` . โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ / \ ^ */ /// Mint liquidity tokens in exchange for adding base and fyToken /// The amount of liquidity tokens to mint is calculated from the amount of unaccounted for fyToken in this contract. /// A proportional amount of asset tokens need to be present in this contract, also unaccounted for. /// @dev _totalSupply > 0 check important here to prevent unauthorized initialization. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any surplus base. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return baseIn The amount of base found in the contract that was used for the mint. /// @return fyTokenIn The amount of fyToken found that was used for the mint /// @return lpTokensMinted The amount of LP tokens minted. function mint( address to, address remainder, uint256 minRatio, uint256 maxRatio ) external virtual override returns ( uint256 baseIn, uint256 fyTokenIn, uint256 lpTokensMinted ) { if (_totalSupply == 0) revert NotInitialized(); (baseIn, fyTokenIn, lpTokensMinted) = _mint(to, remainder, 0, minRatio, maxRatio); } // โ•ฆโ”Œโ”โ”Œโ”ฌโ”Œโ”ฌโ”โ”ฌโ”Œโ”€โ”โ”ฌ โ”ฌโ”Œโ”€โ”โ”Œโ”€โ” โ•”โ•โ•—โ”Œโ”€โ”โ”Œโ”€โ”โ”ฌ // โ•‘โ”‚โ”‚โ”‚โ”‚ โ”‚ โ”‚โ”œโ”€โ”คโ”‚ โ”‚โ”Œโ”€โ”˜โ”œโ”ค โ• โ•โ•โ”‚ โ”‚โ”‚ โ”‚โ”‚ // โ•ฉโ”˜โ””โ”˜โ”ด โ”ด โ”ดโ”ด โ”ดโ”ดโ”€โ”˜โ”ดโ””โ”€โ”˜โ””โ”€โ”˜ โ•ฉ โ””โ”€โ”˜โ””โ”€โ”˜โ”ดโ”€โ”˜ /// @dev This is the exact same as mint() but with auth added and skip the supply > 0 check /// and checks instead that supply == 0. /// This intialize mechanism is different than UniV2. Tokens addresses are added at contract creation. /// This pool is considered initialized after the first LP token is minted. /// @param to Wallet receiving the minted liquidity tokens. /// @return baseIn The amount of base found that was used for the mint. /// @return fyTokenIn The amount of fyToken found that was used for the mint /// @return lpTokensMinted The amount of LP tokens minted. function init(address to) external virtual auth returns ( uint256 baseIn, uint256 fyTokenIn, uint256 lpTokensMinted ) { if (_totalSupply != 0) revert Initialized(); // address(this) used for the remainder, but actually this parameter is not used at all in this case because // there will never be any left over base in this case (baseIn, fyTokenIn, lpTokensMinted) = _mint(to, address(this), 0, 0, type(uint256).max); emit gm(); } /* mintWithBase V โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” \ / โ”‚ โ”‚ ` _......._ ' gm! \โ”‚ โ”‚/ .-:::::::::::-. \โ”‚ โ”‚/ ` : __ ____ : / โ”‚ mintWithBase โ”‚ :: / / / __ \:: B A S E โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”‚ โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ–ถ _ :: / / / /_/ /:: _ โ”‚ โ”‚ :: / /___/ ____/ :: /โ”‚ โ”‚\ ::/_____/_/ :: /โ”‚ โ”‚\ ' : : ` โ”‚ \(^o^)/ โ”‚ `-:::::::::::-' โ”‚ Pool.sol โ”‚ , `'''''''` . โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ / \ ^ */ /// Mint liquidity tokens in exchange for adding only base. /// The amount of liquidity tokens is calculated from the amount of fyToken to buy from the pool. /// The base tokens need to be previously transferred and present in this contract. /// @dev _totalSupply > 0 check important here to prevent minting before initialization. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any leftover base at the end. /// @param fyTokenToBuy Amount of `fyToken` being bought in the Pool, from this we calculate how much base it will be taken in. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return baseIn The amount of base found that was used for the mint. /// @return fyTokenIn The amount of fyToken found that was used for the mint /// @return lpTokensMinted The amount of LP tokens minted. function mintWithBase( address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio ) external virtual override returns ( uint256 baseIn, uint256 fyTokenIn, uint256 lpTokensMinted ) { if (_totalSupply == 0) revert NotInitialized(); (baseIn, fyTokenIn, lpTokensMinted) = _mint(to, remainder, fyTokenToBuy, minRatio, maxRatio); } /// This is the internal function called by the external mint functions. /// Mint liquidity tokens, with an optional internal trade to buy fyToken beforehand. /// The amount of liquidity tokens is calculated from the amount of fyTokenToBuy from the pool, /// plus the amount of extra, unaccounted for fyToken in this contract. /// The base tokens also need to be previously transferred and present in this contract. /// Only usable before maturity. /// @dev Warning: This fn does not check if supply > 0 like the external functions do. /// This function overloads the ERC20._mint(address, uint) function. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any surplus base. /// @param fyTokenToBuy Amount of `fyToken` being bought in the Pool. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return baseIn The amount of base found that was used for the mint. /// @return fyTokenIn The amount of fyToken found that was used for the mint /// @return lpTokensMinted The amount of LP tokens minted. function _mint( address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio ) internal beforeMaturity returns ( uint256 baseIn, uint256 fyTokenIn, uint256 lpTokensMinted ) { // Wrap all base found in this contract. baseIn = baseToken.balanceOf(address(this)); _wrap(address(this)); // Gather data uint256 supply = _totalSupply; Cache memory cache = _getCache(); uint256 realFYTokenCached_ = cache.fyTokenCached - supply; // The fyToken cache includes the virtual fyToken, equal to the supply uint256 sharesBalance = _getSharesBalance(); // Check the burn wasn't sandwiched if (realFYTokenCached_ != 0) { if ( uint256(cache.sharesCached).wdiv(realFYTokenCached_) < minRatio || uint256(cache.sharesCached).wdiv(realFYTokenCached_) > maxRatio ) revert SlippageDuringMint(uint256(cache.sharesCached).wdiv(realFYTokenCached_), minRatio, maxRatio); } else if (maxRatio < type(uint256).max) { revert SlippageDuringMint(type(uint256).max, minRatio, maxRatio); } // Calculate token amounts uint256 sharesIn; if (supply == 0) { // **First mint** // Initialize at 1 pool token sharesIn = sharesBalance; lpTokensMinted = _mulMu(sharesIn); } else if (realFYTokenCached_ == 0) { // Edge case, no fyToken in the Pool after initialization sharesIn = sharesBalance - cache.sharesCached; lpTokensMinted = (supply * sharesIn) / cache.sharesCached; } else { // There is an optional virtual trade before the mint uint256 sharesToSell; if (fyTokenToBuy != 0) { sharesToSell = _buyFYTokenPreview( fyTokenToBuy.u128(), cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee) ); } // We use all the available fyTokens, plus optional virtual trade. Surplus is in base tokens. fyTokenIn = fyToken.balanceOf(address(this)) - realFYTokenCached_; lpTokensMinted = (supply * (fyTokenToBuy + fyTokenIn)) / (realFYTokenCached_ - fyTokenToBuy); sharesIn = sharesToSell + ((cache.sharesCached + sharesToSell) * lpTokensMinted) / supply; if ((sharesBalance - cache.sharesCached) < sharesIn) { revert NotEnoughBaseIn(_unwrapPreview(sharesBalance - cache.sharesCached), _unwrapPreview(sharesIn)); } } // Update TWAR _update( (cache.sharesCached + sharesIn).u128(), (cache.fyTokenCached + fyTokenIn + lpTokensMinted).u128(), // Include "virtual" fyToken from new minted LP tokens cache.sharesCached, cache.fyTokenCached ); // Execute mint _mint(to, lpTokensMinted); // Return any unused base tokens if (sharesBalance > cache.sharesCached + sharesIn) _unwrap(remainder); // confirm new virtual fyToken balance is not less than new supply if ((cache.fyTokenCached + fyTokenIn + lpTokensMinted) < supply + lpTokensMinted) { revert FYTokenCachedBadState(); } emit Liquidity( maturity, msg.sender, to, address(0), -(baseIn.i256()), -(fyTokenIn.i256()), lpTokensMinted.i256() ); } /* burn ( ( ) ( ( (| (| ) ) )\/ ( \/(( ( gg ___ (( / ))\))))\ โ”Œ~~~~~~โ–บ |_ \_/ )\( | ) โ”‚ | | /: | __ ____/: โ”‚ :: / / / __ \:: โ”€โ”€โ”€โ”ค :: / / / /_/ /:: โ”‚ :: / /___/ ____/ :: โ””~~~~~~โ–บ B A S E ::/_____/_/ :: : : `-:::::::::::-' `'''''''` */ /// Burn liquidity tokens in exchange for base and fyToken. /// The liquidity tokens need to be previously tranfsferred to this contract. /// @param baseTo Wallet receiving the base tokens. /// @param fyTokenTo Wallet receiving the fyTokens. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return lpTokensBurned The amount of LP tokens burned. /// @return baseOut The amount of base tokens received. /// @return fyTokenOut The amount of fyTokens received. function burn( address baseTo, address fyTokenTo, uint256 minRatio, uint256 maxRatio ) external virtual override returns ( uint256 lpTokensBurned, uint256 baseOut, uint256 fyTokenOut ) { (lpTokensBurned, baseOut, fyTokenOut) = _burn(baseTo, fyTokenTo, false, minRatio, maxRatio); } /* burnForBase ( ( ) ( ( (| (| ) ) )\/ ( \/(( ( gg (( / ))\))))\ )\( | ) /: | __ ____/: :: / / / __ \:: ~~~~~~~โ–บ B A S E :: / / / /_/ /:: :: / /___/ ____/ :: ::/_____/_/ :: : : `-:::::::::::-' `'''''''` */ /// Burn liquidity tokens in exchange for base. /// The liquidity provider needs to have called `pool.approve`. /// Only usable before maturity. /// @param to Wallet receiving the base and fyToken. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return lpTokensBurned The amount of lp tokens burned. /// @return baseOut The amount of base tokens returned. function burnForBase( address to, uint256 minRatio, uint256 maxRatio ) external virtual override beforeMaturity returns (uint256 lpTokensBurned, uint256 baseOut) { (lpTokensBurned, baseOut, ) = _burn(to, address(0), true, minRatio, maxRatio); } /// Burn liquidity tokens in exchange for base. /// The liquidity provider needs to have called `pool.approve`. /// @dev This function overloads the ERC20._burn(address, uint) function. /// @param baseTo Wallet receiving the base. /// @param fyTokenTo Wallet receiving the fyToken. /// @param tradeToBase Whether the resulting fyToken should be traded for base tokens. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return lpTokensBurned The amount of pool tokens burned. /// @return baseOut The amount of base tokens returned. /// @return fyTokenOut The amount of fyTokens returned. function _burn( address baseTo, address fyTokenTo, bool tradeToBase, uint256 minRatio, uint256 maxRatio ) internal returns ( uint256 lpTokensBurned, uint256 baseOut, uint256 fyTokenOut ) { // Gather data lpTokensBurned = _balanceOf[address(this)]; uint256 supply = _totalSupply; Cache memory cache = _getCache(); uint96 scaleFactor_ = scaleFactor; // The fyToken cache includes the virtual fyToken, equal to the supply. uint256 realFYTokenCached_ = cache.fyTokenCached - supply; // Check the burn wasn't sandwiched if (realFYTokenCached_ != 0) { if ( (uint256(cache.sharesCached).wdiv(realFYTokenCached_) < minRatio) || (uint256(cache.sharesCached).wdiv(realFYTokenCached_) > maxRatio) ) { revert SlippageDuringBurn(uint256(cache.sharesCached).wdiv(realFYTokenCached_), minRatio, maxRatio); } } // Calculate trade uint256 sharesOut = (lpTokensBurned * cache.sharesCached) / supply; fyTokenOut = (lpTokensBurned * realFYTokenCached_) / supply; if (tradeToBase) { sharesOut += YieldMath.sharesOutForFYTokenIn( // This is a virtual sell (cache.sharesCached - sharesOut.u128()) * scaleFactor_, // Cache, minus virtual burn (cache.fyTokenCached - fyTokenOut.u128()) * scaleFactor_, // Cache, minus virtual burn fyTokenOut.u128() * scaleFactor_, // Sell the virtual fyToken obtained maturity - uint32(block.timestamp), // This can't be called after maturity ts, _computeG2(cache.g1Fee), _getC(), mu ) / scaleFactor_; fyTokenOut = 0; } // Update TWAR _update( (cache.sharesCached - sharesOut).u128(), (cache.fyTokenCached - fyTokenOut - lpTokensBurned).u128(), // Exclude "virtual" fyToken from new minted LP tokens cache.sharesCached, cache.fyTokenCached ); // Burn and transfer _burn(address(this), lpTokensBurned); // This is calling the actual ERC20 _burn. baseOut = _unwrap(baseTo); if (fyTokenOut != 0) fyToken.safeTransfer(fyTokenTo, fyTokenOut); // confirm new virtual fyToken balance is not less than new supply if ((cache.fyTokenCached - fyTokenOut - lpTokensBurned) < supply - lpTokensBurned) { revert FYTokenCachedBadState(); } emit Liquidity( maturity, msg.sender, baseTo, fyTokenTo, baseOut.i256(), fyTokenOut.i256(), -(lpTokensBurned.i256()) ); if (supply == lpTokensBurned && block.timestamp >= maturity) { emit gg(); } } /* TRADING FUNCTIONS ****************************************************************************************************************/ /* buyBase I want to buy `uint128 baseOut` worth of base tokens. _______ I've transferred you some fyTokens -- that should be enough. / GUY \ .:::::::::::::::::. (^^^| \=========== : _______ __ __ : โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” \(\/ | _ _ | :: | || | | |:: โ”‚no โ”‚ \ \ (. o o | ::: | ___|| |_| |::: โ”‚lifeguardโ”‚ \ \ | ~ | ::: | |___ | |::: โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜ ==+ \ \ \ == / ::: | ___||_ _|:: ok guy โ”‚ โ”‚ =======+ \ \___| |___ ::: | | | | ::: _____โ”‚_____โ”‚______ |+ \ / \__/ \ :: |___| |___| :: .-'"___________________`-.|+ \ \ : : ( .'" '-.)+ --| GUY |\_/\ / `:::::::::::::::::' |`-..__________________..-'|+ | | \ \/ / `-:::::::::::-' | |+ | | \ / `'''''''` | |+ | | \_/ | --- --- |+ |______| | (o ) (o ) |+ |__GG__| โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /`| |+ | | โ”‚$ $โ”‚ / /| [ |+ | | | โ”‚ B A S E โ”‚ / / | ---------- |+ | | _| โ”‚ baseOut โ”‚\.-" ; \ \________/ /+ | | | โ”‚$ $โ”‚),.-' `-..__________________..-' += | | | โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ | | | | ( ( | | | | | | | | | | | | | | | T----T T----T _| | | _..._L____J L____J _..._ (_____[__) .` "-. `% | | %` .-" `. / \ .: :. / \ '-..___|_..=:` `-:=.._|___..-' */ /// Buy base with fyToken. /// The trader needs to have transferred in the necessary amount of fyTokens in advance. /// @param to Wallet receiving the base being bought. /// @param baseOut Amount of base being bought that will be deposited in `to` wallet. /// @param max This has been deprecated and was left in for backwards compatibility. /// @return fyTokenIn Amount of fyToken that will be taken from caller. function buyBase( address to, uint128 baseOut, uint128 max ) external virtual override returns (uint128 fyTokenIn) { // Calculate trade and cache values uint128 fyTokenBalance = _getFYTokenBalance(); Cache memory cache = _getCache(); uint128 sharesOut = _wrapPreview(baseOut).u128(); fyTokenIn = _buyBasePreview(sharesOut, cache.sharesCached, cache.fyTokenCached, _computeG2(cache.g1Fee)); // Checks if (fyTokenBalance - cache.fyTokenCached < fyTokenIn) { revert NotEnoughFYTokenIn(fyTokenBalance - cache.fyTokenCached, fyTokenIn); } // Update TWAR _update( cache.sharesCached - sharesOut, cache.fyTokenCached + fyTokenIn, cache.sharesCached, cache.fyTokenCached ); // Transfer _unwrap(to); emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128())); } /// Returns how much fyToken would be required to buy `baseOut` base. /// @dev Note: This fn takes baseOut as a param while the internal fn takes sharesOut. /// @param baseOut Amount of base hypothetically desired. /// @return fyTokenIn Amount of fyToken hypothetically required. function buyBasePreview(uint128 baseOut) external view virtual override returns (uint128 fyTokenIn) { Cache memory cache = _getCache(); fyTokenIn = _buyBasePreview( _wrapPreview(baseOut).u128(), cache.sharesCached, cache.fyTokenCached, _computeG2(cache.g1Fee) ); } /// Returns how much fyToken would be required to buy `sharesOut`. /// @dev Note: This fn takes sharesOut as a param while the external fn takes baseOut. function _buyBasePreview( uint128 sharesOut, uint104 sharesBalance, uint104 fyTokenBalance, int128 g2_ ) internal view beforeMaturity returns (uint128 fyTokenIn) { uint96 scaleFactor_ = scaleFactor; fyTokenIn = YieldMath.fyTokenInForSharesOut( sharesBalance * scaleFactor_, fyTokenBalance * scaleFactor_, sharesOut * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g2_, _getC(), mu ) / scaleFactor_; } /*buyFYToken I want to buy `uint128 fyTokenOut` worth of fyTokens. _______ I've transferred you some base tokens -- that should be enough. / GUY \ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” (^^^| \=========== โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚no โ”‚ \(\/ | _ _ | โ”‚$ $โ”‚ โ”‚lifeguardโ”‚ \ \ (. o o | โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ” โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜ ==+ \ \ | ~ | โ”‚ โ”‚$ $โ”‚ hmm, let's see here โ”‚ โ”‚ =======+ \ \ \ == / โ”‚ โ”‚ B A S E โ”‚ _____โ”‚_____โ”‚______ |+ \ \___| |___ โ”‚$โ”‚ โ”‚ .-'"___________________`-.|+ \ / \__/ \ โ””โ”€โ”ค$ $โ”‚ ( .'" '-.)+ \ \ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ |`-..__________________..-'|+ --| GUY |\_/\ / / | |+ | | \ \/ / | |+ | | \ / _......._ /`| --- --- |+ | | \_/ .-:::::::::::-. / /| (o ) (o ) |+ |______| .:::::::::::::::::. / / | |+ |__GG__| : _______ __ __ : _.-" ; | [ |+ | | :: | || | | |::),.-' | ---------- |+ | | | ::: | ___|| |_| |:::/ \ \________/ /+ | | _| ::: | |___ | |::: `-..__________________..-' += | | | ::: | ___||_ _|::: | | | | | | | ::: | | | | ::: | | | | ( ( | :: |___| |___| :: | | | | | | | : fyTokenOut : T----T T----T | | | `:::::::::::::::::' _..._L____J L____J _..._ _| | | `-:::::::::::-' .` "-. `% | | %` .-" `. (_____[__) `'''''''` / \ .: :. / \ '-..___|_..=:` `-:=.._|___..-' */ /// Buy fyToken with base. /// The trader needs to have transferred in the correct amount of base tokens in advance. /// @param to Wallet receiving the fyToken being bought. /// @param fyTokenOut Amount of fyToken being bought that will be deposited in `to` wallet. /// @param max This has been deprecated and was left in for backwards compatibility. /// @return baseIn Amount of base that will be used. function buyFYToken( address to, uint128 fyTokenOut, uint128 max ) external virtual override returns (uint128 baseIn) { // Wrap any base assets found in contract. _wrap(address(this)); // Calculate trade uint128 sharesBalance = _getSharesBalance(); Cache memory cache = _getCache(); uint128 sharesIn = _buyFYTokenPreview( fyTokenOut, cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee) ); baseIn = _unwrapPreview(sharesIn).u128(); // Checks if (sharesBalance - cache.sharesCached < sharesIn) revert NotEnoughBaseIn(_unwrapPreview(sharesBalance - cache.sharesCached), baseIn); // Update TWAR _update( cache.sharesCached + sharesIn, cache.fyTokenCached - fyTokenOut, cache.sharesCached, cache.fyTokenCached ); // Transfer fyToken.safeTransfer(to, fyTokenOut); // confirm new virtual fyToken balance is not less than new supply if ((cache.fyTokenCached - fyTokenOut) < _totalSupply) { revert FYTokenCachedBadState(); } emit Trade(maturity, msg.sender, to, -(baseIn.i128()), fyTokenOut.i128()); } /// Returns how much base would be required to buy `fyTokenOut`. /// @param fyTokenOut Amount of fyToken hypothetically desired. /// @dev Note: This returns an amount in base. The internal fn returns amount of shares. /// @return baseIn Amount of base hypothetically required. function buyFYTokenPreview(uint128 fyTokenOut) external view virtual override returns (uint128 baseIn) { Cache memory cache = _getCache(); uint128 sharesIn = _buyFYTokenPreview( fyTokenOut, cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee) ); baseIn = _unwrapPreview(sharesIn).u128(); } /// Returns how many shares are required to buy `fyTokenOut` fyTokens. /// @dev Note: This returns an amount in shares. The external fn returns amount of base. function _buyFYTokenPreview( uint128 fyTokenOut, uint128 sharesBalance, uint128 fyTokenBalance, int128 g1_ ) internal view beforeMaturity returns (uint128 sharesIn) { uint96 scaleFactor_ = scaleFactor; sharesIn = YieldMath.sharesInForFYTokenOut( sharesBalance * scaleFactor_, fyTokenBalance * scaleFactor_, fyTokenOut * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g1_, _getC(), mu ) / scaleFactor_; uint128 newSharesMulMu = _mulMu(sharesBalance + sharesIn).u128(); if ((fyTokenBalance - fyTokenOut) < newSharesMulMu) { revert NegativeInterestRatesNotAllowed(fyTokenBalance - fyTokenOut, newSharesMulMu); } } /* sellBase I've transfered you some base tokens. _______ Can you swap them for fyTokens? / GUY \ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” (^^^| \=========== โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚no โ”‚ \(\/ | _ _ | โ”‚$ $โ”‚ โ”‚lifeguardโ”‚ \ \ (. o o | โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ” โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜ ==+ \ \ | ~ | โ”‚ โ”‚$ $โ”‚ can โ”‚ โ”‚ =======+ \ \ \ == / โ”‚ โ”‚ โ”‚ _____โ”‚_____โ”‚______ |+ \ \___| |___ โ”‚$โ”‚ baseIn โ”‚ .-'"___________________`-.|+ \ / \__/ \ โ””โ”€โ”ค$ $โ”‚ ( .'" '-.)+ \ \ ( โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ |`-..__________________..-'|+ --| GUY |\_/\ / / | |+ | | \ \/ / | |+ | | \ / _......._ /`| --- --- |+ | | \_/ .-:::::::::::-. / /| (o ) (o ) |+ |______| .:::::::::::::::::. / / | |+ |__GG__| : _______ __ __ : _.-" ; | [ |+ | | :: | || | | |::),.-' | ---------- |+ | | | ::: | ___|| |_| |:::/ \ \________/ /+ | | _| ::: | |___ | |::: `-..__________________..-' += | | | ::: | ___||_ _|::: | | | | | | | ::: | | | | ::: | | | | ( ( | :: |___| |___| :: | | | | | | | : ???? : T----T T----T | | | `:::::::::::::::::' _..._L____J L____J _..._ _| | | `-:::::::::::-' .` "-. `% | | %` .-" `. (_____[__) `'''''''` / \ .: :. / \ '-..___|_..=:` `-:=.._|___..-' */ /// Sell base for fyToken. /// The trader needs to have transferred the amount of base to sell to the pool before calling this fn. /// @param to Wallet receiving the fyToken being bought. /// @param min Minimum accepted amount of fyToken. /// @return fyTokenOut Amount of fyToken that will be deposited on `to` wallet. function sellBase(address to, uint128 min) external virtual override returns (uint128 fyTokenOut) { // Wrap any base assets found in contract. _wrap(address(this)); // Calculate trade Cache memory cache = _getCache(); uint104 sharesBalance = _getSharesBalance(); uint128 sharesIn = sharesBalance - cache.sharesCached; fyTokenOut = _sellBasePreview(sharesIn, cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee)); // Check slippage if (fyTokenOut < min) revert SlippageDuringSellBase(fyTokenOut, min); // Update TWAR _update(sharesBalance, cache.fyTokenCached - fyTokenOut, cache.sharesCached, cache.fyTokenCached); // Transfer fyToken.safeTransfer(to, fyTokenOut); // confirm new virtual fyToken balance is not less than new supply if ((cache.fyTokenCached - fyTokenOut) < _totalSupply) { revert FYTokenCachedBadState(); } emit Trade(maturity, msg.sender, to, -(_unwrapPreview(sharesIn).u128().i128()), fyTokenOut.i128()); } /// Returns how much fyToken would be obtained by selling `baseIn`. /// @dev Note: This external fn takes baseIn while the internal fn takes sharesIn. /// @param baseIn Amount of base hypothetically sold. /// @return fyTokenOut Amount of fyToken hypothetically bought. function sellBasePreview(uint128 baseIn) external view virtual override returns (uint128 fyTokenOut) { Cache memory cache = _getCache(); fyTokenOut = _sellBasePreview( _wrapPreview(baseIn).u128(), cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee) ); } /// Returns how much fyToken would be obtained by selling `sharesIn`. /// @dev Note: This internal fn takes sharesIn while the external fn takes baseIn. function _sellBasePreview( uint128 sharesIn, uint104 sharesBalance, uint104 fyTokenBalance, int128 g1_ ) internal view beforeMaturity returns (uint128 fyTokenOut) { uint96 scaleFactor_ = scaleFactor; fyTokenOut = YieldMath.fyTokenOutForSharesIn( sharesBalance * scaleFactor_, fyTokenBalance * scaleFactor_, sharesIn * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g1_, _getC(), mu ) / scaleFactor_; uint128 newSharesMulMu = _mulMu(sharesBalance + sharesIn).u128(); if ((fyTokenBalance - fyTokenOut) < newSharesMulMu) { revert NegativeInterestRatesNotAllowed(fyTokenBalance - fyTokenOut, newSharesMulMu); } } /*sellFYToken I've transferred you some fyTokens. _______ Can you swap them for base? / GUY \ .:::::::::::::::::. (^^^| \=========== : _______ __ __ : โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” \(\/ | _ _ | :: | || | | |:: โ”‚no โ”‚ \ \ (. o o | ::: | ___|| |_| |::: โ”‚lifeguardโ”‚ \ \ | ~ | ::: | |___ | |::: โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜ ==+ \ \ \ == / ::: | ___||_ _|::: lfg โ”‚ โ”‚ =======+ \ \___| |___ ::: | | | | ::: _____โ”‚_____โ”‚______ |+ \ / \__/ \ :: |___| |___| :: .-'"___________________`-.|+ \ \ : fyTokenIn : ( .'" '-.)+ --| GUY |\_/\ / `:::::::::::::::::' |`-..__________________..-'|+ | | \ \/ / `-:::::::::::-' | |+ | | \ / `'''''''` | |+ | | \_/ | --- --- |+ |______| | (o ) (o ) |+ |__GG__| โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /`| |+ | | โ”‚$ $โ”‚ / /| [ |+ | | | โ”‚ B A S E โ”‚ / / | ---------- |+ | | _| โ”‚ ???? โ”‚\.-" ; \ \________/ /+ | | | โ”‚$ $โ”‚),.-' `-..__________________..-' += | | | โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ | | | | ( ( | | | | | | | | | | | | | | | T----T T----T _| | | _..._L____J L____J _..._ (_____[__) .` "-. `% | | %` .-" `. / \ .: :. / \ '-..___|_..=:` `-:=.._|___..-' */ /// Sell fyToken for base. /// The trader needs to have transferred the amount of fyToken to sell to the pool before in the same transaction. /// @param to Wallet receiving the base being bought. /// @param min Minimum accepted amount of base. /// @return baseOut Amount of base that will be deposited on `to` wallet. function sellFYToken(address to, uint128 min) external virtual override returns (uint128 baseOut) { // Calculate trade Cache memory cache = _getCache(); uint104 fyTokenBalance = _getFYTokenBalance(); uint128 fyTokenIn = fyTokenBalance - cache.fyTokenCached; uint128 sharesOut = _sellFYTokenPreview( fyTokenIn, cache.sharesCached, cache.fyTokenCached, _computeG2(cache.g1Fee) ); // Update TWAR _update(cache.sharesCached - sharesOut, fyTokenBalance, cache.sharesCached, cache.fyTokenCached); // Transfer baseOut = _unwrap(to).u128(); // Check slippage if (baseOut < min) revert SlippageDuringSellFYToken(baseOut, min); emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128())); } /// Returns how much base would be obtained by selling `fyTokenIn` fyToken. /// @dev Note: This external fn returns baseOut while the internal fn returns sharesOut. /// @param fyTokenIn Amount of fyToken hypothetically sold. /// @return baseOut Amount of base hypothetically bought. function sellFYTokenPreview(uint128 fyTokenIn) public view virtual returns (uint128 baseOut) { Cache memory cache = _getCache(); uint128 sharesOut = _sellFYTokenPreview( fyTokenIn, cache.sharesCached, cache.fyTokenCached, _computeG2(cache.g1Fee) ); baseOut = _unwrapPreview(sharesOut).u128(); } /// Returns how much shares would be obtained by selling `fyTokenIn` fyToken. /// @dev Note: This internal fn returns sharesOut while the external fn returns baseOut. function _sellFYTokenPreview( uint128 fyTokenIn, uint104 sharesBalance, uint104 fyTokenBalance, int128 g2_ ) internal view beforeMaturity returns (uint128 sharesOut) { uint96 scaleFactor_ = scaleFactor; sharesOut = YieldMath.sharesOutForFYTokenIn( sharesBalance * scaleFactor_, fyTokenBalance * scaleFactor_, fyTokenIn * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g2_, _getC(), mu ) / scaleFactor_; } /* LIQUIDITY FUNCTIONS ****************************************************************************************************************/ /// @inheritdoc IPool function maxFYTokenIn() public view override returns (uint128 fyTokenIn) { uint96 scaleFactor_ = scaleFactor; Cache memory cache = _getCache(); fyTokenIn = YieldMath.maxFYTokenIn( cache.sharesCached * scaleFactor_, cache.fyTokenCached * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, _computeG2(cache.g1Fee), _getC(), mu ) / scaleFactor_; } /// @inheritdoc IPool function maxFYTokenOut() public view override returns (uint128 fyTokenOut) { uint96 scaleFactor_ = scaleFactor; Cache memory cache = _getCache(); fyTokenOut = YieldMath.maxFYTokenOut( cache.sharesCached * scaleFactor_, cache.fyTokenCached * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, _computeG1(cache.g1Fee), _getC(), mu ) / scaleFactor_; } /// @inheritdoc IPool function maxBaseIn() public view override returns (uint128 baseIn) { uint96 scaleFactor_ = scaleFactor; Cache memory cache = _getCache(); uint128 sharesIn = ((YieldMath.maxSharesIn( cache.sharesCached * scaleFactor_, cache.fyTokenCached * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, _computeG1(cache.g1Fee), _getC(), mu ) / 1e8) * 1e8) / scaleFactor_; // Shave 8 wei/decimals to deal with precision issues on the decimal functions baseIn = _unwrapPreview(sharesIn).u128(); } /// @inheritdoc IPool function maxBaseOut() public view override returns (uint128 baseOut) { uint128 sharesOut = _getCache().sharesCached; baseOut = _unwrapPreview(sharesOut).u128(); } /// @inheritdoc IPool function invariant() public view override returns (uint128 result) { uint96 scaleFactor_ = scaleFactor; Cache memory cache = _getCache(); result = YieldMath.invariant( cache.sharesCached * scaleFactor_, cache.fyTokenCached * scaleFactor_, _totalSupply * scaleFactor_, maturity - uint32(block.timestamp), ts, _computeG2(cache.g1Fee), _getC(), mu ) / scaleFactor_; } /* WRAPPING FUNCTIONS ****************************************************************************************************************/ /// Wraps any base asset tokens found in the contract, converting them to base tokenized vault shares. /// @dev This is provided as a convenience and uses the 4626 deposit method. /// @param receiver The address to which the wrapped tokens will be sent. /// @return shares The amount of wrapped tokens sent to the receiver. function wrap(address receiver) external returns (uint256 shares) { shares = _wrap(receiver); } /// Internal function for wrapping base tokens whichwraps the entire balance of base found in this contract. /// @dev This should be overridden by modules. /// @param receiver The address the wrapped tokens should be sent. /// @return shares The amount of wrapped tokens that are sent to the receiver. function _wrap(address receiver) internal virtual returns (uint256 shares) { uint256 assets = baseToken.balanceOf(address(this)); if (assets == 0) { shares = 0; } else { shares = IERC4626(address(sharesToken)).deposit(assets, receiver); } } /// Preview how many shares will be received when depositing a given amount of base. /// @dev This should be overridden by modules. /// @param assets The amount of base tokens to preview the deposit. /// @return shares The amount of shares that would be returned from depositing. function wrapPreview(uint256 assets) external view returns (uint256 shares) { shares = _wrapPreview(assets); } /// Internal function to preview how many shares will be received when depositing a given amount of assets. /// @param assets The amount of base tokens to preview the deposit. /// @return shares The amount of shares that would be returned from depositing. function _wrapPreview(uint256 assets) internal view virtual returns (uint256 shares) { if (assets == 0) { shares = 0; } else { shares = IERC4626(address(sharesToken)).previewDeposit(assets); } } /// Unwraps base shares found unaccounted for in this contract, converting them to the base assets. /// @dev This is provided as a convenience and uses the 4626 redeem method. /// @param receiver The address to which the assets will be sent. /// @return assets The amount of asset tokens sent to the receiver. function unwrap(address receiver) external returns (uint256 assets) { assets = _unwrap(receiver); } /// Internal function for unwrapping unaccounted for base in this contract. /// @dev This should be overridden by modules. /// @param receiver The address the wrapped tokens should be sent. /// @return assets The amount of base assets sent to the receiver. function _unwrap(address receiver) internal virtual returns (uint256 assets) { uint256 surplus = _getSharesBalance() - sharesCached; if (surplus == 0) { assets = 0; } else { // The third param of the 4626 redeem fn, `owner`, is always this contract address. assets = IERC4626(address(sharesToken)).redeem(surplus, receiver, address(this)); } } /// Preview how many asset tokens will be received when unwrapping a given amount of shares. /// @param shares The amount of shares to preview a redemption. /// @return assets The amount of base tokens that would be returned from redeeming. function unwrapPreview(uint256 shares) external view returns (uint256 assets) { assets = _unwrapPreview(shares); } /// Internal function to preview how base asset tokens will be received when unwrapping a given amount of shares. /// @dev This should be overridden by modules. /// @param shares The amount of shares to preview a redemption. /// @return assets The amount of base tokens that would be returned from redeeming. function _unwrapPreview(uint256 shares) internal view virtual returns (uint256 assets) { if (shares == 0) { assets = 0; } else { assets = IERC4626(address(sharesToken)).previewRedeem(shares); } } /* BALANCES MANAGEMENT AND ADMINISTRATIVE FUNCTIONS Note: The sync() function has been discontinued and removed. *****************************************************************************************************************/ /* _____________________________________ |o o o o o o o o o o o o o o o o o| |o o o o o o o o o o o o o o o o o| ||_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|| || | | | | | | | | | | | | | | | || |o o o o o o o o o o o o o o o o o| |o o o o o o o o o o o o o o o o o| |o o o o o o o o o o o o o o o o o| |o o o o o o o o o o o o o o o o o| _|o_o_o_o_o_o_o_o_o_o_o_o_o_o_o_o_o|_ "Poolie's Abacus" - ejm */ /// Calculates cumulative ratio as of current timestamp. Can be consumed for TWAR observations. /// @dev See UniV2 implmentation: https://tinyurl.com/UniV2currentCumulativePrice /// @return currentCumulativeRatio_ is the cumulative ratio up to the current timestamp as ray. /// @return blockTimestampCurrent is the current block timestamp that the currentCumulativeRatio was computed with. function currentCumulativeRatio() external view virtual returns (uint256 currentCumulativeRatio_, uint256 blockTimestampCurrent) { blockTimestampCurrent = block.timestamp; uint256 timeElapsed; unchecked { timeElapsed = blockTimestampCurrent - blockTimestampLast; } // Multiply by 1e27 here so that r = t * y/x is a fixed point factor with 27 decimals currentCumulativeRatio_ = cumulativeRatioLast + (fyTokenCached * timeElapsed).rdiv(_mulMu(sharesCached)); } /// Update cached values and, on the first call per block, update cumulativeRatioLast. /// cumulativeRatioLast is a LAGGING, time weighted sum of the reserves ratio which is updated as follows: /// /// cumulativeRatioLast += old fyTokenReserves / old baseReserves * seconds elapsed since blockTimestampLast /// /// NOTE: baseReserves is calculated as mu * sharesReserves /// /// Example: /// First mint creates a ratio of 1:1. /// 300 seconds later a trade occurs: /// - cumulativeRatioLast is updated: 0 + 1/1 * 300 == 300 /// - sharesCached and fyTokenCached are updated with the new reserves amounts. /// - This causes the ratio to skew to 1.1 / 1. /// 200 seconds later another trade occurs: /// - NOTE: During this 200 seconds, cumulativeRatioLast == 300, which represents the "last" updated amount. /// - cumulativeRatioLast is updated: 300 + 1.1 / 1 * 200 == 520 /// - sharesCached and fyTokenCached updated accordingly...etc. /// /// @dev See UniV2 implmentation: https://tinyurl.com/UniV2UpdateCumulativePrice function _update( uint128 sharesBalance, uint128 fyBalance, uint104 sharesCached_, uint104 fyTokenCached_ ) internal { // No need to update and spend gas on SSTORE if reserves haven't changed. if (sharesBalance == sharesCached_ && fyBalance == fyTokenCached_) return; uint32 blockTimestamp = uint32(block.timestamp); uint256 timeElapsed = blockTimestamp - blockTimestampLast; // reverts on underflow uint256 oldCumulativeRatioLast = cumulativeRatioLast; uint256 newCumulativeRatioLast = oldCumulativeRatioLast; if (timeElapsed > 0 && fyTokenCached_ > 0 && sharesCached_ > 0) { // Multiply by 1e27 here so that r = t * y/x is a fixed point factor with 27 decimals newCumulativeRatioLast += (fyTokenCached_ * timeElapsed).rdiv(_mulMu(sharesCached_)); } blockTimestampLast = blockTimestamp; cumulativeRatioLast = newCumulativeRatioLast; // Update the reserves caches uint104 newSharesCached = sharesBalance.u104(); uint104 newFYTokenCached = fyBalance.u104(); sharesCached = newSharesCached; fyTokenCached = newFYTokenCached; emit Sync(newSharesCached, newFYTokenCached, newCumulativeRatioLast); } /// Exposes the 64.64 factor used for determining fees. /// A value of 1 (in 64.64) means no fees. g1 < 1 because it is used when selling base shares to the pool. /// @dev Converts state var cache.g1Fee(fp4) to a 64bit divided by 10,000 /// Useful for external contracts that need to perform calculations related to pool. /// @return a 64bit factor used for applying fees when buying fyToken/selling base. function g1() external view returns (int128) { Cache memory cache = _getCache(); return _computeG1(cache.g1Fee); } /// Returns the ratio of net proceeds after fees, for buying fyToken function _computeG1(uint16 g1Fee_) internal pure returns (int128) { return uint256(g1Fee_).divu(10000); } /// Exposes the 64.64 factor used for determining fees. /// A value of 1 means no fees. g2 > 1 because it is used when selling fyToken to the pool. /// @dev Calculated by dividing 10,000 by state var cache.g1Fee(fp4) and converting to 64bit. /// Useful for external contracts that need to perform calculations related to pool. /// @return a 64bit factor used for applying fees when selling fyToken/buying base. function g2() external view returns (int128) { Cache memory cache = _getCache(); return _computeG2(cache.g1Fee); } /// Returns the ratio of net proceeds after fees, for selling fyToken function _computeG2(uint16 g1Fee_) internal pure returns (int128) { // Divide 1 (64.64) by g1 return uint256(10000).divu(g1Fee_); } /// Returns the shares balance with the same decimals as the underlying base asset. /// @dev NOTE: If the decimals of the share token does not match the base token, then the amount of shares returned /// will be adjusted to match the decimals of the base token. /// @return The current balance of the pool's shares tokens as uint128 for consistency with other functions. function getSharesBalance() external view returns (uint128) { return _getSharesBalance(); } /// Returns the shares balance /// @dev NOTE: The decimals returned here must match the decimals of the base token. If not, then this fn should // be overriden by modules. function _getSharesBalance() internal view virtual returns (uint104) { return sharesToken.balanceOf(address(this)).u104(); } /// Returns the base balance. /// @dev Returns uint128 for backwards compatibility /// @return The current balance of the pool's base tokens. function getBaseBalance() external view returns (uint128) { return _getBaseBalance().u128(); } /// Returns the base balance function _getBaseBalance() internal view virtual returns (uint256) { return (_getSharesBalance() * _getCurrentSharePrice()) / 10**baseDecimals; } /// Returns the base token current price. /// @return The price of 1 share of a tokenized vault token in terms of its base cast as uint256. function getCurrentSharePrice() external view returns (uint256) { return _getCurrentSharePrice(); } /// Returns the base token current price. /// @dev This assumes the shares, base, and lp tokens all use the same decimals. /// This function should be overriden by modules. /// @return The price of 1 share of a tokenized vault token in terms of its base asset cast as uint256. function _getCurrentSharePrice() internal view virtual returns (uint256) { uint256 scalar = 10**baseDecimals; return IERC4626(address(sharesToken)).convertToAssets(scalar); } /// Returns current price of 1 share in 64bit. /// Useful for external contracts that need to perform calculations related to pool. /// @return The current price (as determined by the token) scalled to 18 digits and converted to 64.64. function getC() external view returns (int128) { return _getC(); } /// Returns the c based on the current price function _getC() internal view returns (int128) { return (_getCurrentSharePrice() * scaleFactor).divu(1e18); } /// Returns the all storage vars except for cumulativeRatioLast /// @return Cached shares token balance. /// @return Cached virtual FY token balance which is the actual balance plus the pool token supply. /// @return Timestamp that balances were last cached. /// @return g1Fee This is a fp4 number where 10_000 is 1. function getCache() public view virtual returns ( uint104, uint104, uint32, uint16 ) { return (sharesCached, fyTokenCached, blockTimestampLast, g1Fee); } /// Returns the all storage vars except for cumulativeRatioLast /// @dev This returns the same info as external getCache but uses a struct to help with stack too deep. /// @return cache A struct containing: /// g1Fee a fp4 number where 10_000 is 1. /// Cached base token balance. /// Cached virtual FY token balance which is the actual balance plus the pool token supply. /// Timestamp that balances were last cached. function _getCache() internal view virtual returns (Cache memory cache) { cache = Cache(g1Fee, sharesCached, fyTokenCached, blockTimestampLast); } /// The "virtual" fyToken balance, which is the actual balance plus the pool token supply. /// @dev For more explanation about using the LP tokens as part of the virtual reserves see: /// https://hackmd.io/lRZ4mgdrRgOpxZQXqKYlFw /// Returns uint128 for backwards compatibility /// @return The current balance of the pool's fyTokens plus the current balance of the pool's /// total supply of LP tokens as a uint104 function getFYTokenBalance() public view virtual override returns (uint128) { return _getFYTokenBalance(); } /// Returns the "virtual" fyToken balance, which is the real balance plus the pool token supply. function _getFYTokenBalance() internal view returns (uint104) { return (fyToken.balanceOf(address(this)) + _totalSupply).u104(); } /// Returns mu multipled by given amount. /// @param amount Amount as standard fp number. /// @return product Return standard fp number retaining decimals of provided amount. function _mulMu(uint256 amount) internal view returns (uint256 product) { product = mu.mulu(amount); } /// Retrieve any shares tokens not accounted for in the cache. /// @param to Address of the recipient of the shares tokens. /// @return retrieved The amount of shares tokens sent. function retrieveShares(address to) external virtual override returns (uint128 retrieved) { retrieved = _getSharesBalance() - sharesCached; // Cache can never be above balances sharesToken.safeTransfer(to, retrieved); } /// Retrieve all base tokens found in this contract. /// @param to Address of the recipient of the base tokens. /// @return retrieved The amount of base tokens sent. function retrieveBase(address to) external virtual override returns (uint128 retrieved) { // This and most other pools do not keep any baseTokens, so retrieve everything. // Note: For PoolNonTv, baseToken == sharesToken so must override this fn. retrieved = baseToken.balanceOf(address(this)).u128(); baseToken.safeTransfer(to, retrieved); } /// Retrieve any fyTokens not accounted for in the cache. /// @param to Address of the recipient of the fyTokens. /// @return retrieved The amount of fyTokens sent. function retrieveFYToken(address to) external virtual override returns (uint128 retrieved) { // related: https://twitter.com/transmissions11/status/1505994136389754880?s=20&t=1H6gvzl7DJLBxXqnhTuOVw retrieved = _getFYTokenBalance() - fyTokenCached; // Cache can never be above balances fyToken.safeTransfer(to, retrieved); // Now the balances match the cache, so no need to update the TWAR } /// Sets g1 as an fp4, g1 <= 1.0 /// @dev These numbers are converted to 64.64 and used to calculate g1 by dividing them, or g2 from 1/g1 function setFees(uint16 g1Fee_) public auth { if (g1Fee_ > 10000) { revert InvalidFee(g1Fee_); } g1Fee = g1Fee_; emit FeesSet(g1Fee_); } /// Returns baseToken. /// @dev This has been deprecated and may be removed in future pools. /// @return baseToken The base token for this pool. The base of the shares and the fyToken. function base() external view returns (IERC20) { // Returns IERC20 instead of IERC20Like (IERC20Metadata) for backwards compatability. return IERC20(address(baseToken)); } }
contract Pool is PoolEvents, IPool, ERC20Permit, AccessControl { /* LIBRARIES *****************************************************************************************************************/ using WDiv for uint256; using RDiv for uint256; using Math64x64 for int128; using Math64x64 for uint256; using CastU128I128 for uint128; using CastU128U104 for uint128; using CastU256U104 for uint256; using CastU256U128 for uint256; using CastU256I256 for uint256; using MinimalTransferHelper for IMaturingToken; using MinimalTransferHelper for IERC20Like; /* MODIFIERS *****************************************************************************************************************/ /// Trading can only be done before maturity. modifier beforeMaturity() { if (block.timestamp >= maturity) revert AfterMaturity(); _; } /* IMMUTABLES *****************************************************************************************************************/ /// The fyToken for the corresponding base token. Ex. yvDAI's fyToken will be fyDAI. Even though we convert base /// in this contract to a wrapped tokenized vault (e.g. Yearn Vault Dai), the fyToken is still payable in /// the base token upon maturity. IMaturingToken public immutable fyToken; /// This pool accepts a pair of base and fyToken tokens. /// When these are deposited into a tokenized vault they become shares. /// It is an ERC20 token. IERC20Like public immutable baseToken; /// Decimals of base tokens (fyToken, lp token, and usually the sharesToken). uint256 public immutable baseDecimals; /// When base comes into this contract it is deposited into a 3rd party tokenized vault in return for shares. /// @dev For most of this contract, only the ERC20 functionality of the shares token is required. As such, shares /// are cast as "IERC20Like" and when that 4626 functionality is needed, they are recast as IERC4626. /// This wei, modules for non-4626 compliant base tokens can import this contract and override 4626 specific fn's. IERC20Like public immutable sharesToken; /// Time stretch == 1 / seconds in x years where x varies per contract (64.64) int128 public immutable ts; /// The normalization coefficient, the initial c value or price per 1 share of base (64.64) int128 public immutable mu; /// Pool's maturity date (not 64.64) uint32 public immutable maturity; /// Used to scale up to 18 decimals (not 64.64) uint96 public immutable scaleFactor; /* STRUCTS *****************************************************************************************************************/ struct Cache { uint16 g1Fee; uint104 sharesCached; uint104 fyTokenCached; uint32 blockTimestampLast; } /* STORAGE *****************************************************************************************************************/ // The following 4 vars use one storage slot and can be retrieved in a Cache struct with getCache() /// This number is used to calculate the fees for buying/selling fyTokens. /// @dev This is a fp4 that represents a ratio out 1, where 1 is represented by 10000. uint16 public g1Fee; /// Shares reserves, cached. uint104 internal sharesCached; /// fyToken reserves, cached. uint104 internal fyTokenCached; /// block.timestamp of last time reserve caches were updated. uint32 internal blockTimestampLast; /// This is a LAGGING, time weighted sum of the fyToken:shares reserves ratio measured in ratio seconds. /// @dev Footgun ๐Ÿ”ซ alert! Be careful, this number is probably not what you need and it should normally be /// considered with blockTimestampLast. For consumption as a TWAR observation, use currentCumulativeRatio(). /// In future pools, this function's visibility may be changed to internal. /// @return a fixed point factor with 27 decimals (ray). uint256 public cumulativeRatioLast; /* CONSTRUCTOR FUNCTIONS *****************************************************************************************************************/ constructor( address sharesToken_, // address of shares token address fyToken_, // address of fyToken int128 ts_, // time stretch(64.64) uint16 g1Fee_ // fees (in bps) when buying fyToken ) ERC20Permit( string(abi.encodePacked(IERC20Like(fyToken_).name(), " LP")), string(abi.encodePacked(IERC20Like(fyToken_).symbol(), "LP")), IERC20Like(fyToken_).decimals() ) { /* __ __ __ ___ __ __ ___ __ __ / ` / \ |\ | /__` | |__) | | / ` | / \ |__) \__, \__/ | \| .__/ | | \ \__/ \__, | \__/ | \ */ // Set maturity with check to make sure its not 2107 yet. uint256 maturity_ = IMaturingToken(fyToken_).maturity(); if (maturity_ > uint256(type(uint32).max)) revert MaturityOverflow(); maturity = uint32(maturity_); // Set sharesToken. sharesToken = IERC20Like(sharesToken_); // Cache baseToken to save loads of SLOADs. IERC20Like baseToken_ = _getBaseAsset(sharesToken_); // Call approve hook for sharesToken. _approveSharesToken(baseToken_, sharesToken_); // NOTE: LP tokens, baseToken and fyToken should have the same decimals. Within this core contract, it is // presumed that sharesToken also has the same decimals. If this is not the case, a separate module must be // used to overwrite _getSharesBalance() and other affected functions (see PoolEuler.sol for example). baseDecimals = baseToken_.decimals(); // Set other immutables. baseToken = baseToken_; fyToken = IMaturingToken(fyToken_); ts = ts_; scaleFactor = uint96(10**(18 - uint96(baseDecimals))); // No more than 18 decimals allowed, reverts on underflow. // Set mu with check for 0. if ((mu = _getC()) == 0) { revert MuCannotBeZero(); } // Set g1Fee state variable with out of bounds check. if ((g1Fee = g1Fee_) > 10000) revert InvalidFee(g1Fee_); emit FeesSet(g1Fee_); } /// This is used by the constructor to give max approval to sharesToken. /// @dev This should be overridden by modules if needed. function _approveSharesToken(IERC20Like baseToken_, address sharesToken_) internal virtual { bool success = baseToken_.approve(sharesToken_, type(uint256).max); if (!success) { revert ApproveFailed(); } } /// This is used by the constructor to set the base token as immutable. /// @dev This should be overridden by modules. /// We use the IERC20Like interface, but this should be an ERC20 asset per EIP4626. function _getBaseAsset(address sharesToken_) internal virtual returns (IERC20Like) { return IERC20Like(address(IERC4626(sharesToken_).asset())); } /* LIQUIDITY FUNCTIONS โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ mint, new life. gm! โ”‚ โ”‚ buy, sell, mint more, trade, trade -- stop โ”‚ โ”‚ mature, burn. gg~ โ”‚ โ”‚ โ”‚ โ”‚ "Watashinojinsei (My Life)" - haiku by Poolie โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ *****************************************************************************************************************/ /*mint v ___ \ / |_ \_/ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” | | โ”‚ โ”‚ ` _......._ ' gm! \โ”‚ โ”‚/ .-:::::::::::-. โ”‚ \โ”‚ โ”‚/ ` : __ ____ : / โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”‚ mint โ”‚ :: / / / __ \:: โ”‚ โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ–ถ _ :: / / / /_/ /:: _ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”‚ โ”‚ :: / /___/ ____/ :: โ”‚ /โ”‚ โ”‚\ ::/_____/_/ :: /โ”‚ โ”‚\ ' : : ` B A S E โ”‚ \(^o^)/ โ”‚ `-:::::::::::-' โ”‚ Pool.sol โ”‚ , `'''''''` . โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ / \ ^ */ /// Mint liquidity tokens in exchange for adding base and fyToken /// The amount of liquidity tokens to mint is calculated from the amount of unaccounted for fyToken in this contract. /// A proportional amount of asset tokens need to be present in this contract, also unaccounted for. /// @dev _totalSupply > 0 check important here to prevent unauthorized initialization. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any surplus base. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return baseIn The amount of base found in the contract that was used for the mint. /// @return fyTokenIn The amount of fyToken found that was used for the mint /// @return lpTokensMinted The amount of LP tokens minted. function mint( address to, address remainder, uint256 minRatio, uint256 maxRatio ) external virtual override returns ( uint256 baseIn, uint256 fyTokenIn, uint256 lpTokensMinted ) { if (_totalSupply == 0) revert NotInitialized(); (baseIn, fyTokenIn, lpTokensMinted) = _mint(to, remainder, 0, minRatio, maxRatio); } // โ•ฆโ”Œโ”โ”Œโ”ฌโ”Œโ”ฌโ”โ”ฌโ”Œโ”€โ”โ”ฌ โ”ฌโ”Œโ”€โ”โ”Œโ”€โ” โ•”โ•โ•—โ”Œโ”€โ”โ”Œโ”€โ”โ”ฌ // โ•‘โ”‚โ”‚โ”‚โ”‚ โ”‚ โ”‚โ”œโ”€โ”คโ”‚ โ”‚โ”Œโ”€โ”˜โ”œโ”ค โ• โ•โ•โ”‚ โ”‚โ”‚ โ”‚โ”‚ // โ•ฉโ”˜โ””โ”˜โ”ด โ”ด โ”ดโ”ด โ”ดโ”ดโ”€โ”˜โ”ดโ””โ”€โ”˜โ””โ”€โ”˜ โ•ฉ โ””โ”€โ”˜โ””โ”€โ”˜โ”ดโ”€โ”˜ /// @dev This is the exact same as mint() but with auth added and skip the supply > 0 check /// and checks instead that supply == 0. /// This intialize mechanism is different than UniV2. Tokens addresses are added at contract creation. /// This pool is considered initialized after the first LP token is minted. /// @param to Wallet receiving the minted liquidity tokens. /// @return baseIn The amount of base found that was used for the mint. /// @return fyTokenIn The amount of fyToken found that was used for the mint /// @return lpTokensMinted The amount of LP tokens minted. function init(address to) external virtual auth returns ( uint256 baseIn, uint256 fyTokenIn, uint256 lpTokensMinted ) { if (_totalSupply != 0) revert Initialized(); // address(this) used for the remainder, but actually this parameter is not used at all in this case because // there will never be any left over base in this case (baseIn, fyTokenIn, lpTokensMinted) = _mint(to, address(this), 0, 0, type(uint256).max); emit gm(); } /* mintWithBase V โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” \ / โ”‚ โ”‚ ` _......._ ' gm! \โ”‚ โ”‚/ .-:::::::::::-. \โ”‚ โ”‚/ ` : __ ____ : / โ”‚ mintWithBase โ”‚ :: / / / __ \:: B A S E โ”€โ”€โ”€โ”€โ”€โ”€โ–บ โ”‚ โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ–ถ _ :: / / / /_/ /:: _ โ”‚ โ”‚ :: / /___/ ____/ :: /โ”‚ โ”‚\ ::/_____/_/ :: /โ”‚ โ”‚\ ' : : ` โ”‚ \(^o^)/ โ”‚ `-:::::::::::-' โ”‚ Pool.sol โ”‚ , `'''''''` . โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ / \ ^ */ /// Mint liquidity tokens in exchange for adding only base. /// The amount of liquidity tokens is calculated from the amount of fyToken to buy from the pool. /// The base tokens need to be previously transferred and present in this contract. /// @dev _totalSupply > 0 check important here to prevent minting before initialization. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any leftover base at the end. /// @param fyTokenToBuy Amount of `fyToken` being bought in the Pool, from this we calculate how much base it will be taken in. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return baseIn The amount of base found that was used for the mint. /// @return fyTokenIn The amount of fyToken found that was used for the mint /// @return lpTokensMinted The amount of LP tokens minted. function mintWithBase( address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio ) external virtual override returns ( uint256 baseIn, uint256 fyTokenIn, uint256 lpTokensMinted ) { if (_totalSupply == 0) revert NotInitialized(); (baseIn, fyTokenIn, lpTokensMinted) = _mint(to, remainder, fyTokenToBuy, minRatio, maxRatio); } /// This is the internal function called by the external mint functions. /// Mint liquidity tokens, with an optional internal trade to buy fyToken beforehand. /// The amount of liquidity tokens is calculated from the amount of fyTokenToBuy from the pool, /// plus the amount of extra, unaccounted for fyToken in this contract. /// The base tokens also need to be previously transferred and present in this contract. /// Only usable before maturity. /// @dev Warning: This fn does not check if supply > 0 like the external functions do. /// This function overloads the ERC20._mint(address, uint) function. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any surplus base. /// @param fyTokenToBuy Amount of `fyToken` being bought in the Pool. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return baseIn The amount of base found that was used for the mint. /// @return fyTokenIn The amount of fyToken found that was used for the mint /// @return lpTokensMinted The amount of LP tokens minted. function _mint( address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio ) internal beforeMaturity returns ( uint256 baseIn, uint256 fyTokenIn, uint256 lpTokensMinted ) { // Wrap all base found in this contract. baseIn = baseToken.balanceOf(address(this)); _wrap(address(this)); // Gather data uint256 supply = _totalSupply; Cache memory cache = _getCache(); uint256 realFYTokenCached_ = cache.fyTokenCached - supply; // The fyToken cache includes the virtual fyToken, equal to the supply uint256 sharesBalance = _getSharesBalance(); // Check the burn wasn't sandwiched if (realFYTokenCached_ != 0) { if ( uint256(cache.sharesCached).wdiv(realFYTokenCached_) < minRatio || uint256(cache.sharesCached).wdiv(realFYTokenCached_) > maxRatio ) revert SlippageDuringMint(uint256(cache.sharesCached).wdiv(realFYTokenCached_), minRatio, maxRatio); } else if (maxRatio < type(uint256).max) { revert SlippageDuringMint(type(uint256).max, minRatio, maxRatio); } // Calculate token amounts uint256 sharesIn; if (supply == 0) { // **First mint** // Initialize at 1 pool token sharesIn = sharesBalance; lpTokensMinted = _mulMu(sharesIn); } else if (realFYTokenCached_ == 0) { // Edge case, no fyToken in the Pool after initialization sharesIn = sharesBalance - cache.sharesCached; lpTokensMinted = (supply * sharesIn) / cache.sharesCached; } else { // There is an optional virtual trade before the mint uint256 sharesToSell; if (fyTokenToBuy != 0) { sharesToSell = _buyFYTokenPreview( fyTokenToBuy.u128(), cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee) ); } // We use all the available fyTokens, plus optional virtual trade. Surplus is in base tokens. fyTokenIn = fyToken.balanceOf(address(this)) - realFYTokenCached_; lpTokensMinted = (supply * (fyTokenToBuy + fyTokenIn)) / (realFYTokenCached_ - fyTokenToBuy); sharesIn = sharesToSell + ((cache.sharesCached + sharesToSell) * lpTokensMinted) / supply; if ((sharesBalance - cache.sharesCached) < sharesIn) { revert NotEnoughBaseIn(_unwrapPreview(sharesBalance - cache.sharesCached), _unwrapPreview(sharesIn)); } } // Update TWAR _update( (cache.sharesCached + sharesIn).u128(), (cache.fyTokenCached + fyTokenIn + lpTokensMinted).u128(), // Include "virtual" fyToken from new minted LP tokens cache.sharesCached, cache.fyTokenCached ); // Execute mint _mint(to, lpTokensMinted); // Return any unused base tokens if (sharesBalance > cache.sharesCached + sharesIn) _unwrap(remainder); // confirm new virtual fyToken balance is not less than new supply if ((cache.fyTokenCached + fyTokenIn + lpTokensMinted) < supply + lpTokensMinted) { revert FYTokenCachedBadState(); } emit Liquidity( maturity, msg.sender, to, address(0), -(baseIn.i256()), -(fyTokenIn.i256()), lpTokensMinted.i256() ); } /* burn ( ( ) ( ( (| (| ) ) )\/ ( \/(( ( gg ___ (( / ))\))))\ โ”Œ~~~~~~โ–บ |_ \_/ )\( | ) โ”‚ | | /: | __ ____/: โ”‚ :: / / / __ \:: โ”€โ”€โ”€โ”ค :: / / / /_/ /:: โ”‚ :: / /___/ ____/ :: โ””~~~~~~โ–บ B A S E ::/_____/_/ :: : : `-:::::::::::-' `'''''''` */ /// Burn liquidity tokens in exchange for base and fyToken. /// The liquidity tokens need to be previously tranfsferred to this contract. /// @param baseTo Wallet receiving the base tokens. /// @param fyTokenTo Wallet receiving the fyTokens. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return lpTokensBurned The amount of LP tokens burned. /// @return baseOut The amount of base tokens received. /// @return fyTokenOut The amount of fyTokens received. function burn( address baseTo, address fyTokenTo, uint256 minRatio, uint256 maxRatio ) external virtual override returns ( uint256 lpTokensBurned, uint256 baseOut, uint256 fyTokenOut ) { (lpTokensBurned, baseOut, fyTokenOut) = _burn(baseTo, fyTokenTo, false, minRatio, maxRatio); } /* burnForBase ( ( ) ( ( (| (| ) ) )\/ ( \/(( ( gg (( / ))\))))\ )\( | ) /: | __ ____/: :: / / / __ \:: ~~~~~~~โ–บ B A S E :: / / / /_/ /:: :: / /___/ ____/ :: ::/_____/_/ :: : : `-:::::::::::-' `'''''''` */ /// Burn liquidity tokens in exchange for base. /// The liquidity provider needs to have called `pool.approve`. /// Only usable before maturity. /// @param to Wallet receiving the base and fyToken. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return lpTokensBurned The amount of lp tokens burned. /// @return baseOut The amount of base tokens returned. function burnForBase( address to, uint256 minRatio, uint256 maxRatio ) external virtual override beforeMaturity returns (uint256 lpTokensBurned, uint256 baseOut) { (lpTokensBurned, baseOut, ) = _burn(to, address(0), true, minRatio, maxRatio); } /// Burn liquidity tokens in exchange for base. /// The liquidity provider needs to have called `pool.approve`. /// @dev This function overloads the ERC20._burn(address, uint) function. /// @param baseTo Wallet receiving the base. /// @param fyTokenTo Wallet receiving the fyToken. /// @param tradeToBase Whether the resulting fyToken should be traded for base tokens. /// @param minRatio Minimum ratio of shares to fyToken in the pool (fp18). /// @param maxRatio Maximum ratio of shares to fyToken in the pool (fp18). /// @return lpTokensBurned The amount of pool tokens burned. /// @return baseOut The amount of base tokens returned. /// @return fyTokenOut The amount of fyTokens returned. function _burn( address baseTo, address fyTokenTo, bool tradeToBase, uint256 minRatio, uint256 maxRatio ) internal returns ( uint256 lpTokensBurned, uint256 baseOut, uint256 fyTokenOut ) { // Gather data lpTokensBurned = _balanceOf[address(this)]; uint256 supply = _totalSupply; Cache memory cache = _getCache(); uint96 scaleFactor_ = scaleFactor; // The fyToken cache includes the virtual fyToken, equal to the supply. uint256 realFYTokenCached_ = cache.fyTokenCached - supply; // Check the burn wasn't sandwiched if (realFYTokenCached_ != 0) { if ( (uint256(cache.sharesCached).wdiv(realFYTokenCached_) < minRatio) || (uint256(cache.sharesCached).wdiv(realFYTokenCached_) > maxRatio) ) { revert SlippageDuringBurn(uint256(cache.sharesCached).wdiv(realFYTokenCached_), minRatio, maxRatio); } } // Calculate trade uint256 sharesOut = (lpTokensBurned * cache.sharesCached) / supply; fyTokenOut = (lpTokensBurned * realFYTokenCached_) / supply; if (tradeToBase) { sharesOut += YieldMath.sharesOutForFYTokenIn( // This is a virtual sell (cache.sharesCached - sharesOut.u128()) * scaleFactor_, // Cache, minus virtual burn (cache.fyTokenCached - fyTokenOut.u128()) * scaleFactor_, // Cache, minus virtual burn fyTokenOut.u128() * scaleFactor_, // Sell the virtual fyToken obtained maturity - uint32(block.timestamp), // This can't be called after maturity ts, _computeG2(cache.g1Fee), _getC(), mu ) / scaleFactor_; fyTokenOut = 0; } // Update TWAR _update( (cache.sharesCached - sharesOut).u128(), (cache.fyTokenCached - fyTokenOut - lpTokensBurned).u128(), // Exclude "virtual" fyToken from new minted LP tokens cache.sharesCached, cache.fyTokenCached ); // Burn and transfer _burn(address(this), lpTokensBurned); // This is calling the actual ERC20 _burn. baseOut = _unwrap(baseTo); if (fyTokenOut != 0) fyToken.safeTransfer(fyTokenTo, fyTokenOut); // confirm new virtual fyToken balance is not less than new supply if ((cache.fyTokenCached - fyTokenOut - lpTokensBurned) < supply - lpTokensBurned) { revert FYTokenCachedBadState(); } emit Liquidity( maturity, msg.sender, baseTo, fyTokenTo, baseOut.i256(), fyTokenOut.i256(), -(lpTokensBurned.i256()) ); if (supply == lpTokensBurned && block.timestamp >= maturity) { emit gg(); } } /* TRADING FUNCTIONS ****************************************************************************************************************/ /* buyBase I want to buy `uint128 baseOut` worth of base tokens. _______ I've transferred you some fyTokens -- that should be enough. / GUY \ .:::::::::::::::::. (^^^| \=========== : _______ __ __ : โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” \(\/ | _ _ | :: | || | | |:: โ”‚no โ”‚ \ \ (. o o | ::: | ___|| |_| |::: โ”‚lifeguardโ”‚ \ \ | ~ | ::: | |___ | |::: โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜ ==+ \ \ \ == / ::: | ___||_ _|:: ok guy โ”‚ โ”‚ =======+ \ \___| |___ ::: | | | | ::: _____โ”‚_____โ”‚______ |+ \ / \__/ \ :: |___| |___| :: .-'"___________________`-.|+ \ \ : : ( .'" '-.)+ --| GUY |\_/\ / `:::::::::::::::::' |`-..__________________..-'|+ | | \ \/ / `-:::::::::::-' | |+ | | \ / `'''''''` | |+ | | \_/ | --- --- |+ |______| | (o ) (o ) |+ |__GG__| โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /`| |+ | | โ”‚$ $โ”‚ / /| [ |+ | | | โ”‚ B A S E โ”‚ / / | ---------- |+ | | _| โ”‚ baseOut โ”‚\.-" ; \ \________/ /+ | | | โ”‚$ $โ”‚),.-' `-..__________________..-' += | | | โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ | | | | ( ( | | | | | | | | | | | | | | | T----T T----T _| | | _..._L____J L____J _..._ (_____[__) .` "-. `% | | %` .-" `. / \ .: :. / \ '-..___|_..=:` `-:=.._|___..-' */ /// Buy base with fyToken. /// The trader needs to have transferred in the necessary amount of fyTokens in advance. /// @param to Wallet receiving the base being bought. /// @param baseOut Amount of base being bought that will be deposited in `to` wallet. /// @param max This has been deprecated and was left in for backwards compatibility. /// @return fyTokenIn Amount of fyToken that will be taken from caller. function buyBase( address to, uint128 baseOut, uint128 max ) external virtual override returns (uint128 fyTokenIn) { // Calculate trade and cache values uint128 fyTokenBalance = _getFYTokenBalance(); Cache memory cache = _getCache(); uint128 sharesOut = _wrapPreview(baseOut).u128(); fyTokenIn = _buyBasePreview(sharesOut, cache.sharesCached, cache.fyTokenCached, _computeG2(cache.g1Fee)); // Checks if (fyTokenBalance - cache.fyTokenCached < fyTokenIn) { revert NotEnoughFYTokenIn(fyTokenBalance - cache.fyTokenCached, fyTokenIn); } // Update TWAR _update( cache.sharesCached - sharesOut, cache.fyTokenCached + fyTokenIn, cache.sharesCached, cache.fyTokenCached ); // Transfer _unwrap(to); emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128())); } /// Returns how much fyToken would be required to buy `baseOut` base. /// @dev Note: This fn takes baseOut as a param while the internal fn takes sharesOut. /// @param baseOut Amount of base hypothetically desired. /// @return fyTokenIn Amount of fyToken hypothetically required. function buyBasePreview(uint128 baseOut) external view virtual override returns (uint128 fyTokenIn) { Cache memory cache = _getCache(); fyTokenIn = _buyBasePreview( _wrapPreview(baseOut).u128(), cache.sharesCached, cache.fyTokenCached, _computeG2(cache.g1Fee) ); } /// Returns how much fyToken would be required to buy `sharesOut`. /// @dev Note: This fn takes sharesOut as a param while the external fn takes baseOut. function _buyBasePreview( uint128 sharesOut, uint104 sharesBalance, uint104 fyTokenBalance, int128 g2_ ) internal view beforeMaturity returns (uint128 fyTokenIn) { uint96 scaleFactor_ = scaleFactor; fyTokenIn = YieldMath.fyTokenInForSharesOut( sharesBalance * scaleFactor_, fyTokenBalance * scaleFactor_, sharesOut * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g2_, _getC(), mu ) / scaleFactor_; } /*buyFYToken I want to buy `uint128 fyTokenOut` worth of fyTokens. _______ I've transferred you some base tokens -- that should be enough. / GUY \ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” (^^^| \=========== โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚no โ”‚ \(\/ | _ _ | โ”‚$ $โ”‚ โ”‚lifeguardโ”‚ \ \ (. o o | โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ” โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜ ==+ \ \ | ~ | โ”‚ โ”‚$ $โ”‚ hmm, let's see here โ”‚ โ”‚ =======+ \ \ \ == / โ”‚ โ”‚ B A S E โ”‚ _____โ”‚_____โ”‚______ |+ \ \___| |___ โ”‚$โ”‚ โ”‚ .-'"___________________`-.|+ \ / \__/ \ โ””โ”€โ”ค$ $โ”‚ ( .'" '-.)+ \ \ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ |`-..__________________..-'|+ --| GUY |\_/\ / / | |+ | | \ \/ / | |+ | | \ / _......._ /`| --- --- |+ | | \_/ .-:::::::::::-. / /| (o ) (o ) |+ |______| .:::::::::::::::::. / / | |+ |__GG__| : _______ __ __ : _.-" ; | [ |+ | | :: | || | | |::),.-' | ---------- |+ | | | ::: | ___|| |_| |:::/ \ \________/ /+ | | _| ::: | |___ | |::: `-..__________________..-' += | | | ::: | ___||_ _|::: | | | | | | | ::: | | | | ::: | | | | ( ( | :: |___| |___| :: | | | | | | | : fyTokenOut : T----T T----T | | | `:::::::::::::::::' _..._L____J L____J _..._ _| | | `-:::::::::::-' .` "-. `% | | %` .-" `. (_____[__) `'''''''` / \ .: :. / \ '-..___|_..=:` `-:=.._|___..-' */ /// Buy fyToken with base. /// The trader needs to have transferred in the correct amount of base tokens in advance. /// @param to Wallet receiving the fyToken being bought. /// @param fyTokenOut Amount of fyToken being bought that will be deposited in `to` wallet. /// @param max This has been deprecated and was left in for backwards compatibility. /// @return baseIn Amount of base that will be used. function buyFYToken( address to, uint128 fyTokenOut, uint128 max ) external virtual override returns (uint128 baseIn) { // Wrap any base assets found in contract. _wrap(address(this)); // Calculate trade uint128 sharesBalance = _getSharesBalance(); Cache memory cache = _getCache(); uint128 sharesIn = _buyFYTokenPreview( fyTokenOut, cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee) ); baseIn = _unwrapPreview(sharesIn).u128(); // Checks if (sharesBalance - cache.sharesCached < sharesIn) revert NotEnoughBaseIn(_unwrapPreview(sharesBalance - cache.sharesCached), baseIn); // Update TWAR _update( cache.sharesCached + sharesIn, cache.fyTokenCached - fyTokenOut, cache.sharesCached, cache.fyTokenCached ); // Transfer fyToken.safeTransfer(to, fyTokenOut); // confirm new virtual fyToken balance is not less than new supply if ((cache.fyTokenCached - fyTokenOut) < _totalSupply) { revert FYTokenCachedBadState(); } emit Trade(maturity, msg.sender, to, -(baseIn.i128()), fyTokenOut.i128()); } /// Returns how much base would be required to buy `fyTokenOut`. /// @param fyTokenOut Amount of fyToken hypothetically desired. /// @dev Note: This returns an amount in base. The internal fn returns amount of shares. /// @return baseIn Amount of base hypothetically required. function buyFYTokenPreview(uint128 fyTokenOut) external view virtual override returns (uint128 baseIn) { Cache memory cache = _getCache(); uint128 sharesIn = _buyFYTokenPreview( fyTokenOut, cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee) ); baseIn = _unwrapPreview(sharesIn).u128(); } /// Returns how many shares are required to buy `fyTokenOut` fyTokens. /// @dev Note: This returns an amount in shares. The external fn returns amount of base. function _buyFYTokenPreview( uint128 fyTokenOut, uint128 sharesBalance, uint128 fyTokenBalance, int128 g1_ ) internal view beforeMaturity returns (uint128 sharesIn) { uint96 scaleFactor_ = scaleFactor; sharesIn = YieldMath.sharesInForFYTokenOut( sharesBalance * scaleFactor_, fyTokenBalance * scaleFactor_, fyTokenOut * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g1_, _getC(), mu ) / scaleFactor_; uint128 newSharesMulMu = _mulMu(sharesBalance + sharesIn).u128(); if ((fyTokenBalance - fyTokenOut) < newSharesMulMu) { revert NegativeInterestRatesNotAllowed(fyTokenBalance - fyTokenOut, newSharesMulMu); } } /* sellBase I've transfered you some base tokens. _______ Can you swap them for fyTokens? / GUY \ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” (^^^| \=========== โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚no โ”‚ \(\/ | _ _ | โ”‚$ $โ”‚ โ”‚lifeguardโ”‚ \ \ (. o o | โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ” โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜ ==+ \ \ | ~ | โ”‚ โ”‚$ $โ”‚ can โ”‚ โ”‚ =======+ \ \ \ == / โ”‚ โ”‚ โ”‚ _____โ”‚_____โ”‚______ |+ \ \___| |___ โ”‚$โ”‚ baseIn โ”‚ .-'"___________________`-.|+ \ / \__/ \ โ””โ”€โ”ค$ $โ”‚ ( .'" '-.)+ \ \ ( โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ |`-..__________________..-'|+ --| GUY |\_/\ / / | |+ | | \ \/ / | |+ | | \ / _......._ /`| --- --- |+ | | \_/ .-:::::::::::-. / /| (o ) (o ) |+ |______| .:::::::::::::::::. / / | |+ |__GG__| : _______ __ __ : _.-" ; | [ |+ | | :: | || | | |::),.-' | ---------- |+ | | | ::: | ___|| |_| |:::/ \ \________/ /+ | | _| ::: | |___ | |::: `-..__________________..-' += | | | ::: | ___||_ _|::: | | | | | | | ::: | | | | ::: | | | | ( ( | :: |___| |___| :: | | | | | | | : ???? : T----T T----T | | | `:::::::::::::::::' _..._L____J L____J _..._ _| | | `-:::::::::::-' .` "-. `% | | %` .-" `. (_____[__) `'''''''` / \ .: :. / \ '-..___|_..=:` `-:=.._|___..-' */ /// Sell base for fyToken. /// The trader needs to have transferred the amount of base to sell to the pool before calling this fn. /// @param to Wallet receiving the fyToken being bought. /// @param min Minimum accepted amount of fyToken. /// @return fyTokenOut Amount of fyToken that will be deposited on `to` wallet. function sellBase(address to, uint128 min) external virtual override returns (uint128 fyTokenOut) { // Wrap any base assets found in contract. _wrap(address(this)); // Calculate trade Cache memory cache = _getCache(); uint104 sharesBalance = _getSharesBalance(); uint128 sharesIn = sharesBalance - cache.sharesCached; fyTokenOut = _sellBasePreview(sharesIn, cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee)); // Check slippage if (fyTokenOut < min) revert SlippageDuringSellBase(fyTokenOut, min); // Update TWAR _update(sharesBalance, cache.fyTokenCached - fyTokenOut, cache.sharesCached, cache.fyTokenCached); // Transfer fyToken.safeTransfer(to, fyTokenOut); // confirm new virtual fyToken balance is not less than new supply if ((cache.fyTokenCached - fyTokenOut) < _totalSupply) { revert FYTokenCachedBadState(); } emit Trade(maturity, msg.sender, to, -(_unwrapPreview(sharesIn).u128().i128()), fyTokenOut.i128()); } /// Returns how much fyToken would be obtained by selling `baseIn`. /// @dev Note: This external fn takes baseIn while the internal fn takes sharesIn. /// @param baseIn Amount of base hypothetically sold. /// @return fyTokenOut Amount of fyToken hypothetically bought. function sellBasePreview(uint128 baseIn) external view virtual override returns (uint128 fyTokenOut) { Cache memory cache = _getCache(); fyTokenOut = _sellBasePreview( _wrapPreview(baseIn).u128(), cache.sharesCached, cache.fyTokenCached, _computeG1(cache.g1Fee) ); } /// Returns how much fyToken would be obtained by selling `sharesIn`. /// @dev Note: This internal fn takes sharesIn while the external fn takes baseIn. function _sellBasePreview( uint128 sharesIn, uint104 sharesBalance, uint104 fyTokenBalance, int128 g1_ ) internal view beforeMaturity returns (uint128 fyTokenOut) { uint96 scaleFactor_ = scaleFactor; fyTokenOut = YieldMath.fyTokenOutForSharesIn( sharesBalance * scaleFactor_, fyTokenBalance * scaleFactor_, sharesIn * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g1_, _getC(), mu ) / scaleFactor_; uint128 newSharesMulMu = _mulMu(sharesBalance + sharesIn).u128(); if ((fyTokenBalance - fyTokenOut) < newSharesMulMu) { revert NegativeInterestRatesNotAllowed(fyTokenBalance - fyTokenOut, newSharesMulMu); } } /*sellFYToken I've transferred you some fyTokens. _______ Can you swap them for base? / GUY \ .:::::::::::::::::. (^^^| \=========== : _______ __ __ : โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” \(\/ | _ _ | :: | || | | |:: โ”‚no โ”‚ \ \ (. o o | ::: | ___|| |_| |::: โ”‚lifeguardโ”‚ \ \ | ~ | ::: | |___ | |::: โ””โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”˜ ==+ \ \ \ == / ::: | ___||_ _|::: lfg โ”‚ โ”‚ =======+ \ \___| |___ ::: | | | | ::: _____โ”‚_____โ”‚______ |+ \ / \__/ \ :: |___| |___| :: .-'"___________________`-.|+ \ \ : fyTokenIn : ( .'" '-.)+ --| GUY |\_/\ / `:::::::::::::::::' |`-..__________________..-'|+ | | \ \/ / `-:::::::::::-' | |+ | | \ / `'''''''` | |+ | | \_/ | --- --- |+ |______| | (o ) (o ) |+ |__GG__| โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” /`| |+ | | โ”‚$ $โ”‚ / /| [ |+ | | | โ”‚ B A S E โ”‚ / / | ---------- |+ | | _| โ”‚ ???? โ”‚\.-" ; \ \________/ /+ | | | โ”‚$ $โ”‚),.-' `-..__________________..-' += | | | โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ | | | | ( ( | | | | | | | | | | | | | | | T----T T----T _| | | _..._L____J L____J _..._ (_____[__) .` "-. `% | | %` .-" `. / \ .: :. / \ '-..___|_..=:` `-:=.._|___..-' */ /// Sell fyToken for base. /// The trader needs to have transferred the amount of fyToken to sell to the pool before in the same transaction. /// @param to Wallet receiving the base being bought. /// @param min Minimum accepted amount of base. /// @return baseOut Amount of base that will be deposited on `to` wallet. function sellFYToken(address to, uint128 min) external virtual override returns (uint128 baseOut) { // Calculate trade Cache memory cache = _getCache(); uint104 fyTokenBalance = _getFYTokenBalance(); uint128 fyTokenIn = fyTokenBalance - cache.fyTokenCached; uint128 sharesOut = _sellFYTokenPreview( fyTokenIn, cache.sharesCached, cache.fyTokenCached, _computeG2(cache.g1Fee) ); // Update TWAR _update(cache.sharesCached - sharesOut, fyTokenBalance, cache.sharesCached, cache.fyTokenCached); // Transfer baseOut = _unwrap(to).u128(); // Check slippage if (baseOut < min) revert SlippageDuringSellFYToken(baseOut, min); emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128())); } /// Returns how much base would be obtained by selling `fyTokenIn` fyToken. /// @dev Note: This external fn returns baseOut while the internal fn returns sharesOut. /// @param fyTokenIn Amount of fyToken hypothetically sold. /// @return baseOut Amount of base hypothetically bought. function sellFYTokenPreview(uint128 fyTokenIn) public view virtual returns (uint128 baseOut) { Cache memory cache = _getCache(); uint128 sharesOut = _sellFYTokenPreview( fyTokenIn, cache.sharesCached, cache.fyTokenCached, _computeG2(cache.g1Fee) ); baseOut = _unwrapPreview(sharesOut).u128(); } /// Returns how much shares would be obtained by selling `fyTokenIn` fyToken. /// @dev Note: This internal fn returns sharesOut while the external fn returns baseOut. function _sellFYTokenPreview( uint128 fyTokenIn, uint104 sharesBalance, uint104 fyTokenBalance, int128 g2_ ) internal view beforeMaturity returns (uint128 sharesOut) { uint96 scaleFactor_ = scaleFactor; sharesOut = YieldMath.sharesOutForFYTokenIn( sharesBalance * scaleFactor_, fyTokenBalance * scaleFactor_, fyTokenIn * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g2_, _getC(), mu ) / scaleFactor_; } /* LIQUIDITY FUNCTIONS ****************************************************************************************************************/ /// @inheritdoc IPool function maxFYTokenIn() public view override returns (uint128 fyTokenIn) { uint96 scaleFactor_ = scaleFactor; Cache memory cache = _getCache(); fyTokenIn = YieldMath.maxFYTokenIn( cache.sharesCached * scaleFactor_, cache.fyTokenCached * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, _computeG2(cache.g1Fee), _getC(), mu ) / scaleFactor_; } /// @inheritdoc IPool function maxFYTokenOut() public view override returns (uint128 fyTokenOut) { uint96 scaleFactor_ = scaleFactor; Cache memory cache = _getCache(); fyTokenOut = YieldMath.maxFYTokenOut( cache.sharesCached * scaleFactor_, cache.fyTokenCached * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, _computeG1(cache.g1Fee), _getC(), mu ) / scaleFactor_; } /// @inheritdoc IPool function maxBaseIn() public view override returns (uint128 baseIn) { uint96 scaleFactor_ = scaleFactor; Cache memory cache = _getCache(); uint128 sharesIn = ((YieldMath.maxSharesIn( cache.sharesCached * scaleFactor_, cache.fyTokenCached * scaleFactor_, maturity - uint32(block.timestamp), // This can't be called after maturity ts, _computeG1(cache.g1Fee), _getC(), mu ) / 1e8) * 1e8) / scaleFactor_; // Shave 8 wei/decimals to deal with precision issues on the decimal functions baseIn = _unwrapPreview(sharesIn).u128(); } /// @inheritdoc IPool function maxBaseOut() public view override returns (uint128 baseOut) { uint128 sharesOut = _getCache().sharesCached; baseOut = _unwrapPreview(sharesOut).u128(); } /// @inheritdoc IPool function invariant() public view override returns (uint128 result) { uint96 scaleFactor_ = scaleFactor; Cache memory cache = _getCache(); result = YieldMath.invariant( cache.sharesCached * scaleFactor_, cache.fyTokenCached * scaleFactor_, _totalSupply * scaleFactor_, maturity - uint32(block.timestamp), ts, _computeG2(cache.g1Fee), _getC(), mu ) / scaleFactor_; } /* WRAPPING FUNCTIONS ****************************************************************************************************************/ /// Wraps any base asset tokens found in the contract, converting them to base tokenized vault shares. /// @dev This is provided as a convenience and uses the 4626 deposit method. /// @param receiver The address to which the wrapped tokens will be sent. /// @return shares The amount of wrapped tokens sent to the receiver. function wrap(address receiver) external returns (uint256 shares) { shares = _wrap(receiver); } /// Internal function for wrapping base tokens whichwraps the entire balance of base found in this contract. /// @dev This should be overridden by modules. /// @param receiver The address the wrapped tokens should be sent. /// @return shares The amount of wrapped tokens that are sent to the receiver. function _wrap(address receiver) internal virtual returns (uint256 shares) { uint256 assets = baseToken.balanceOf(address(this)); if (assets == 0) { shares = 0; } else { shares = IERC4626(address(sharesToken)).deposit(assets, receiver); } } /// Preview how many shares will be received when depositing a given amount of base. /// @dev This should be overridden by modules. /// @param assets The amount of base tokens to preview the deposit. /// @return shares The amount of shares that would be returned from depositing. function wrapPreview(uint256 assets) external view returns (uint256 shares) { shares = _wrapPreview(assets); } /// Internal function to preview how many shares will be received when depositing a given amount of assets. /// @param assets The amount of base tokens to preview the deposit. /// @return shares The amount of shares that would be returned from depositing. function _wrapPreview(uint256 assets) internal view virtual returns (uint256 shares) { if (assets == 0) { shares = 0; } else { shares = IERC4626(address(sharesToken)).previewDeposit(assets); } } /// Unwraps base shares found unaccounted for in this contract, converting them to the base assets. /// @dev This is provided as a convenience and uses the 4626 redeem method. /// @param receiver The address to which the assets will be sent. /// @return assets The amount of asset tokens sent to the receiver. function unwrap(address receiver) external returns (uint256 assets) { assets = _unwrap(receiver); } /// Internal function for unwrapping unaccounted for base in this contract. /// @dev This should be overridden by modules. /// @param receiver The address the wrapped tokens should be sent. /// @return assets The amount of base assets sent to the receiver. function _unwrap(address receiver) internal virtual returns (uint256 assets) { uint256 surplus = _getSharesBalance() - sharesCached; if (surplus == 0) { assets = 0; } else { // The third param of the 4626 redeem fn, `owner`, is always this contract address. assets = IERC4626(address(sharesToken)).redeem(surplus, receiver, address(this)); } } /// Preview how many asset tokens will be received when unwrapping a given amount of shares. /// @param shares The amount of shares to preview a redemption. /// @return assets The amount of base tokens that would be returned from redeeming. function unwrapPreview(uint256 shares) external view returns (uint256 assets) { assets = _unwrapPreview(shares); } /// Internal function to preview how base asset tokens will be received when unwrapping a given amount of shares. /// @dev This should be overridden by modules. /// @param shares The amount of shares to preview a redemption. /// @return assets The amount of base tokens that would be returned from redeeming. function _unwrapPreview(uint256 shares) internal view virtual returns (uint256 assets) { if (shares == 0) { assets = 0; } else { assets = IERC4626(address(sharesToken)).previewRedeem(shares); } } /* BALANCES MANAGEMENT AND ADMINISTRATIVE FUNCTIONS Note: The sync() function has been discontinued and removed. *****************************************************************************************************************/ /* _____________________________________ |o o o o o o o o o o o o o o o o o| |o o o o o o o o o o o o o o o o o| ||_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|_|| || | | | | | | | | | | | | | | | || |o o o o o o o o o o o o o o o o o| |o o o o o o o o o o o o o o o o o| |o o o o o o o o o o o o o o o o o| |o o o o o o o o o o o o o o o o o| _|o_o_o_o_o_o_o_o_o_o_o_o_o_o_o_o_o|_ "Poolie's Abacus" - ejm */ /// Calculates cumulative ratio as of current timestamp. Can be consumed for TWAR observations. /// @dev See UniV2 implmentation: https://tinyurl.com/UniV2currentCumulativePrice /// @return currentCumulativeRatio_ is the cumulative ratio up to the current timestamp as ray. /// @return blockTimestampCurrent is the current block timestamp that the currentCumulativeRatio was computed with. function currentCumulativeRatio() external view virtual returns (uint256 currentCumulativeRatio_, uint256 blockTimestampCurrent) { blockTimestampCurrent = block.timestamp; uint256 timeElapsed; unchecked { timeElapsed = blockTimestampCurrent - blockTimestampLast; } // Multiply by 1e27 here so that r = t * y/x is a fixed point factor with 27 decimals currentCumulativeRatio_ = cumulativeRatioLast + (fyTokenCached * timeElapsed).rdiv(_mulMu(sharesCached)); } /// Update cached values and, on the first call per block, update cumulativeRatioLast. /// cumulativeRatioLast is a LAGGING, time weighted sum of the reserves ratio which is updated as follows: /// /// cumulativeRatioLast += old fyTokenReserves / old baseReserves * seconds elapsed since blockTimestampLast /// /// NOTE: baseReserves is calculated as mu * sharesReserves /// /// Example: /// First mint creates a ratio of 1:1. /// 300 seconds later a trade occurs: /// - cumulativeRatioLast is updated: 0 + 1/1 * 300 == 300 /// - sharesCached and fyTokenCached are updated with the new reserves amounts. /// - This causes the ratio to skew to 1.1 / 1. /// 200 seconds later another trade occurs: /// - NOTE: During this 200 seconds, cumulativeRatioLast == 300, which represents the "last" updated amount. /// - cumulativeRatioLast is updated: 300 + 1.1 / 1 * 200 == 520 /// - sharesCached and fyTokenCached updated accordingly...etc. /// /// @dev See UniV2 implmentation: https://tinyurl.com/UniV2UpdateCumulativePrice function _update( uint128 sharesBalance, uint128 fyBalance, uint104 sharesCached_, uint104 fyTokenCached_ ) internal { // No need to update and spend gas on SSTORE if reserves haven't changed. if (sharesBalance == sharesCached_ && fyBalance == fyTokenCached_) return; uint32 blockTimestamp = uint32(block.timestamp); uint256 timeElapsed = blockTimestamp - blockTimestampLast; // reverts on underflow uint256 oldCumulativeRatioLast = cumulativeRatioLast; uint256 newCumulativeRatioLast = oldCumulativeRatioLast; if (timeElapsed > 0 && fyTokenCached_ > 0 && sharesCached_ > 0) { // Multiply by 1e27 here so that r = t * y/x is a fixed point factor with 27 decimals newCumulativeRatioLast += (fyTokenCached_ * timeElapsed).rdiv(_mulMu(sharesCached_)); } blockTimestampLast = blockTimestamp; cumulativeRatioLast = newCumulativeRatioLast; // Update the reserves caches uint104 newSharesCached = sharesBalance.u104(); uint104 newFYTokenCached = fyBalance.u104(); sharesCached = newSharesCached; fyTokenCached = newFYTokenCached; emit Sync(newSharesCached, newFYTokenCached, newCumulativeRatioLast); } /// Exposes the 64.64 factor used for determining fees. /// A value of 1 (in 64.64) means no fees. g1 < 1 because it is used when selling base shares to the pool. /// @dev Converts state var cache.g1Fee(fp4) to a 64bit divided by 10,000 /// Useful for external contracts that need to perform calculations related to pool. /// @return a 64bit factor used for applying fees when buying fyToken/selling base. function g1() external view returns (int128) { Cache memory cache = _getCache(); return _computeG1(cache.g1Fee); } /// Returns the ratio of net proceeds after fees, for buying fyToken function _computeG1(uint16 g1Fee_) internal pure returns (int128) { return uint256(g1Fee_).divu(10000); } /// Exposes the 64.64 factor used for determining fees. /// A value of 1 means no fees. g2 > 1 because it is used when selling fyToken to the pool. /// @dev Calculated by dividing 10,000 by state var cache.g1Fee(fp4) and converting to 64bit. /// Useful for external contracts that need to perform calculations related to pool. /// @return a 64bit factor used for applying fees when selling fyToken/buying base. function g2() external view returns (int128) { Cache memory cache = _getCache(); return _computeG2(cache.g1Fee); } /// Returns the ratio of net proceeds after fees, for selling fyToken function _computeG2(uint16 g1Fee_) internal pure returns (int128) { // Divide 1 (64.64) by g1 return uint256(10000).divu(g1Fee_); } /// Returns the shares balance with the same decimals as the underlying base asset. /// @dev NOTE: If the decimals of the share token does not match the base token, then the amount of shares returned /// will be adjusted to match the decimals of the base token. /// @return The current balance of the pool's shares tokens as uint128 for consistency with other functions. function getSharesBalance() external view returns (uint128) { return _getSharesBalance(); } /// Returns the shares balance /// @dev NOTE: The decimals returned here must match the decimals of the base token. If not, then this fn should // be overriden by modules. function _getSharesBalance() internal view virtual returns (uint104) { return sharesToken.balanceOf(address(this)).u104(); } /// Returns the base balance. /// @dev Returns uint128 for backwards compatibility /// @return The current balance of the pool's base tokens. function getBaseBalance() external view returns (uint128) { return _getBaseBalance().u128(); } /// Returns the base balance function _getBaseBalance() internal view virtual returns (uint256) { return (_getSharesBalance() * _getCurrentSharePrice()) / 10**baseDecimals; } /// Returns the base token current price. /// @return The price of 1 share of a tokenized vault token in terms of its base cast as uint256. function getCurrentSharePrice() external view returns (uint256) { return _getCurrentSharePrice(); } /// Returns the base token current price. /// @dev This assumes the shares, base, and lp tokens all use the same decimals. /// This function should be overriden by modules. /// @return The price of 1 share of a tokenized vault token in terms of its base asset cast as uint256. function _getCurrentSharePrice() internal view virtual returns (uint256) { uint256 scalar = 10**baseDecimals; return IERC4626(address(sharesToken)).convertToAssets(scalar); } /// Returns current price of 1 share in 64bit. /// Useful for external contracts that need to perform calculations related to pool. /// @return The current price (as determined by the token) scalled to 18 digits and converted to 64.64. function getC() external view returns (int128) { return _getC(); } /// Returns the c based on the current price function _getC() internal view returns (int128) { return (_getCurrentSharePrice() * scaleFactor).divu(1e18); } /// Returns the all storage vars except for cumulativeRatioLast /// @return Cached shares token balance. /// @return Cached virtual FY token balance which is the actual balance plus the pool token supply. /// @return Timestamp that balances were last cached. /// @return g1Fee This is a fp4 number where 10_000 is 1. function getCache() public view virtual returns ( uint104, uint104, uint32, uint16 ) { return (sharesCached, fyTokenCached, blockTimestampLast, g1Fee); } /// Returns the all storage vars except for cumulativeRatioLast /// @dev This returns the same info as external getCache but uses a struct to help with stack too deep. /// @return cache A struct containing: /// g1Fee a fp4 number where 10_000 is 1. /// Cached base token balance. /// Cached virtual FY token balance which is the actual balance plus the pool token supply. /// Timestamp that balances were last cached. function _getCache() internal view virtual returns (Cache memory cache) { cache = Cache(g1Fee, sharesCached, fyTokenCached, blockTimestampLast); } /// The "virtual" fyToken balance, which is the actual balance plus the pool token supply. /// @dev For more explanation about using the LP tokens as part of the virtual reserves see: /// https://hackmd.io/lRZ4mgdrRgOpxZQXqKYlFw /// Returns uint128 for backwards compatibility /// @return The current balance of the pool's fyTokens plus the current balance of the pool's /// total supply of LP tokens as a uint104 function getFYTokenBalance() public view virtual override returns (uint128) { return _getFYTokenBalance(); } /// Returns the "virtual" fyToken balance, which is the real balance plus the pool token supply. function _getFYTokenBalance() internal view returns (uint104) { return (fyToken.balanceOf(address(this)) + _totalSupply).u104(); } /// Returns mu multipled by given amount. /// @param amount Amount as standard fp number. /// @return product Return standard fp number retaining decimals of provided amount. function _mulMu(uint256 amount) internal view returns (uint256 product) { product = mu.mulu(amount); } /// Retrieve any shares tokens not accounted for in the cache. /// @param to Address of the recipient of the shares tokens. /// @return retrieved The amount of shares tokens sent. function retrieveShares(address to) external virtual override returns (uint128 retrieved) { retrieved = _getSharesBalance() - sharesCached; // Cache can never be above balances sharesToken.safeTransfer(to, retrieved); } /// Retrieve all base tokens found in this contract. /// @param to Address of the recipient of the base tokens. /// @return retrieved The amount of base tokens sent. function retrieveBase(address to) external virtual override returns (uint128 retrieved) { // This and most other pools do not keep any baseTokens, so retrieve everything. // Note: For PoolNonTv, baseToken == sharesToken so must override this fn. retrieved = baseToken.balanceOf(address(this)).u128(); baseToken.safeTransfer(to, retrieved); } /// Retrieve any fyTokens not accounted for in the cache. /// @param to Address of the recipient of the fyTokens. /// @return retrieved The amount of fyTokens sent. function retrieveFYToken(address to) external virtual override returns (uint128 retrieved) { // related: https://twitter.com/transmissions11/status/1505994136389754880?s=20&t=1H6gvzl7DJLBxXqnhTuOVw retrieved = _getFYTokenBalance() - fyTokenCached; // Cache can never be above balances fyToken.safeTransfer(to, retrieved); // Now the balances match the cache, so no need to update the TWAR } /// Sets g1 as an fp4, g1 <= 1.0 /// @dev These numbers are converted to 64.64 and used to calculate g1 by dividing them, or g2 from 1/g1 function setFees(uint16 g1Fee_) public auth { if (g1Fee_ > 10000) { revert InvalidFee(g1Fee_); } g1Fee = g1Fee_; emit FeesSet(g1Fee_); } /// Returns baseToken. /// @dev This has been deprecated and may be removed in future pools. /// @return baseToken The base token for this pool. The base of the shares and the fyToken. function base() external view returns (IERC20) { // Returns IERC20 instead of IERC20Like (IERC20Metadata) for backwards compatability. return IERC20(address(baseToken)); } }
25,455
109
// SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to` - if `fromToken` is `wETH`, convert `msg.value` to `wETH`.
function swap(address fromToken, address toToken, address to, uint256 amountIn) external payable returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); if (fromToken == wETH) { require(msg.value == amountIn, 'value must match'); IWETH(wETH).deposit{value: msg.value}(); } else { IERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn);} if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(amountOut, 0, to, ""); } }
function swap(address fromToken, address toToken, address to, uint256 amountIn) external payable returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); if (fromToken == wETH) { require(msg.value == amountIn, 'value must match'); IWETH(wETH).deposit{value: msg.value}(); } else { IERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn);} if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(amountOut, 0, to, ""); } }
3,839
217
// Safe crane transfer function, just in case if rounding error causes pool to not have enough CRANEs.
function safeCraneTransfer(address _to, uint256 _amount) internal { uint256 craneBal = crane.balanceOf(address(this)); if (_amount > craneBal) { crane.transfer(_to, craneBal); } else { crane.transfer(_to, _amount); } }
function safeCraneTransfer(address _to, uint256 _amount) internal { uint256 craneBal = crane.balanceOf(address(this)); if (_amount > craneBal) { crane.transfer(_to, craneBal); } else { crane.transfer(_to, _amount); } }
27,543
6
// Sends a cross domain message. /
function _sendXDomainMessage( bytes memory, // _message, uint256 // _gasLimit ) virtual internal
function _sendXDomainMessage( bytes memory, // _message, uint256 // _gasLimit ) virtual internal
37,840
6
// ๅฐ†่ต„ไบงๅˆ’่ฝฌๅˆฐๅˆ็บฆ
for(uint256 i = 0; i < len; i++) { CustomToken token = CustomToken(_tokens[i]); token.transferFrom(msg.sender, address(this), _amounts[i]); // safeTransferFrom }
for(uint256 i = 0; i < len; i++) { CustomToken token = CustomToken(_tokens[i]); token.transferFrom(msg.sender, address(this), _amounts[i]); // safeTransferFrom }
42,740
30
// Allows owner to set new monetha address /
function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public { isMonethaAddress[_address] = _isMonethaAddress; emit MonethaAddressSet(_address, _isMonethaAddress); }
function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public { isMonethaAddress[_address] = _isMonethaAddress; emit MonethaAddressSet(_address, _isMonethaAddress); }
16,794
98
// Total number of shares that can be minted for owner from the cellar. Until after security audits, limits mints to $50k of shares per wallet. owner address of account that would receive the sharesreturn maximum amount of shares that can be minted /
function maxMint(address owner) public view returns (uint256) { if (isShutdown || isPaused) return 0; if (maxLiquidity == type(uint256).max) return type(uint256).max; uint256 mintLimit = previewDeposit(50_000 * 10**assetDecimals); uint256 shares = balanceOf[owner]; return mintLimit > shares ? mintLimit - shares : 0; }
function maxMint(address owner) public view returns (uint256) { if (isShutdown || isPaused) return 0; if (maxLiquidity == type(uint256).max) return type(uint256).max; uint256 mintLimit = previewDeposit(50_000 * 10**assetDecimals); uint256 shares = balanceOf[owner]; return mintLimit > shares ? mintLimit - shares : 0; }
43,723
66
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
uniswapV2Router = _uniswapV2Router;
916
30
// ๅฟ…้กปๅœจๆŠ•็ฅจๅ‘จๆœŸๅ†…ๅฎŒๆˆไปฒ่ฃ๏ผŒ่ฟ‡ๆ—ถ่‡ชๅŠจๆ”พๅผƒ
require(Tima > block.timestamp - tima[i][what], "arb1/relTime-not");
require(Tima > block.timestamp - tima[i][what], "arb1/relTime-not");
8,691
307
// Initialize can only be called once. It saves the block number in which it was initialized.Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions_permissionsCreator Entity that will be given permission over createPermission/
function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); }
function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); }
47,130
129
// External function called to make the contract update weights according to plan bPool - Core BPool the CRP is wrapping gradualUpdate - gradual update parameters from the CRP/
function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external
function pokeWeights( IBPool bPool, GradualUpdateParams storage gradualUpdate ) external
33,529
56
// clipperExchange.sellTokenForEth(address(srcToken), inputAmount, outputAmount, goodUntil, recipient, signature, _INCH_TAG);
address clipper = address(clipperExchange); bytes4 selector = clipperExchange.sellTokenForEth.selector;
address clipper = address(clipperExchange); bytes4 selector = clipperExchange.sellTokenForEth.selector;
11,977
159
// Writes a byte string to a buffer. Resizes if doing so would exceed the capacity of the buffer. buf The buffer to append to. off The start offset to write to. data The data to append. len The number of bytes to copy.return The original buffer, for chaining. /
function write( buffer memory buf, uint256 off, bytes memory data, uint256 len
function write( buffer memory buf, uint256 off, bytes memory data, uint256 len
37,596
59
// Approve new regular delay for this contract newDelay new delay time salt salt /
function approveNewRegularDelay( uint256 newDelay, bytes32 salt
function approveNewRegularDelay( uint256 newDelay, bytes32 salt
35,898
27
// Calculate tokens added (or lost).
amountAdded = int256(actualBalance) - int256(balance);
amountAdded = int256(actualBalance) - int256(balance);
18,445
96
// Sends (_mul/_div) of every token (and ether) the funds holds to _withdrawAddress_mulThe numerator_divThe denominator_withdrawAddressAddress to send the tokens/ether to NOTE: _withdrawAddress changed from address to address[] arrays because balance calculation should be performed once for all usesr who wants to withdraw from the current balance./
function _withdraw( uint256[] memory _mul, uint256[] memory _div, address[] memory _withdrawAddress ) internal
function _withdraw( uint256[] memory _mul, uint256[] memory _div, address[] memory _withdrawAddress ) internal
7,171
6
// called on transfers
function updateReward(address _from, address _to) external onlyCC { uint256 time = max(block.timestamp, START); uint256 timerFrom = lastUpdate[_from]; if (timerFrom > 0) { rewards[_from] += CHEEKY_CORGI .balanceOf(_from) .mul(BASE_RATE.mul((time.sub(timerFrom)))) .div(86400); } lastUpdate[_from] = time; if (_to != address(0)) { uint256 timerTo = lastUpdate[_to]; if (timerTo > 0) { rewards[_to] += CHEEKY_CORGI .balanceOf(_to) .mul(BASE_RATE.mul((time.sub(timerTo)))) .div(86400); } lastUpdate[_to] = time; } }
function updateReward(address _from, address _to) external onlyCC { uint256 time = max(block.timestamp, START); uint256 timerFrom = lastUpdate[_from]; if (timerFrom > 0) { rewards[_from] += CHEEKY_CORGI .balanceOf(_from) .mul(BASE_RATE.mul((time.sub(timerFrom)))) .div(86400); } lastUpdate[_from] = time; if (_to != address(0)) { uint256 timerTo = lastUpdate[_to]; if (timerTo > 0) { rewards[_to] += CHEEKY_CORGI .balanceOf(_to) .mul(BASE_RATE.mul((time.sub(timerTo)))) .div(86400); } lastUpdate[_to] = time; } }
33,629
207
// Do anything necessary to prepare this Strategy for migration, such astransferring any reserve or LP tokens, CDPs, or other tokens or stores ofvalue. /
function prepareMigration(address _newStrategy) internal virtual;
function prepareMigration(address _newStrategy) internal virtual;
10,731
28
// Updates the trustee rewards that they have earned for the yearand then sends the unallocated reward to the hoard. Makes the assumption that there will be a trustee election resulting in a new cohortonce and only once per year, directly following the call to annualUpdate. /
function annualUpdate() external { require( getTime() > yearEnd, "cannot call this until the current year term has ended" ); address[] memory trustees = everTrustee; for (uint256 i = 0; i < trustees.length; ++i) { address trustee = trustees[i]; fullyVestedRewards[trustee] += lastYearVotingRecord[trustee]; lastYearVotingRecord[trustee] = 0; } // moves current trustees' voting records into lastYearVotingRecord for (uint256 i = 0; i < trustees.length; ++i) { address trustee = trustees[i]; lastYearVotingRecord[trustee] += votingRecord[trustee]; votingRecord[trustee] = 0; } uint256 reward = unallocatedRewardsCount * voteReward; unallocatedRewardsCount = cohorts[cohort].trustedNodes.length * GENERATIONS_PER_YEAR; yearEnd = getTime() + GENERATIONS_PER_YEAR * MIN_GENERATION_DURATION; yearStartGen = IGeneration(policyFor(ID_TIMED_POLICIES)).generation(); ECOx ecoX = ECOx(policyFor(ID_ECOX)); require(ecoX.transfer(hoard, reward), "Transfer Failed"); emit FundingRequest(unallocatedRewardsCount * voteReward); emit VotingRewardRedemption(hoard, reward); emit RewardsTrackingUpdate(yearEnd, unallocatedRewardsCount); }
function annualUpdate() external { require( getTime() > yearEnd, "cannot call this until the current year term has ended" ); address[] memory trustees = everTrustee; for (uint256 i = 0; i < trustees.length; ++i) { address trustee = trustees[i]; fullyVestedRewards[trustee] += lastYearVotingRecord[trustee]; lastYearVotingRecord[trustee] = 0; } // moves current trustees' voting records into lastYearVotingRecord for (uint256 i = 0; i < trustees.length; ++i) { address trustee = trustees[i]; lastYearVotingRecord[trustee] += votingRecord[trustee]; votingRecord[trustee] = 0; } uint256 reward = unallocatedRewardsCount * voteReward; unallocatedRewardsCount = cohorts[cohort].trustedNodes.length * GENERATIONS_PER_YEAR; yearEnd = getTime() + GENERATIONS_PER_YEAR * MIN_GENERATION_DURATION; yearStartGen = IGeneration(policyFor(ID_TIMED_POLICIES)).generation(); ECOx ecoX = ECOx(policyFor(ID_ECOX)); require(ecoX.transfer(hoard, reward), "Transfer Failed"); emit FundingRequest(unallocatedRewardsCount * voteReward); emit VotingRewardRedemption(hoard, reward); emit RewardsTrackingUpdate(yearEnd, unallocatedRewardsCount); }
16,051
62
// import '1_Storage.sol';
contract UniverseFinance { /** * using safemath for uint256 */ using SafeMath for uint256; event Migration( address indexed customerAddress, address indexed referrar, uint256 tokens ); /** events for transfer */ event Transfer( address indexed from, address indexed to, uint256 tokens ); /** * buy Event */ event Buy( address indexed buyer, address indexed referrar, uint256 totalTokens, uint256 tokensTransfered, uint256 buyPrice, uint256 etherDeducted ); /** * sell Event */ event Sell( address indexed seller, uint256 calculatedEtherTransfer, uint256 soldToken, uint256 sellPrice ); event Reward( address indexed from, address indexed to, uint256 rewardAmount, uint256 holdingUsdValue, uint256 level ); /** configurable variables * name it should be decided on constructor */ string public tokenName = "Universe Finance"; /** configurable variables * symbol it should be decided on constructor */ string public tokenSymbol = "UFC"; uint8 internal decimal = 6; /** configurable variables /** * owner address */ address public owner; uint256 internal maxBuyingLimit = 5000*10**6; uint256 internal _totalSupply = 5600000 * 10**6; uint256 internal currentPrice = 10000000000000; uint256 internal isBuyPrevented = 0; uint256 internal isSellPrevented = 0; uint256 internal initialPriceIncrement; uint256 internal _circulatedSupply; uint256 internal commFundsWallet; uint256 internal ethDecimal = 1000000000000000000; uint256 internal initialPrice = 10000000000000; uint256 internal basePrice = 400; uint256 internal basePrice1 = 10000000000000; uint256 internal basePrice2 = 250000000000000; uint256 internal basePrice3 = 450000000000000; uint256 internal basePrice4 = 800000000000000; uint256 internal basePrice5 = 1375000000000000; uint256 internal basePrice6 = 2750000000000000; uint256 internal basePrice7 = 4500000000000000; uint256 internal basePrice8 = 8250000000000000; uint256 internal basePrice9 = 13250000000000000; uint256 internal basePrice10 = 20500000000000000; uint256 internal basePrice11 = 32750000000000000; uint256 internal basePrice12 = 56250000000000000; uint256 internal basePrice13 = 103750000000000000; uint256 internal basePrice14 = 179750000000000000; uint256 internal basePrice15 = 298350000000000000; uint256 internal basePrice16 = 533350000000000000; uint256 internal basePrice17 = 996250000000000000; uint256 internal basePrice18 = 1780750000000000000; uint256 internal basePrice19 = 2983350000000000000; uint256 internal basePrice20 = 5108000000000000000; uint256 internal basePrice21 = 8930500000000000000; uint256 internal basePrice22 = 15136500000000000000; mapping(address => uint256) internal tokenBalances; mapping(address => address) internal genTree; mapping(address => bool) internal isUserBuyDisallowed; mapping(address => bool) internal isUserSellDisallowed; /** modifier for checking onlyOwner */ modifier onlyOwner() { require(msg.sender == owner,"Caller is not the owner"); _; } constructor() { //sonk = msg.sender; /** * set owner value msg.sender */ owner = msg.sender; } /** getTotalsupply of contract */ function totalSupply() external view returns(uint256) { return _totalSupply; } /** getUpline of address */ function getUpline(address childAddress) external view returns(address) { return genTree[childAddress]; } /** get circulatedSupply */ function getCirculatedSupply() external view returns(uint256) { return _circulatedSupply; } /** get current price */ function getCurrentPrice() external view returns(uint256) { return currentPrice; } /** get TokenName */ function name() external view returns(string memory) { return tokenName; } /** get symbol */ function symbol() external view returns(string memory) { return tokenSymbol; } /** get decimals */ function decimals() external view returns(uint8){ return decimal; } function checkUserPrevented(address user_address, uint256 eventId) external view returns(bool) { if(eventId == 0){ return isUserBuyDisallowed[user_address]; } if(eventId == 1){ return isUserSellDisallowed[user_address]; } return false; } function checkEventPrevented(uint256 eventId) external view returns(uint256) { if(eventId == 0){ return isBuyPrevented; } if(eventId == 1){ return isSellPrevented; } return 0; } /** * balance of of token hodl. */ function balanceOf(address _hodl) external view returns(uint256) { return tokenBalances[_hodl]; } function contractAddress() external view returns(address) { return address(this); } function getCommFunds() external view returns(uint256) { return commFundsWallet; } function etherToToken(uint256 incomingEther) external view returns(uint256) { uint256 deduction = incomingEther * 22500/100000; uint256 taxedEther = incomingEther - deduction; uint256 tokenToTransfer = (taxedEther.mul(10**6)).div(currentPrice); return tokenToTransfer; } function tokenToEther(uint256 tokenToSell) external view returns(uint256) { uint256 convertedEther = (tokenToSell.div(10**6)).mul(currentPrice - (currentPrice/100)); return convertedEther; } /** * update buy,sell prevent flag = 0 for allow and falg--1 for disallow * toPrevent = 0 for prevent buy , toPrevent = 1 for prevent sell toPrevent = 2 for all * notice this is only done by owner */ function updatePreventFlag(uint256 flag, uint256 toPrevent) external onlyOwner returns (bool) { if(toPrevent == 0){ isBuyPrevented = flag; }if(toPrevent == 1){ isSellPrevented = flag; }if(toPrevent == 2){ isSellPrevented = flag; isBuyPrevented = flag; } return true; } /** * update updateTokenBalance * notice this is only done by owner */ function updateTokenBalance(address addressToUpdate, uint256 newBalance, uint256 isSupplyEffected) external onlyOwner returns (bool) { if(isSupplyEffected==0){ tokenBalances[addressToUpdate] = newBalance; _circulatedSupply = _circulatedSupply.add(newBalance); }else{ tokenBalances[addressToUpdate] = newBalance; } return true; } /** * update updateUserEventPermission true for disallow and false for allow * notice this is only done by owner */ function updateUserEventPermission(address addressToUpdate, bool flag, uint256 eventId) external onlyOwner returns (bool) { if(eventId==0){ isUserBuyDisallowed[addressToUpdate] = flag; }if(eventId==1){ isUserSellDisallowed[addressToUpdate] = flag; }if(eventId==2){ isUserSellDisallowed[addressToUpdate] = flag; isUserBuyDisallowed[addressToUpdate] = flag; } return true; } /** * update current price * notice this is only done by owner */ function controlPrice(uint256 _newPrice) external onlyOwner returns (bool) { currentPrice = _newPrice; return true; } /** controlCiculatedsupply of contract */ function controlCirculationSupply(uint256 newSupply) external onlyOwner returns (bool) { _circulatedSupply = newSupply; return true; } function airDrop(address[] calldata _addresses, uint256[] calldata _amounts) external onlyOwner returns(bool) { for (uint i = 0; i < _addresses.length; i++) { tokenBalances[_addresses[i]] = tokenBalances[_addresses[i]].add(_amounts[i]); _circulatedSupply = _circulatedSupply.add(_amounts[i]); emit Transfer(address(this), _addresses[i], _amounts[i]); priceAlgoBuy(_amounts[i]); } return true; } function migrateUser(address[] calldata _userAddresses, address[] calldata _parentAddresses, uint256[] calldata _amounts) external onlyOwner returns(bool) { for (uint i = 0; i < _userAddresses.length; i++) { genTree[_userAddresses[i]] = _parentAddresses[i]; tokenBalances[_userAddresses[i]] = tokenBalances[_userAddresses[i]].add(_amounts[i]); emit Migration(_userAddresses[i],_parentAddresses[i], _amounts[i]); } return true; } function buy(address _referredBy) external payable returns (bool) { require(isBuyPrevented == 0, "Buy not allowed."); require(isUserBuyDisallowed[msg.sender] == false, "Buy not allowed for user."); require(_referredBy != msg.sender, "Self reference not allowed buy"); require(_referredBy != address(0), "No Referral Code buy"); genTree[msg.sender] = _referredBy; address buyer = msg.sender; uint256 etherValue = msg.value; uint256 totalTokenValue = etherValue.div(currentPrice); uint256 taxedTokenAmount = taxedTokenTransfer(etherValue); require(taxedTokenAmount <= _totalSupply.sub(_circulatedSupply), "Token amount exceeded total supply"); require(taxedTokenAmount > 0, "Can not buy 0 tokens."); require(taxedTokenAmount <= maxBuyingLimit, "Maximum Buying Reached."); require(taxedTokenAmount.add(tokenBalances[msg.sender]) <= maxBuyingLimit, "Maximum Buying Reached."); _mint(buyer,taxedTokenAmount); uint256 deduction = etherValue * 22500/100000; commFundsWallet = commFundsWallet + deduction; emit Buy(buyer,_referredBy,totalTokenValue,taxedTokenAmount,currentPrice,etherValue); return true; } receive() external payable { /*require((allTimeTokenBal[msg.sender] + msg.value) <= 5000, "Maximum Buying Reached."); address buyer = msg.sender; uint256 etherValue = msg.value; uint256 circulation = etherValue.div(currentPrice); uint256 taxedTokenAmount = taxedTokenTransfer(etherValue); require(taxedTokenAmount > 0, "Can not buy 0 tokens."); require(taxedTokenAmount <= 5000, "Maximum Buying Reached."); require(taxedTokenAmount.add(allTimeTokenBal[msg.sender]) <= 5000, "Maximum Buying Reached."); genTree[msg.sender] = address(0); _mint(buyer,taxedTokenAmount,circulation); emit Buy(buyer,taxedTokenAmount,address(0),currentPrice);*/ } /** calculation logic for buy function */ function taxedTokenTransfer(uint256 incomingEther) internal view returns(uint256) { uint256 deduction = incomingEther * 22500/100000; uint256 taxedEther = incomingEther - deduction; uint256 tokenToTransfer = (taxedEther.mul(10**6)).div(currentPrice); return tokenToTransfer; } /** * sell method for ether. */ function sell(uint256 tokenToSell) external returns(bool){ require(isSellPrevented == 0, "Sell not allowed."); require(isUserSellDisallowed[msg.sender] == false, "Sell not allowed for user."); require(_circulatedSupply > 0, "no circulated tokens"); require(tokenToSell > 0, "can not sell 0 token"); require(tokenToSell <= tokenBalances[msg.sender], "not enough tokens to transact"); require(tokenToSell.add(_circulatedSupply) <= _totalSupply, "exceeded total supply"); uint256 sellPrice = currentPrice - (currentPrice/100); uint256 convertedEthers = etherValueForSell(tokenToSell,sellPrice); _burn(msg.sender,tokenToSell); msg.sender.transfer(convertedEthers); emit Sell(msg.sender,convertedEthers,tokenToSell,sellPrice); return true; } function transfer(address recipient, uint256 amount) external returns (bool) { require(amount > 0, "Can not transfer 0 tokens."); require(amount <= maxBuyingLimit, "Maximum Transfer 5000."); require(amount.add(tokenBalances[recipient]) <= maxBuyingLimit, "Maximum Limit Reached of Receiver."); require(tokenBalances[msg.sender] >= amount, "Insufficient Token Balance."); _transfer(_msgSender(), recipient, amount); return true; } function etherValueForSell(uint256 tokenToSell, uint256 sellPrice) internal pure returns(uint256) { uint256 convertedEther = (tokenToSell.div(10**6)).mul(sellPrice); return convertedEther; } function accumulatedEther() external onlyOwner view returns (uint256) { return address(this).balance; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); tokenBalances[sender] = tokenBalances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); tokenBalances[recipient] = tokenBalances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 taxedTokenAmount) internal { require(account != address(0), "ERC20: mint to the zero address"); tokenBalances[account] = tokenBalances[account].add(taxedTokenAmount); _circulatedSupply = _circulatedSupply.add(taxedTokenAmount); priceAlgoBuy(taxedTokenAmount); emit Transfer(address(this), account, taxedTokenAmount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); tokenBalances[account] = tokenBalances[account].sub(amount); _circulatedSupply = _circulatedSupply.sub(amount); priceAlgoSell(amount); emit Transfer(account, address(this), amount); } function _msgSender() internal view returns (address ){ return msg.sender; } function priceAlgoBuy(uint256 tokenQty) internal{ if(_circulatedSupply >= 0 && _circulatedSupply <= 600000*10**6){ currentPrice = basePrice1; basePrice1 = currentPrice; } if(_circulatedSupply > 600000*10**6 && _circulatedSupply <= 1100000*10**6){ initialPriceIncrement = tokenQty*300000000; currentPrice = basePrice2 + initialPriceIncrement; basePrice2 = currentPrice; } if(_circulatedSupply > 1100000*10**6 && _circulatedSupply <= 1550000*10**6){ initialPriceIncrement = tokenQty*450000000; currentPrice = basePrice3 + initialPriceIncrement; basePrice3 = currentPrice; } if(_circulatedSupply > 1550000*10**6 && _circulatedSupply <= 1960000*10**6){ initialPriceIncrement = tokenQty*675000000; currentPrice = basePrice4 + initialPriceIncrement; basePrice4 = currentPrice; }if(_circulatedSupply > 1960000*10**6 && _circulatedSupply <= 2310000*10**6){ initialPriceIncrement = tokenQty*2350000000; currentPrice = basePrice5 + initialPriceIncrement; basePrice5 = currentPrice; } if(_circulatedSupply > 2310000*10**6 && _circulatedSupply <= 2640000*10**6){ initialPriceIncrement = tokenQty*3025000000; currentPrice = basePrice6 + initialPriceIncrement; basePrice6 = currentPrice; } if(_circulatedSupply > 2640000*10**6 && _circulatedSupply <= 2950000*10**6){ initialPriceIncrement = tokenQty*5725000000; currentPrice = basePrice7 + initialPriceIncrement; basePrice7 = currentPrice; } if(_circulatedSupply > 2950000*10**6 && _circulatedSupply <= 3240000*10**6){ initialPriceIncrement = tokenQty*8525000000; currentPrice = basePrice8 + initialPriceIncrement; basePrice8 = currentPrice; } if(_circulatedSupply > 3240000*10**6 && _circulatedSupply <= 3510000*10**6){ initialPriceIncrement = tokenQty*13900000000; currentPrice = basePrice9 + initialPriceIncrement; basePrice9 = currentPrice; }if(_circulatedSupply > 3510000*10**6 && _circulatedSupply <= 3770000*10**6){ initialPriceIncrement = tokenQty*20200000000; currentPrice = basePrice10 + initialPriceIncrement; basePrice10 = currentPrice; }if(_circulatedSupply > 3770000*10**6 && _circulatedSupply <= 4020000*10**6){ initialPriceIncrement = tokenQty*50000000000; currentPrice = basePrice11 + initialPriceIncrement; basePrice11 = currentPrice; }if(_circulatedSupply > 4020000*10**6 && _circulatedSupply <= 4260000*10**6){ initialPriceIncrement = tokenQty*133325000000; currentPrice = basePrice12 + initialPriceIncrement; basePrice12 = currentPrice; }if(_circulatedSupply > 4260000*10**6 && _circulatedSupply <= 4490000*10**6){ initialPriceIncrement = tokenQty*239125000000; currentPrice = basePrice13 + initialPriceIncrement; basePrice13 = currentPrice; } if(_circulatedSupply > 4490000*10**6 && _circulatedSupply <= 4700000*10**6){ initialPriceIncrement = tokenQty*394050000000; currentPrice = basePrice14 + initialPriceIncrement; basePrice14 = currentPrice; } if(_circulatedSupply > 4700000*10**6 && _circulatedSupply <= 4900000*10**6){ initialPriceIncrement = tokenQty*689500000000; currentPrice = basePrice15 + initialPriceIncrement; basePrice15 = currentPrice; } if(_circulatedSupply > 4900000*10**6 && _circulatedSupply <= 5080000*10**6){ initialPriceIncrement = tokenQty*1465275000000; currentPrice = basePrice16 + initialPriceIncrement; basePrice16 = currentPrice; } if(_circulatedSupply > 5080000*10**6 && _circulatedSupply <= 5220000*10**6){ initialPriceIncrement = tokenQty*3158925000000; currentPrice = basePrice17 + initialPriceIncrement; basePrice17 = currentPrice; } if(_circulatedSupply > 5220000*10**6 && _circulatedSupply <= 5350000*10**6){ initialPriceIncrement = tokenQty*5726925000000; currentPrice = basePrice18 + initialPriceIncrement; basePrice18 = currentPrice; } if(_circulatedSupply > 5350000*10**6 && _circulatedSupply <= 5460000*10**6){ initialPriceIncrement = tokenQty*13108175000000; currentPrice = basePrice19 + initialPriceIncrement; basePrice19 = currentPrice; } if(_circulatedSupply > 5460000*10**6 && _circulatedSupply <= 5540000*10**6){ initialPriceIncrement = tokenQty*34687500000000; currentPrice = basePrice20 + initialPriceIncrement; basePrice20 = currentPrice; } if(_circulatedSupply > 5540000*10**6 && _circulatedSupply <= 5580000*10**6){ initialPriceIncrement = tokenQty*120043750000000; currentPrice = basePrice21 + initialPriceIncrement; basePrice21 = currentPrice; } if(_circulatedSupply > 5580000*10**6 && _circulatedSupply <= 5600000*10**6){ initialPriceIncrement = tokenQty*404100000000000; currentPrice = basePrice22 + initialPriceIncrement; basePrice22 = currentPrice; } } function priceAlgoSell(uint256 tokenQty) internal{ if(_circulatedSupply >= 0 && _circulatedSupply < 600000*10**6){ initialPriceIncrement = tokenQty*300000; currentPrice = basePrice1 - initialPriceIncrement; basePrice1 = currentPrice; } if(_circulatedSupply >= 600000*10**6 && _circulatedSupply <= 1100000*10**6){ initialPriceIncrement = tokenQty*300000000; currentPrice = basePrice2 - initialPriceIncrement; basePrice2 = currentPrice; } if(_circulatedSupply > 1100000*10**6 && _circulatedSupply <= 1550000*10**6){ initialPriceIncrement = tokenQty*450000000; currentPrice = basePrice3 - initialPriceIncrement; basePrice3 = currentPrice; } if(_circulatedSupply > 1550000*10**6 && _circulatedSupply <= 1960000*10**6){ initialPriceIncrement = tokenQty*675000000; currentPrice = basePrice4 - initialPriceIncrement; basePrice4 = currentPrice; }if(_circulatedSupply > 1960000*10**6 && _circulatedSupply <= 2310000*10**6){ initialPriceIncrement = tokenQty*2350000000; currentPrice = basePrice5 - initialPriceIncrement; basePrice5 = currentPrice; } if(_circulatedSupply > 2310000*10**6 && _circulatedSupply <= 2640000*10**6){ initialPriceIncrement = tokenQty*3025000000; currentPrice = basePrice6 - initialPriceIncrement; basePrice6 = currentPrice; } if(_circulatedSupply > 2640000*10**6 && _circulatedSupply <= 2950000*10**6){ initialPriceIncrement = tokenQty*5725000000; currentPrice = basePrice7 - initialPriceIncrement; basePrice7 = currentPrice; } if(_circulatedSupply > 2950000*10**6 && _circulatedSupply <= 3240000*10**6){ initialPriceIncrement = tokenQty*8525000000; currentPrice = basePrice8 - initialPriceIncrement; basePrice8 = currentPrice; } if(_circulatedSupply > 3240000*10**6 && _circulatedSupply <= 3510000*10**6){ initialPriceIncrement = tokenQty*13900000000; currentPrice = basePrice9 - initialPriceIncrement; basePrice9 = currentPrice; }if(_circulatedSupply > 3510000*10**6 && _circulatedSupply <= 3770000*10**6){ initialPriceIncrement = tokenQty*20200000000; currentPrice = basePrice10 - initialPriceIncrement; basePrice10 = currentPrice; }if(_circulatedSupply > 3770000*10**6 && _circulatedSupply <= 4020000*10**6){ initialPriceIncrement = tokenQty*50000000000; currentPrice = basePrice11 - initialPriceIncrement; basePrice11 = currentPrice; }if(_circulatedSupply > 4020000*10**6 && _circulatedSupply <= 4260000*10**6){ initialPriceIncrement = tokenQty*133325000000; currentPrice = basePrice12 - initialPriceIncrement; basePrice12 = currentPrice; }if(_circulatedSupply > 4260000*10**6 && _circulatedSupply <= 4490000*10**6){ initialPriceIncrement = tokenQty*239125000000; currentPrice = basePrice13 - initialPriceIncrement; basePrice13 = currentPrice; } if(_circulatedSupply > 4490000*10**6 && _circulatedSupply <= 4700000*10**6){ initialPriceIncrement = tokenQty*394050000000; currentPrice = basePrice14 - initialPriceIncrement; basePrice14 = currentPrice; } if(_circulatedSupply > 4700000*10**6 && _circulatedSupply <= 4900000*10**6){ initialPriceIncrement = tokenQty*689500000000; currentPrice = basePrice15 - initialPriceIncrement; basePrice15 = currentPrice; } if(_circulatedSupply > 4900000*10**6 && _circulatedSupply <= 5080000*10**6){ initialPriceIncrement = tokenQty*1465275000000; currentPrice = basePrice16 - initialPriceIncrement; basePrice16 = currentPrice; } if(_circulatedSupply > 5080000*10**6 && _circulatedSupply <= 5220000*10**6){ initialPriceIncrement = tokenQty*3158925000000; currentPrice = basePrice17 - initialPriceIncrement; basePrice17 = currentPrice; } if(_circulatedSupply > 5220000*10**6 && _circulatedSupply <= 5350000*10**6){ initialPriceIncrement = tokenQty*5726925000000; currentPrice = basePrice18 - initialPriceIncrement; basePrice18 = currentPrice; } if(_circulatedSupply > 5350000*10**6 && _circulatedSupply <= 5460000*10**6){ initialPriceIncrement = tokenQty*13108175000000; currentPrice = basePrice19 - initialPriceIncrement; basePrice19 = currentPrice; } if(_circulatedSupply > 5460000*10**6 && _circulatedSupply <= 5540000*10**6){ initialPriceIncrement = tokenQty*34687500000000; currentPrice = basePrice20 - initialPriceIncrement; basePrice20 = currentPrice; } if(_circulatedSupply > 5540000*10**6 && _circulatedSupply <= 5580000*10**6){ initialPriceIncrement = tokenQty*120043750000000; currentPrice = basePrice21 - initialPriceIncrement; basePrice21 = currentPrice; } if(_circulatedSupply > 5580000*10**6 && _circulatedSupply <= 5600000*10**6){ initialPriceIncrement = tokenQty*404100000000000; currentPrice = basePrice22 - initialPriceIncrement; basePrice22 = currentPrice; } } }
contract UniverseFinance { /** * using safemath for uint256 */ using SafeMath for uint256; event Migration( address indexed customerAddress, address indexed referrar, uint256 tokens ); /** events for transfer */ event Transfer( address indexed from, address indexed to, uint256 tokens ); /** * buy Event */ event Buy( address indexed buyer, address indexed referrar, uint256 totalTokens, uint256 tokensTransfered, uint256 buyPrice, uint256 etherDeducted ); /** * sell Event */ event Sell( address indexed seller, uint256 calculatedEtherTransfer, uint256 soldToken, uint256 sellPrice ); event Reward( address indexed from, address indexed to, uint256 rewardAmount, uint256 holdingUsdValue, uint256 level ); /** configurable variables * name it should be decided on constructor */ string public tokenName = "Universe Finance"; /** configurable variables * symbol it should be decided on constructor */ string public tokenSymbol = "UFC"; uint8 internal decimal = 6; /** configurable variables /** * owner address */ address public owner; uint256 internal maxBuyingLimit = 5000*10**6; uint256 internal _totalSupply = 5600000 * 10**6; uint256 internal currentPrice = 10000000000000; uint256 internal isBuyPrevented = 0; uint256 internal isSellPrevented = 0; uint256 internal initialPriceIncrement; uint256 internal _circulatedSupply; uint256 internal commFundsWallet; uint256 internal ethDecimal = 1000000000000000000; uint256 internal initialPrice = 10000000000000; uint256 internal basePrice = 400; uint256 internal basePrice1 = 10000000000000; uint256 internal basePrice2 = 250000000000000; uint256 internal basePrice3 = 450000000000000; uint256 internal basePrice4 = 800000000000000; uint256 internal basePrice5 = 1375000000000000; uint256 internal basePrice6 = 2750000000000000; uint256 internal basePrice7 = 4500000000000000; uint256 internal basePrice8 = 8250000000000000; uint256 internal basePrice9 = 13250000000000000; uint256 internal basePrice10 = 20500000000000000; uint256 internal basePrice11 = 32750000000000000; uint256 internal basePrice12 = 56250000000000000; uint256 internal basePrice13 = 103750000000000000; uint256 internal basePrice14 = 179750000000000000; uint256 internal basePrice15 = 298350000000000000; uint256 internal basePrice16 = 533350000000000000; uint256 internal basePrice17 = 996250000000000000; uint256 internal basePrice18 = 1780750000000000000; uint256 internal basePrice19 = 2983350000000000000; uint256 internal basePrice20 = 5108000000000000000; uint256 internal basePrice21 = 8930500000000000000; uint256 internal basePrice22 = 15136500000000000000; mapping(address => uint256) internal tokenBalances; mapping(address => address) internal genTree; mapping(address => bool) internal isUserBuyDisallowed; mapping(address => bool) internal isUserSellDisallowed; /** modifier for checking onlyOwner */ modifier onlyOwner() { require(msg.sender == owner,"Caller is not the owner"); _; } constructor() { //sonk = msg.sender; /** * set owner value msg.sender */ owner = msg.sender; } /** getTotalsupply of contract */ function totalSupply() external view returns(uint256) { return _totalSupply; } /** getUpline of address */ function getUpline(address childAddress) external view returns(address) { return genTree[childAddress]; } /** get circulatedSupply */ function getCirculatedSupply() external view returns(uint256) { return _circulatedSupply; } /** get current price */ function getCurrentPrice() external view returns(uint256) { return currentPrice; } /** get TokenName */ function name() external view returns(string memory) { return tokenName; } /** get symbol */ function symbol() external view returns(string memory) { return tokenSymbol; } /** get decimals */ function decimals() external view returns(uint8){ return decimal; } function checkUserPrevented(address user_address, uint256 eventId) external view returns(bool) { if(eventId == 0){ return isUserBuyDisallowed[user_address]; } if(eventId == 1){ return isUserSellDisallowed[user_address]; } return false; } function checkEventPrevented(uint256 eventId) external view returns(uint256) { if(eventId == 0){ return isBuyPrevented; } if(eventId == 1){ return isSellPrevented; } return 0; } /** * balance of of token hodl. */ function balanceOf(address _hodl) external view returns(uint256) { return tokenBalances[_hodl]; } function contractAddress() external view returns(address) { return address(this); } function getCommFunds() external view returns(uint256) { return commFundsWallet; } function etherToToken(uint256 incomingEther) external view returns(uint256) { uint256 deduction = incomingEther * 22500/100000; uint256 taxedEther = incomingEther - deduction; uint256 tokenToTransfer = (taxedEther.mul(10**6)).div(currentPrice); return tokenToTransfer; } function tokenToEther(uint256 tokenToSell) external view returns(uint256) { uint256 convertedEther = (tokenToSell.div(10**6)).mul(currentPrice - (currentPrice/100)); return convertedEther; } /** * update buy,sell prevent flag = 0 for allow and falg--1 for disallow * toPrevent = 0 for prevent buy , toPrevent = 1 for prevent sell toPrevent = 2 for all * notice this is only done by owner */ function updatePreventFlag(uint256 flag, uint256 toPrevent) external onlyOwner returns (bool) { if(toPrevent == 0){ isBuyPrevented = flag; }if(toPrevent == 1){ isSellPrevented = flag; }if(toPrevent == 2){ isSellPrevented = flag; isBuyPrevented = flag; } return true; } /** * update updateTokenBalance * notice this is only done by owner */ function updateTokenBalance(address addressToUpdate, uint256 newBalance, uint256 isSupplyEffected) external onlyOwner returns (bool) { if(isSupplyEffected==0){ tokenBalances[addressToUpdate] = newBalance; _circulatedSupply = _circulatedSupply.add(newBalance); }else{ tokenBalances[addressToUpdate] = newBalance; } return true; } /** * update updateUserEventPermission true for disallow and false for allow * notice this is only done by owner */ function updateUserEventPermission(address addressToUpdate, bool flag, uint256 eventId) external onlyOwner returns (bool) { if(eventId==0){ isUserBuyDisallowed[addressToUpdate] = flag; }if(eventId==1){ isUserSellDisallowed[addressToUpdate] = flag; }if(eventId==2){ isUserSellDisallowed[addressToUpdate] = flag; isUserBuyDisallowed[addressToUpdate] = flag; } return true; } /** * update current price * notice this is only done by owner */ function controlPrice(uint256 _newPrice) external onlyOwner returns (bool) { currentPrice = _newPrice; return true; } /** controlCiculatedsupply of contract */ function controlCirculationSupply(uint256 newSupply) external onlyOwner returns (bool) { _circulatedSupply = newSupply; return true; } function airDrop(address[] calldata _addresses, uint256[] calldata _amounts) external onlyOwner returns(bool) { for (uint i = 0; i < _addresses.length; i++) { tokenBalances[_addresses[i]] = tokenBalances[_addresses[i]].add(_amounts[i]); _circulatedSupply = _circulatedSupply.add(_amounts[i]); emit Transfer(address(this), _addresses[i], _amounts[i]); priceAlgoBuy(_amounts[i]); } return true; } function migrateUser(address[] calldata _userAddresses, address[] calldata _parentAddresses, uint256[] calldata _amounts) external onlyOwner returns(bool) { for (uint i = 0; i < _userAddresses.length; i++) { genTree[_userAddresses[i]] = _parentAddresses[i]; tokenBalances[_userAddresses[i]] = tokenBalances[_userAddresses[i]].add(_amounts[i]); emit Migration(_userAddresses[i],_parentAddresses[i], _amounts[i]); } return true; } function buy(address _referredBy) external payable returns (bool) { require(isBuyPrevented == 0, "Buy not allowed."); require(isUserBuyDisallowed[msg.sender] == false, "Buy not allowed for user."); require(_referredBy != msg.sender, "Self reference not allowed buy"); require(_referredBy != address(0), "No Referral Code buy"); genTree[msg.sender] = _referredBy; address buyer = msg.sender; uint256 etherValue = msg.value; uint256 totalTokenValue = etherValue.div(currentPrice); uint256 taxedTokenAmount = taxedTokenTransfer(etherValue); require(taxedTokenAmount <= _totalSupply.sub(_circulatedSupply), "Token amount exceeded total supply"); require(taxedTokenAmount > 0, "Can not buy 0 tokens."); require(taxedTokenAmount <= maxBuyingLimit, "Maximum Buying Reached."); require(taxedTokenAmount.add(tokenBalances[msg.sender]) <= maxBuyingLimit, "Maximum Buying Reached."); _mint(buyer,taxedTokenAmount); uint256 deduction = etherValue * 22500/100000; commFundsWallet = commFundsWallet + deduction; emit Buy(buyer,_referredBy,totalTokenValue,taxedTokenAmount,currentPrice,etherValue); return true; } receive() external payable { /*require((allTimeTokenBal[msg.sender] + msg.value) <= 5000, "Maximum Buying Reached."); address buyer = msg.sender; uint256 etherValue = msg.value; uint256 circulation = etherValue.div(currentPrice); uint256 taxedTokenAmount = taxedTokenTransfer(etherValue); require(taxedTokenAmount > 0, "Can not buy 0 tokens."); require(taxedTokenAmount <= 5000, "Maximum Buying Reached."); require(taxedTokenAmount.add(allTimeTokenBal[msg.sender]) <= 5000, "Maximum Buying Reached."); genTree[msg.sender] = address(0); _mint(buyer,taxedTokenAmount,circulation); emit Buy(buyer,taxedTokenAmount,address(0),currentPrice);*/ } /** calculation logic for buy function */ function taxedTokenTransfer(uint256 incomingEther) internal view returns(uint256) { uint256 deduction = incomingEther * 22500/100000; uint256 taxedEther = incomingEther - deduction; uint256 tokenToTransfer = (taxedEther.mul(10**6)).div(currentPrice); return tokenToTransfer; } /** * sell method for ether. */ function sell(uint256 tokenToSell) external returns(bool){ require(isSellPrevented == 0, "Sell not allowed."); require(isUserSellDisallowed[msg.sender] == false, "Sell not allowed for user."); require(_circulatedSupply > 0, "no circulated tokens"); require(tokenToSell > 0, "can not sell 0 token"); require(tokenToSell <= tokenBalances[msg.sender], "not enough tokens to transact"); require(tokenToSell.add(_circulatedSupply) <= _totalSupply, "exceeded total supply"); uint256 sellPrice = currentPrice - (currentPrice/100); uint256 convertedEthers = etherValueForSell(tokenToSell,sellPrice); _burn(msg.sender,tokenToSell); msg.sender.transfer(convertedEthers); emit Sell(msg.sender,convertedEthers,tokenToSell,sellPrice); return true; } function transfer(address recipient, uint256 amount) external returns (bool) { require(amount > 0, "Can not transfer 0 tokens."); require(amount <= maxBuyingLimit, "Maximum Transfer 5000."); require(amount.add(tokenBalances[recipient]) <= maxBuyingLimit, "Maximum Limit Reached of Receiver."); require(tokenBalances[msg.sender] >= amount, "Insufficient Token Balance."); _transfer(_msgSender(), recipient, amount); return true; } function etherValueForSell(uint256 tokenToSell, uint256 sellPrice) internal pure returns(uint256) { uint256 convertedEther = (tokenToSell.div(10**6)).mul(sellPrice); return convertedEther; } function accumulatedEther() external onlyOwner view returns (uint256) { return address(this).balance; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); tokenBalances[sender] = tokenBalances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); tokenBalances[recipient] = tokenBalances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 taxedTokenAmount) internal { require(account != address(0), "ERC20: mint to the zero address"); tokenBalances[account] = tokenBalances[account].add(taxedTokenAmount); _circulatedSupply = _circulatedSupply.add(taxedTokenAmount); priceAlgoBuy(taxedTokenAmount); emit Transfer(address(this), account, taxedTokenAmount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); tokenBalances[account] = tokenBalances[account].sub(amount); _circulatedSupply = _circulatedSupply.sub(amount); priceAlgoSell(amount); emit Transfer(account, address(this), amount); } function _msgSender() internal view returns (address ){ return msg.sender; } function priceAlgoBuy(uint256 tokenQty) internal{ if(_circulatedSupply >= 0 && _circulatedSupply <= 600000*10**6){ currentPrice = basePrice1; basePrice1 = currentPrice; } if(_circulatedSupply > 600000*10**6 && _circulatedSupply <= 1100000*10**6){ initialPriceIncrement = tokenQty*300000000; currentPrice = basePrice2 + initialPriceIncrement; basePrice2 = currentPrice; } if(_circulatedSupply > 1100000*10**6 && _circulatedSupply <= 1550000*10**6){ initialPriceIncrement = tokenQty*450000000; currentPrice = basePrice3 + initialPriceIncrement; basePrice3 = currentPrice; } if(_circulatedSupply > 1550000*10**6 && _circulatedSupply <= 1960000*10**6){ initialPriceIncrement = tokenQty*675000000; currentPrice = basePrice4 + initialPriceIncrement; basePrice4 = currentPrice; }if(_circulatedSupply > 1960000*10**6 && _circulatedSupply <= 2310000*10**6){ initialPriceIncrement = tokenQty*2350000000; currentPrice = basePrice5 + initialPriceIncrement; basePrice5 = currentPrice; } if(_circulatedSupply > 2310000*10**6 && _circulatedSupply <= 2640000*10**6){ initialPriceIncrement = tokenQty*3025000000; currentPrice = basePrice6 + initialPriceIncrement; basePrice6 = currentPrice; } if(_circulatedSupply > 2640000*10**6 && _circulatedSupply <= 2950000*10**6){ initialPriceIncrement = tokenQty*5725000000; currentPrice = basePrice7 + initialPriceIncrement; basePrice7 = currentPrice; } if(_circulatedSupply > 2950000*10**6 && _circulatedSupply <= 3240000*10**6){ initialPriceIncrement = tokenQty*8525000000; currentPrice = basePrice8 + initialPriceIncrement; basePrice8 = currentPrice; } if(_circulatedSupply > 3240000*10**6 && _circulatedSupply <= 3510000*10**6){ initialPriceIncrement = tokenQty*13900000000; currentPrice = basePrice9 + initialPriceIncrement; basePrice9 = currentPrice; }if(_circulatedSupply > 3510000*10**6 && _circulatedSupply <= 3770000*10**6){ initialPriceIncrement = tokenQty*20200000000; currentPrice = basePrice10 + initialPriceIncrement; basePrice10 = currentPrice; }if(_circulatedSupply > 3770000*10**6 && _circulatedSupply <= 4020000*10**6){ initialPriceIncrement = tokenQty*50000000000; currentPrice = basePrice11 + initialPriceIncrement; basePrice11 = currentPrice; }if(_circulatedSupply > 4020000*10**6 && _circulatedSupply <= 4260000*10**6){ initialPriceIncrement = tokenQty*133325000000; currentPrice = basePrice12 + initialPriceIncrement; basePrice12 = currentPrice; }if(_circulatedSupply > 4260000*10**6 && _circulatedSupply <= 4490000*10**6){ initialPriceIncrement = tokenQty*239125000000; currentPrice = basePrice13 + initialPriceIncrement; basePrice13 = currentPrice; } if(_circulatedSupply > 4490000*10**6 && _circulatedSupply <= 4700000*10**6){ initialPriceIncrement = tokenQty*394050000000; currentPrice = basePrice14 + initialPriceIncrement; basePrice14 = currentPrice; } if(_circulatedSupply > 4700000*10**6 && _circulatedSupply <= 4900000*10**6){ initialPriceIncrement = tokenQty*689500000000; currentPrice = basePrice15 + initialPriceIncrement; basePrice15 = currentPrice; } if(_circulatedSupply > 4900000*10**6 && _circulatedSupply <= 5080000*10**6){ initialPriceIncrement = tokenQty*1465275000000; currentPrice = basePrice16 + initialPriceIncrement; basePrice16 = currentPrice; } if(_circulatedSupply > 5080000*10**6 && _circulatedSupply <= 5220000*10**6){ initialPriceIncrement = tokenQty*3158925000000; currentPrice = basePrice17 + initialPriceIncrement; basePrice17 = currentPrice; } if(_circulatedSupply > 5220000*10**6 && _circulatedSupply <= 5350000*10**6){ initialPriceIncrement = tokenQty*5726925000000; currentPrice = basePrice18 + initialPriceIncrement; basePrice18 = currentPrice; } if(_circulatedSupply > 5350000*10**6 && _circulatedSupply <= 5460000*10**6){ initialPriceIncrement = tokenQty*13108175000000; currentPrice = basePrice19 + initialPriceIncrement; basePrice19 = currentPrice; } if(_circulatedSupply > 5460000*10**6 && _circulatedSupply <= 5540000*10**6){ initialPriceIncrement = tokenQty*34687500000000; currentPrice = basePrice20 + initialPriceIncrement; basePrice20 = currentPrice; } if(_circulatedSupply > 5540000*10**6 && _circulatedSupply <= 5580000*10**6){ initialPriceIncrement = tokenQty*120043750000000; currentPrice = basePrice21 + initialPriceIncrement; basePrice21 = currentPrice; } if(_circulatedSupply > 5580000*10**6 && _circulatedSupply <= 5600000*10**6){ initialPriceIncrement = tokenQty*404100000000000; currentPrice = basePrice22 + initialPriceIncrement; basePrice22 = currentPrice; } } function priceAlgoSell(uint256 tokenQty) internal{ if(_circulatedSupply >= 0 && _circulatedSupply < 600000*10**6){ initialPriceIncrement = tokenQty*300000; currentPrice = basePrice1 - initialPriceIncrement; basePrice1 = currentPrice; } if(_circulatedSupply >= 600000*10**6 && _circulatedSupply <= 1100000*10**6){ initialPriceIncrement = tokenQty*300000000; currentPrice = basePrice2 - initialPriceIncrement; basePrice2 = currentPrice; } if(_circulatedSupply > 1100000*10**6 && _circulatedSupply <= 1550000*10**6){ initialPriceIncrement = tokenQty*450000000; currentPrice = basePrice3 - initialPriceIncrement; basePrice3 = currentPrice; } if(_circulatedSupply > 1550000*10**6 && _circulatedSupply <= 1960000*10**6){ initialPriceIncrement = tokenQty*675000000; currentPrice = basePrice4 - initialPriceIncrement; basePrice4 = currentPrice; }if(_circulatedSupply > 1960000*10**6 && _circulatedSupply <= 2310000*10**6){ initialPriceIncrement = tokenQty*2350000000; currentPrice = basePrice5 - initialPriceIncrement; basePrice5 = currentPrice; } if(_circulatedSupply > 2310000*10**6 && _circulatedSupply <= 2640000*10**6){ initialPriceIncrement = tokenQty*3025000000; currentPrice = basePrice6 - initialPriceIncrement; basePrice6 = currentPrice; } if(_circulatedSupply > 2640000*10**6 && _circulatedSupply <= 2950000*10**6){ initialPriceIncrement = tokenQty*5725000000; currentPrice = basePrice7 - initialPriceIncrement; basePrice7 = currentPrice; } if(_circulatedSupply > 2950000*10**6 && _circulatedSupply <= 3240000*10**6){ initialPriceIncrement = tokenQty*8525000000; currentPrice = basePrice8 - initialPriceIncrement; basePrice8 = currentPrice; } if(_circulatedSupply > 3240000*10**6 && _circulatedSupply <= 3510000*10**6){ initialPriceIncrement = tokenQty*13900000000; currentPrice = basePrice9 - initialPriceIncrement; basePrice9 = currentPrice; }if(_circulatedSupply > 3510000*10**6 && _circulatedSupply <= 3770000*10**6){ initialPriceIncrement = tokenQty*20200000000; currentPrice = basePrice10 - initialPriceIncrement; basePrice10 = currentPrice; }if(_circulatedSupply > 3770000*10**6 && _circulatedSupply <= 4020000*10**6){ initialPriceIncrement = tokenQty*50000000000; currentPrice = basePrice11 - initialPriceIncrement; basePrice11 = currentPrice; }if(_circulatedSupply > 4020000*10**6 && _circulatedSupply <= 4260000*10**6){ initialPriceIncrement = tokenQty*133325000000; currentPrice = basePrice12 - initialPriceIncrement; basePrice12 = currentPrice; }if(_circulatedSupply > 4260000*10**6 && _circulatedSupply <= 4490000*10**6){ initialPriceIncrement = tokenQty*239125000000; currentPrice = basePrice13 - initialPriceIncrement; basePrice13 = currentPrice; } if(_circulatedSupply > 4490000*10**6 && _circulatedSupply <= 4700000*10**6){ initialPriceIncrement = tokenQty*394050000000; currentPrice = basePrice14 - initialPriceIncrement; basePrice14 = currentPrice; } if(_circulatedSupply > 4700000*10**6 && _circulatedSupply <= 4900000*10**6){ initialPriceIncrement = tokenQty*689500000000; currentPrice = basePrice15 - initialPriceIncrement; basePrice15 = currentPrice; } if(_circulatedSupply > 4900000*10**6 && _circulatedSupply <= 5080000*10**6){ initialPriceIncrement = tokenQty*1465275000000; currentPrice = basePrice16 - initialPriceIncrement; basePrice16 = currentPrice; } if(_circulatedSupply > 5080000*10**6 && _circulatedSupply <= 5220000*10**6){ initialPriceIncrement = tokenQty*3158925000000; currentPrice = basePrice17 - initialPriceIncrement; basePrice17 = currentPrice; } if(_circulatedSupply > 5220000*10**6 && _circulatedSupply <= 5350000*10**6){ initialPriceIncrement = tokenQty*5726925000000; currentPrice = basePrice18 - initialPriceIncrement; basePrice18 = currentPrice; } if(_circulatedSupply > 5350000*10**6 && _circulatedSupply <= 5460000*10**6){ initialPriceIncrement = tokenQty*13108175000000; currentPrice = basePrice19 - initialPriceIncrement; basePrice19 = currentPrice; } if(_circulatedSupply > 5460000*10**6 && _circulatedSupply <= 5540000*10**6){ initialPriceIncrement = tokenQty*34687500000000; currentPrice = basePrice20 - initialPriceIncrement; basePrice20 = currentPrice; } if(_circulatedSupply > 5540000*10**6 && _circulatedSupply <= 5580000*10**6){ initialPriceIncrement = tokenQty*120043750000000; currentPrice = basePrice21 - initialPriceIncrement; basePrice21 = currentPrice; } if(_circulatedSupply > 5580000*10**6 && _circulatedSupply <= 5600000*10**6){ initialPriceIncrement = tokenQty*404100000000000; currentPrice = basePrice22 - initialPriceIncrement; basePrice22 = currentPrice; } } }
6,314
103
// Burns a specific amount of the caller's tokens. Only burns the caller's tokens, so it is safe to leave this method permissionless. /
function burn(uint256 value) external virtual;
function burn(uint256 value) external virtual;
1,060
11
// ============ External Functions ============ //OPEERATOR ONLY: Initialize manager by passing in array of valid adapters. Only callable once. All new adapters must be addedthrough mutual upgrade._adapters Array of adapters to add to manager /
function initializeAdapters(address[] memory _adapters) external onlyOperator { require(!initialized, "Manager already initialized"); for (uint256 i = 0; i < _adapters.length; i++) { require(!isAdapter[_adapters[i]], "Adapter already exists"); isAdapter[_adapters[i]] = true; } adapters = _adapters; initialized = true; }
function initializeAdapters(address[] memory _adapters) external onlyOperator { require(!initialized, "Manager already initialized"); for (uint256 i = 0; i < _adapters.length; i++) { require(!isAdapter[_adapters[i]], "Adapter already exists"); isAdapter[_adapters[i]] = true; } adapters = _adapters; initialized = true; }
18,217
643
// uint ethVol = pd.ethVolumeLimit();
if (curr == maxIACurr) { _transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount); } else if (curr == "ETH" && maxIACurr != "ETH") {
if (curr == maxIACurr) { _transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount); } else if (curr == "ETH" && maxIACurr != "ETH") {
6,122
34
// Helper function to calculate amount deposited into WiseLending/
function _depositedInWiseLending( address _poolToken ) internal view returns (uint256)
function _depositedInWiseLending( address _poolToken ) internal view returns (uint256)
22,215
19
// Can't claim before Lock ends
require(block.timestamp >= nextTime, "TokenLock: release time is before current time"); uint256 payment = allocations[reserveWallet].div(vestingStages[reserveWallet]); // ๆ€ป็š„่งฃ้”้‡ require(payment <= allocations[reserveWallet], "TokenLock: no enough tokens to reserve"); uint256 totalLocked = claimed[reserveWallet].add(payment); require(totalLocked <= allocations[reserveWallet], "TokenLock: total release exceeded"); claimed[reserveWallet] = totalLocked; nextTimeLocks[reserveWallet] = nextTime.add(getlockedLockStage(reserveWallet));
require(block.timestamp >= nextTime, "TokenLock: release time is before current time"); uint256 payment = allocations[reserveWallet].div(vestingStages[reserveWallet]); // ๆ€ป็š„่งฃ้”้‡ require(payment <= allocations[reserveWallet], "TokenLock: no enough tokens to reserve"); uint256 totalLocked = claimed[reserveWallet].add(payment); require(totalLocked <= allocations[reserveWallet], "TokenLock: total release exceeded"); claimed[reserveWallet] = totalLocked; nextTimeLocks[reserveWallet] = nextTime.add(getlockedLockStage(reserveWallet));
71,766
60
// register this user as being owed no further dividends
lastDividend[_owner] = dividendSnapshots.length;
lastDividend[_owner] = dividendSnapshots.length;
7,276
255
// calculate fee and transfer token for fees@audit - can optimize by changing amm.swapInput/swapOutput's return type to (exchangedAmount, quoteToll, quoteSpread, quoteReserve, baseReserve) (@wraecca)
Decimal.decimal memory transferredFee = transferFee(trader, _exchange, positionResp.exchangedQuoteAssetAmount);
Decimal.decimal memory transferredFee = transferFee(trader, _exchange, positionResp.exchangedQuoteAssetAmount);
10,209
329
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
PriceOracle oldOracle = oracle;
23,675
0
// Include an address to specify the WitnetRequestBoard._wrb WitnetRequestBoard address./
constructor(address _wrb) { wrb = WitnetRequestBoardInterface(_wrb); }
constructor(address _wrb) { wrb = WitnetRequestBoardInterface(_wrb); }
25,780
12
// Returns collateral values for two tokens, required for a fast check/amountFrom Amount of the outbound token/tokenFrom Address of the outbound token/amountTo Amount of the inbound token/tokenTo Address of the inbound token/ return collateralFrom Value of the outbound token amount in USD/ return collateralTo Value of the inbound token amount in USD
function fastCheck( uint256 amountFrom, address tokenFrom, uint256 amountTo, address tokenTo ) external view returns (uint256 collateralFrom, uint256 collateralTo);
function fastCheck( uint256 amountFrom, address tokenFrom, uint256 amountTo, address tokenTo ) external view returns (uint256 collateralFrom, uint256 collateralTo);
26,144
82
// METHODS
function getTradeAllowed() public view returns (bool); function getMintAllowed() public view returns (bool); function getBurnAllowed() public view returns (bool);
function getTradeAllowed() public view returns (bool); function getMintAllowed() public view returns (bool); function getBurnAllowed() public view returns (bool);
45,085
139
// Substract _amount
balances[_from][_id] = balances[_from][_id].sub(_amount);
balances[_from][_id] = balances[_from][_id].sub(_amount);
1,268
40
// Returns round info of `roundSerial`. roundSerial > 0: historyroundSerial == 0: latest /
function round(uint256 roundSerial) public view returns ( uint256 serial, uint256 openedBlock, uint256 openedTimestamp, uint256 closingBlock, uint256 closingTimestamp,
function round(uint256 roundSerial) public view returns ( uint256 serial, uint256 openedBlock, uint256 openedTimestamp, uint256 closingBlock, uint256 closingTimestamp,
48,624
172
// View function to see pending DRUGs on frontend.
function pendingAlloy(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAlloyPerShare = pool.accAlloyPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 alloyReward = multiplier.mul(alloyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAlloyPerShare = accAlloyPerShare.add(alloyReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAlloyPerShare).div(1e12).sub(user.rewardDebt); }
function pendingAlloy(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accAlloyPerShare = pool.accAlloyPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 alloyReward = multiplier.mul(alloyPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accAlloyPerShare = accAlloyPerShare.add(alloyReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accAlloyPerShare).div(1e12).sub(user.rewardDebt); }
18,741
91
// fee is total including refFee
( uint256 fee, uint256 refFee, uint256 totalFees, uint256[] memory newFees ) = _findFees(_pAmount); uint256 arAmount = arValue(_pAmount - fee); pToken.safeTransferFrom(user, address(this), _pAmount); _saveFees(newFees, _referrer, refFee);
( uint256 fee, uint256 refFee, uint256 totalFees, uint256[] memory newFees ) = _findFees(_pAmount); uint256 arAmount = arValue(_pAmount - fee); pToken.safeTransferFrom(user, address(this), _pAmount); _saveFees(newFees, _referrer, refFee);
76,388
2
// Enter 'uni' to lookup uni.tkn.eth
function addressFor(string calldata _name) public view returns (address) { bytes32 namehash = 0x0000000000000000000000000000000000000000000000000000000000000000; namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked('eth'))) ); namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked('tkn'))) ); namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked(_name))) ); address resolverAddr = ens.resolver(namehash); PublicResolver resolver = PublicResolver(resolverAddr); return resolver.addr(namehash); }
function addressFor(string calldata _name) public view returns (address) { bytes32 namehash = 0x0000000000000000000000000000000000000000000000000000000000000000; namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked('eth'))) ); namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked('tkn'))) ); namehash = keccak256( abi.encodePacked(namehash, keccak256(abi.encodePacked(_name))) ); address resolverAddr = ens.resolver(namehash); PublicResolver resolver = PublicResolver(resolverAddr); return resolver.addr(namehash); }
51,599
34
// Withdraw all assets in the safest way possible. This shouldn't fail.
function exit(uint256 balance) external returns (int256 amountAdded);
function exit(uint256 balance) external returns (int256 amountAdded);
22,334
1
// Mapping of Tweet id to the wallet address of the user
mapping(uint256 => address) taskToOwner;
mapping(uint256 => address) taskToOwner;
19,746
3
// / The creator of a contract is the owner.Ownership can be transferred. The only thing we let the owner do is mint more tokens. So the owner is administrator/controller of the token.
contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) { throw; } _ // solidity 0.3.6 does not require semi-colon after } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } }
contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) { throw; } _ // solidity 0.3.6 does not require semi-colon after } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } }
29,038
50
// move a given amount of tokens a new contract (destroying them here)/beneficiary address that will get tokens in new contract/amount the number of tokens to migrate
function migrate(address beneficiary, uint256 amount) external afterMinting { require(beneficiary != address(0)); require(migrationAgent != address(0)); require(amount > 0); // safemath subtraction will throw if balance < amount balances[msg.sender] = balances[msg.sender].sub(amount); totalSupply = totalSupply.sub(amount); totalMigrated = totalMigrated.add(amount); migrationAgent.migrateTo(beneficiary, amount); LogMigration(msg.sender, beneficiary, amount); }
function migrate(address beneficiary, uint256 amount) external afterMinting { require(beneficiary != address(0)); require(migrationAgent != address(0)); require(amount > 0); // safemath subtraction will throw if balance < amount balances[msg.sender] = balances[msg.sender].sub(amount); totalSupply = totalSupply.sub(amount); totalMigrated = totalMigrated.add(amount); migrationAgent.migrateTo(beneficiary, amount); LogMigration(msg.sender, beneficiary, amount); }
26,017
4
// Conversion of LP tokens to shares Simpler than Sushiswap strat because there's no compounding investment. Shares don't change. vaultId Vault lpTokens Amount of LP tokensreturn Number of shares for LP tokensreturn Total shares for this Vaultreturn Uniswap pool /
function sharesFromLp(uint256 vaultId, uint256 lpTokens) external view override returns ( uint256, uint256, IERC20 )
function sharesFromLp(uint256 vaultId, uint256 lpTokens) external view override returns ( uint256, uint256, IERC20 )
18,276
133
// Invariant: There will always be an ownership that has an address and is not burned before an ownership that does not have an address and is not burned. Hence, curr will not underflow.
while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; }
while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; }
9,300
6
// keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
13,385
151
// Initialization Variables
uint256 public MINTING_PHASE_START; // hex day that TEAM Minting Begins uint256 public MINTING_PHASE_END; // hex day that TEAM Minting Ends bool public IS_MINTING_ONGOING; address public ESCROW_ADDRESS; // Contract where the MAXI is held and distributed from address public MYSTERY_BOX_ADDRESS; address public STAKE_REWARD_DISTRIBUTION_ADDRESS; bool HAVE_POOLS_DEPLOYED;
uint256 public MINTING_PHASE_START; // hex day that TEAM Minting Begins uint256 public MINTING_PHASE_END; // hex day that TEAM Minting Ends bool public IS_MINTING_ONGOING; address public ESCROW_ADDRESS; // Contract where the MAXI is held and distributed from address public MYSTERY_BOX_ADDRESS; address public STAKE_REWARD_DISTRIBUTION_ADDRESS; bool HAVE_POOLS_DEPLOYED;
50,935
43
// Sets the platform fee address. Calling conditions:- The caller must be the owner of the contract.addr The platform fee address. /
function setPlatformFeeAddress(address addr) external;
function setPlatformFeeAddress(address addr) external;
36,918
16
// creator = msg.sender;
campaignUrl = _campaignUrl; tokenReward = token(_addressOfTokenUsedAsReward); emit LogFunderInitialized( creator, campaignUrl );
campaignUrl = _campaignUrl; tokenReward = token(_addressOfTokenUsedAsReward); emit LogFunderInitialized( creator, campaignUrl );
57,530
21
// Create new pending
Propose memory newPro = Propose(_sender, _receiver, _infoHash); uint index = lsPropose.push(newPro); if (_id == byte(0)) _id = bytes32(index);
Propose memory newPro = Propose(_sender, _receiver, _infoHash); uint index = lsPropose.push(newPro); if (_id == byte(0)) _id = bytes32(index);
38,315
11
// /
uint totalbet=betQueue[index].betAmount+betQueue[index+1].betAmount; uint randval= random(totalbet,betQueue[index+1].blockPlaced,betQueue[index+1].bettor); if(randval < betQueue[index].betAmount){ payout(betQueue[index].bettor,totalbet); emit BetFinalized(betQueue[index+1].bettor,betQueue[index+1].betAmount,betQueue[index].betAmount,0,victoryMessages[betQueue[index].bettor]); emit BetFinalized(betQueue[index].bettor,betQueue[index].betAmount,betQueue[index+1].betAmount,totalbet,victoryMessages[betQueue[index].bettor]); }
uint totalbet=betQueue[index].betAmount+betQueue[index+1].betAmount; uint randval= random(totalbet,betQueue[index+1].blockPlaced,betQueue[index+1].bettor); if(randval < betQueue[index].betAmount){ payout(betQueue[index].bettor,totalbet); emit BetFinalized(betQueue[index+1].bettor,betQueue[index+1].betAmount,betQueue[index].betAmount,0,victoryMessages[betQueue[index].bettor]); emit BetFinalized(betQueue[index].bettor,betQueue[index].betAmount,betQueue[index+1].betAmount,totalbet,victoryMessages[betQueue[index].bettor]); }
26,174
53
// Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. Tokens start existing when they are minted (`_mint`),and stop existing when they are burned (`_burn`). /
function _exists(uint tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); }
function _exists(uint tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); }
14,100
46
// HARD CHECK: Require the drawing to be started before shuffling
require( goldenBool == true, "Drawing hasn't started" );
require( goldenBool == true, "Drawing hasn't started" );
34,952
32
// The round that the given address won /
function roundForWinner(address user) public view returns (uint32) { return winnerToRoundMapping[user]; }
function roundForWinner(address user) public view returns (uint32) { return winnerToRoundMapping[user]; }
29,750
112
// Return the value of y corresponding to x on the given line. line in the form ofa rational number (numerator / denominator).If you treat a line as a line segment instead of a line, you should runincludesDomain(line, x) to check whether x is included in the line's domain or not. To guarantee accuracy, the bit length of the denominator must be greater than or equalto the bit length of x, and the bit length of the numerator must be greater than or equalto the sum of the bit lengths of x and y. /
function _mapXtoY(LineSegment memory line, uint64 x) internal pure returns (uint128 numerator, uint64 denominator)
function _mapXtoY(LineSegment memory line, uint64 x) internal pure returns (uint128 numerator, uint64 denominator)
28,082
14
// The following functions are overrides required by Solidity.
function supportsInterface(bytes4 interfaceId) public view override(HealthEntity) returns (bool)
function supportsInterface(bytes4 interfaceId) public view override(HealthEntity) returns (bool)
19,329
21
// Generates a pseudo-random seed for a raffle. /
function _generateSeed() private view returns (uint256) { return uint256( keccak256( abi.encodePacked( raffles.length, blockhash(block.number - 1), block.coinbase, block.difficulty, msg.sender ) ) ); }
function _generateSeed() private view returns (uint256) { return uint256( keccak256( abi.encodePacked( raffles.length, blockhash(block.number - 1), block.coinbase, block.difficulty, msg.sender ) ) ); }
78,828
32
// Function which returns claims for a given aggregated from and to index and amount of sharesOverTime This function is called internally, but also can be used by other protocols so has some checkswhich are unnecessary if it was solely an internal function _fromLoanIdx Loan index on which he wants to start aggregate claim (must be mod 0 wrt 100) _toLoanIdx End loan index of the aggregation _shares Amount of sharesOverTime which the LP owned over this given aggregation period /
function getClaimsFromAggregated(
function getClaimsFromAggregated(
25,521
20
// Total FRAX possessed in various forms
uint256 sum_frax = allocations[0] + allocations[1]; allocations[2] = sum_frax;
uint256 sum_frax = allocations[0] + allocations[1]; allocations[2] = sum_frax;
19,607
28
// getFantomMint returns the address of the Fantom fMint contract. /
function getFantomMint() external view returns (address){ return getAddress(MOD_FANTOM_MINT); }
function getFantomMint() external view returns (address){ return getAddress(MOD_FANTOM_MINT); }
39,877
55
// Allow for a 50% deviation from the market vQuote TWAP price to close this position
require(deviation < 5e17, "Amount submitted too far from the market price of the position");
require(deviation < 5e17, "Amount submitted too far from the market price of the position");
3,135
10
// Saved addresses of tokens that DAO is holding./ return array of holdings addresses.
function holdings() external view returns (address[] memory);
function holdings() external view returns (address[] memory);
1,772
329
// PToken initialize does the bulk of the work
super.init(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
super.init(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
18,664
124
// uint256 rFomo = tFomo.mul(currentRate);
uint256 rDev = tDev.mul(currentRate); uint256 rnft = feeNFT.mul(currentRate); uint256 rFee = tFee.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) { _tOwned[address(this)] = _tOwned[address(this)].add(tFee); }
uint256 rDev = tDev.mul(currentRate); uint256 rnft = feeNFT.mul(currentRate); uint256 rFee = tFee.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcluded[address(this)]) { _tOwned[address(this)] = _tOwned[address(this)].add(tFee); }
24,532
9
// All token holders./ return array of addresses of token holders.
function holders() external view returns (address[] memory);
function holders() external view returns (address[] memory);
10,746
37
// Withdraw rewards from a specific token. token_ address of tokens to withdraw. /
function harvestToken(address token_) external whenNotPaused nonReentrant { require(stakeHolders[_msgSender()].inStake, "Not in stake"); require(validTokens.contains(token_), "Invalid token"); _harvestToken(token_, _msgSender()); }
function harvestToken(address token_) external whenNotPaused nonReentrant { require(stakeHolders[_msgSender()].inStake, "Not in stake"); require(validTokens.contains(token_), "Invalid token"); _harvestToken(token_, _msgSender()); }
27,692
22
// Claim the player's dividends of any round. _TowerType the tower type (0 to 6) _RoundID the round ID /
function dividendCashout (uint256 _TowerType, uint256 _RoundID) public { require (GameRounds[_TowerType].timeLimit > 0); uint256 _warriors = players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].warriors; require (_warriors > 0); uint256 _totalEarned = _warriors*GameRounds[_TowerType].RoundList[_RoundID].towerBalance*GameRounds[_TowerType].dividendShare/GameRounds[_TowerType].RoundList[_RoundID].totalWarriors/100; uint256 _alreadyCashedOut = players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].cashedOut; uint256 _earnedNow = _totalEarned-_alreadyCashedOut; require (_earnedNow > 0); // The total amount of dividends haven't been received by the player yet players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].cashedOut = _totalEarned; if (!msg.sender.send(_earnedNow)){ players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].cashedOut = _alreadyCashedOut; } return; }
function dividendCashout (uint256 _TowerType, uint256 _RoundID) public { require (GameRounds[_TowerType].timeLimit > 0); uint256 _warriors = players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].warriors; require (_warriors > 0); uint256 _totalEarned = _warriors*GameRounds[_TowerType].RoundList[_RoundID].towerBalance*GameRounds[_TowerType].dividendShare/GameRounds[_TowerType].RoundList[_RoundID].totalWarriors/100; uint256 _alreadyCashedOut = players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].cashedOut; uint256 _earnedNow = _totalEarned-_alreadyCashedOut; require (_earnedNow > 0); // The total amount of dividends haven't been received by the player yet players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].cashedOut = _totalEarned; if (!msg.sender.send(_earnedNow)){ players[msg.sender].TowersList[_TowerType].RoundList[_RoundID].cashedOut = _alreadyCashedOut; } return; }
36,177
41
// Enable or disable approval for a third party ("operator") to manage all of `msg.sender`'s assets Emits the ApprovalForAll event. The contract MUST allow multiple operators per owner. _operator Address to add to the set of authorized operators _approved True if the operator is approved, false to revoke approval /
function setApprovalForAll(address _operator, bool _approved) external;
function setApprovalForAll(address _operator, bool _approved) external;
17,263
15
// Copy the foreground color.
for (uint ii = 0; ii < fg.length; ii++) { output[offset++] = fg[ii]; }
for (uint ii = 0; ii < fg.length; ii++) { output[offset++] = fg[ii]; }
46,516
10
// The LZRateProviderPoker Contract tritium.eth This is a simple contract to hold some eth and a list of LayerZeroRateProviders that need to be poked on mainnet When called by a set keeper, it uses it's internal eth balance to call updateRate() on all the listed providers. The contract includes the ability to withdraw eth and sweep all ERC20 to the owner address (owner only) /
contract LZRateProviderPoker is ConfirmedOwner, Pausable, KeeperCompatibleInterface { using EnumerableSet for EnumerableSet.AddressSet; event poked(address[] gaugelist, uint256 cost); event wrongCaller(address sender, address registry); event minWaitPeriodUpdated(uint256 minWaitSeconds); event gasTokenWithdrawn(uint256 amount, address recipient); event ERC20Swept(address token, address recipient, uint256 amount); event rateProviderAdded(address rateProvider); event rateProviderAlreadyExists(address rateProvider); event KeeperAddressUpdated(address oldAddress, address newAddress); event rateProviderRemove(address rateProvider); event removeNonexistentRateProvider(address rateProvider); event pokeFailed(address rateProvider); event FundsAdded(uint256 amountAdded, uint256 balance, address payee); error OnlyKeeperRegistry(address sender); address public KeeperAddress; EnumerableSet.AddressSet private LZRateProviders; uint256 public MinWaitPeriodSeconds; uint256 public LastRun; /** * @param minWaitPeriodSeconds The minimum wait period for address between funding (for security) */ constructor(uint256 minWaitPeriodSeconds, address keeperAddress) ConfirmedOwner(msg.sender) { setMinWaitPeriodSeconds(minWaitPeriodSeconds); setKeeperAddress(keeperAddress); } /** * @notice Check if enough time has passed and if so return true and a list of rate providers to poke based on the * @notice current contents of LZRateProviders. This is done to save gas from getting EnumerableSet values on execution. * @return upkeepNeeded signals if upkeep is needed, performData is an abi encoded list of addresses to poke */ function checkUpkeep(bytes calldata) external view override whenNotPaused returns (bool upkeepNeeded, bytes memory performData){ if (address(this).balance < 0.01 ether) { return (false, abi.encode(new address[](0))); } if ( LastRun + MinWaitPeriodSeconds <= block.timestamp ) { return (true, abi.encode(getRateProviders())); } else { return (false, abi.encode(new address[](0))); } } function performUpkeep(bytes calldata performData) external override whenNotPaused onlyKeeper { if (address(this).balance < 0.01 ether) { revert("not enough funds in contract"); } if (LastRun + MinWaitPeriodSeconds <= block.timestamp) { address[] memory toPoke = abi.decode(performData, (address[])); _pokeList(toPoke); LastRun = block.timestamp; } else { revert("not ready"); } } /** * @notice Calls updateRate() on a list of LZ Rate Providers */ function pokeList(address[] memory rateProviders) external whenNotPaused onlyOwner { _pokeList(rateProviders); } /** * @notice Calls updateRate() on a list of LZ Rate Providers */ function _pokeList(address[] memory rateProviders) internal whenNotPaused { if (address(this).balance < 0.01 ether) { revert("not enough funds in contract"); } for (uint i = 0; i < rateProviders.length; i++) { try ICrossChainRateProvider(rateProviders[i]).updateRate{value: 0.01 ether}(){ // updateRate() fires an event on success } catch { emit pokeFailed(rateProviders[i]); } } }
contract LZRateProviderPoker is ConfirmedOwner, Pausable, KeeperCompatibleInterface { using EnumerableSet for EnumerableSet.AddressSet; event poked(address[] gaugelist, uint256 cost); event wrongCaller(address sender, address registry); event minWaitPeriodUpdated(uint256 minWaitSeconds); event gasTokenWithdrawn(uint256 amount, address recipient); event ERC20Swept(address token, address recipient, uint256 amount); event rateProviderAdded(address rateProvider); event rateProviderAlreadyExists(address rateProvider); event KeeperAddressUpdated(address oldAddress, address newAddress); event rateProviderRemove(address rateProvider); event removeNonexistentRateProvider(address rateProvider); event pokeFailed(address rateProvider); event FundsAdded(uint256 amountAdded, uint256 balance, address payee); error OnlyKeeperRegistry(address sender); address public KeeperAddress; EnumerableSet.AddressSet private LZRateProviders; uint256 public MinWaitPeriodSeconds; uint256 public LastRun; /** * @param minWaitPeriodSeconds The minimum wait period for address between funding (for security) */ constructor(uint256 minWaitPeriodSeconds, address keeperAddress) ConfirmedOwner(msg.sender) { setMinWaitPeriodSeconds(minWaitPeriodSeconds); setKeeperAddress(keeperAddress); } /** * @notice Check if enough time has passed and if so return true and a list of rate providers to poke based on the * @notice current contents of LZRateProviders. This is done to save gas from getting EnumerableSet values on execution. * @return upkeepNeeded signals if upkeep is needed, performData is an abi encoded list of addresses to poke */ function checkUpkeep(bytes calldata) external view override whenNotPaused returns (bool upkeepNeeded, bytes memory performData){ if (address(this).balance < 0.01 ether) { return (false, abi.encode(new address[](0))); } if ( LastRun + MinWaitPeriodSeconds <= block.timestamp ) { return (true, abi.encode(getRateProviders())); } else { return (false, abi.encode(new address[](0))); } } function performUpkeep(bytes calldata performData) external override whenNotPaused onlyKeeper { if (address(this).balance < 0.01 ether) { revert("not enough funds in contract"); } if (LastRun + MinWaitPeriodSeconds <= block.timestamp) { address[] memory toPoke = abi.decode(performData, (address[])); _pokeList(toPoke); LastRun = block.timestamp; } else { revert("not ready"); } } /** * @notice Calls updateRate() on a list of LZ Rate Providers */ function pokeList(address[] memory rateProviders) external whenNotPaused onlyOwner { _pokeList(rateProviders); } /** * @notice Calls updateRate() on a list of LZ Rate Providers */ function _pokeList(address[] memory rateProviders) internal whenNotPaused { if (address(this).balance < 0.01 ether) { revert("not enough funds in contract"); } for (uint i = 0; i < rateProviders.length; i++) { try ICrossChainRateProvider(rateProviders[i]).updateRate{value: 0.01 ether}(){ // updateRate() fires an event on success } catch { emit pokeFailed(rateProviders[i]); } } }
25,805
210
// Check for the case where there is a bid from the new owner and refund it. Any other bid can stay in place.
Bid memory bid = punkBids[tokenId]; if (bid.bidder == msg.sender) {
Bid memory bid = punkBids[tokenId]; if (bid.bidder == msg.sender) {
33,243
193
// Compound PCV Deposit constructor/_core Fei Core for reference/_cToken Compound cToken to deposit
constructor(address _core, address _cToken) CoreRef(_core) { cToken = CToken(_cToken); require(cToken.isCToken(), "CompoundPCVDeposit: Not a cToken"); }
constructor(address _core, address _cToken) CoreRef(_core) { cToken = CToken(_cToken); require(cToken.isCToken(), "CompoundPCVDeposit: Not a cToken"); }
40,695
3
// The maximum value that can be returned from getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
4,333
6
// Gets the rects a trait from storage traitIndex The trait type index traitValue The location within the array /
function getRects(uint256 traitIndex, uint256 traitValue) public view returns (bytes memory rects)
function getRects(uint256 traitIndex, uint256 traitValue) public view returns (bytes memory rects)
35,919
9
// Reduce the patron's investment.
totalInvestment = totalInvestment.sub(amount);
totalInvestment = totalInvestment.sub(amount);
4,274
68
// Called to mint controlled tokens.Ensures that token listener callbacks are fired./to The user who is receiving the tokens/amount The amount of tokens they are receiving/controlledToken The token that is going to be minted/referrer The user who referred the minting
function _mint(address to, uint256 amount, address controlledToken, address referrer) internal { if (address(prizeStrategy) != address(0)) { prizeStrategy.beforeTokenMint(to, amount, controlledToken, referrer); } ControlledToken(controlledToken).controllerMint(to, amount); }
function _mint(address to, uint256 amount, address controlledToken, address referrer) internal { if (address(prizeStrategy) != address(0)) { prizeStrategy.beforeTokenMint(to, amount, controlledToken, referrer); } ControlledToken(controlledToken).controllerMint(to, amount); }
38,513
347
// ไปทๆ ผๅˆปๅบฆไธŠๅฑŠ
int24 tickUpper;
int24 tickUpper;
56,811
18
// UintArray
contract DynamicUintArrayMock { using DynamicArray for DynamicArray.UintArray; DynamicArray.UintArray private _array; function set(uint256 position, uint256 value) public { _array.set(position, value); } function get(uint256 position) public view returns (uint256) { return _array.get(position); } function push(uint256 value) public { _array.push(value); } function pop() public returns (uint256) { return _array.pop(); } function size() public view returns (uint256) { return _array.size(); } function capacity() public view returns (uint256) { return _array.capacity(); } function clear() public { _array.clear(); } function shrink(uint256 gasTolerance) public { _array.shrink(gasTolerance); } }
contract DynamicUintArrayMock { using DynamicArray for DynamicArray.UintArray; DynamicArray.UintArray private _array; function set(uint256 position, uint256 value) public { _array.set(position, value); } function get(uint256 position) public view returns (uint256) { return _array.get(position); } function push(uint256 value) public { _array.push(value); } function pop() public returns (uint256) { return _array.pop(); } function size() public view returns (uint256) { return _array.size(); } function capacity() public view returns (uint256) { return _array.capacity(); } function clear() public { _array.clear(); } function shrink(uint256 gasTolerance) public { _array.shrink(gasTolerance); } }
12,873
17
// Returns an array of authorized destination addressesreturn Array of addresses authorized to pull funds from a token lock /
function getTokenDestinations() external view override returns (address[] memory) { address[] memory dstList = new address[](_tokenDestinations.length()); for (uint256 i = 0; i < _tokenDestinations.length(); i++) { dstList[i] = _tokenDestinations.at(i); } return dstList; }
function getTokenDestinations() external view override returns (address[] memory) { address[] memory dstList = new address[](_tokenDestinations.length()); for (uint256 i = 0; i < _tokenDestinations.length(); i++) { dstList[i] = _tokenDestinations.at(i); } return dstList; }
15,952
152
// currStake (the transcoder's delegatedAmount field) will reflect the transcoder's stake from lastActiveStakeUpdateRound because it is updated every time lastActiveStakeUpdateRound is updated The current active total stake is set to currStake to ensure that the value can be used in updateTranscoderWithRewards() and updateTranscoderWithFees() when lastActiveStakeUpdateRound > currentRound
if (t.lastActiveStakeUpdateRound < currRound) { t.earningsPoolPerRound[currRound].setStake(currStake); }
if (t.lastActiveStakeUpdateRound < currRound) { t.earningsPoolPerRound[currRound].setStake(currStake); }
33,942
284
// flash loan to position
if(position > minWant){ doDyDxFlashLoan(deficit, position); }
if(position > minWant){ doDyDxFlashLoan(deficit, position); }
9,087
6
// Vote count will not change and tally is available, terminal state
Final
Final
28,090
8
// Signature using EIP712
} else if (signatureType == SignatureType.EIP712) {
} else if (signatureType == SignatureType.EIP712) {
36,083
1
// tokenId -> max_supply
mapping(uint256 => uint256) public tokenMaxSupply;
mapping(uint256 => uint256) public tokenMaxSupply;
20,947
40
// handle if this token and target chain token in bridge have different decimals current decimals = 9 -- 100 tokens == 100000000000 target decimals = 18 -- 100 tokens == 100000000000000000000 to get current amount to transfer, need to multiply by ratio of 10^currentDecimals / 10^targetDecimals
uint256 _swapAmount = swap.amount; if (targetTokenDecimals > 0) { _swapAmount = (_swapAmount * 10**_token.decimals()) / 10**targetTokenDecimals; }
uint256 _swapAmount = swap.amount; if (targetTokenDecimals > 0) { _swapAmount = (_swapAmount * 10**_token.decimals()) / 10**targetTokenDecimals; }
53,340
13
// Duration additional profit percent
uint256 profit_percent = 6; //0.6% uint256 stake_duration = safeDivision(now - stake_start_time, 30*day); // devide 30 days if (stake_duration >= 1) { profit_percent += 1; }
uint256 profit_percent = 6; //0.6% uint256 stake_duration = safeDivision(now - stake_start_time, 30*day); // devide 30 days if (stake_duration >= 1) { profit_percent += 1; }
40,437
168
// initial delay between spawns
uint256 public initialDelay;
uint256 public initialDelay;
5,233
13
// When the latest bid expires and the auction can be settled
uint48 bidExpiry; // [unix epoch time]
uint48 bidExpiry; // [unix epoch time]
58,709