ERC-20
Protocol
Overview
Max Total Supply
9,826,421.458087471694577316 asoBLAST
Holders
56 (0.00%)
Market
Price
$0.00 @ 0.000000 ETH
Onchain Market Cap
$0.00
Circulating Supply Market Cap
-
Other Info
Token Contract (WITH 18 Decimals)
Loading...
Loading
Loading...
Loading
Loading...
Loading
Contract Name:
CErc20Immutable
Compiler Version
v0.8.19+commit.7dd6d404
Optimization Enabled:
Yes with 50 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; import "./CErc20.sol"; /** * @title Compound's CErc20Immutable Contract * @notice CTokens which wrap an EIP-20 underlying and are immutable * @author Compound */ contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor( address underlying_, Comptroller comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_ ) { // Creator of the contract is admin during initialization admin = payable(msg.sender); // Initialize the market initialize( underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_ ); // Set the proper admin now that initialization is done admin = admin_; } }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; import "./CToken.sol"; interface CompLike { function delegate(address delegatee) external; } /** * @title Compound's CErc20 Contract * @notice CTokens which wrap an EIP-20 underlying * @author Compound */ contract CErc20 is CToken, CErc20Interface { /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( address underlying_, Comptroller comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { // CToken initialize does the bulk of the work super.initialize( comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_ ); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external override returns (uint) { mintInternal(mintAmount); return NO_ERROR; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external override returns (uint) { redeemInternal(redeemTokens); return NO_ERROR; } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying( uint redeemAmount ) external override returns (uint) { redeemUnderlyingInternal(redeemAmount); return NO_ERROR; } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external override returns (uint) { borrowInternal(borrowAmount); return NO_ERROR; } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay, or -1 for the full outstanding amount * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external override returns (uint) { repayBorrowInternal(repayAmount); return NO_ERROR; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay, or -1 for the full outstanding amount * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf( address borrower, uint repayAmount ) external override returns (uint) { repayBorrowBehalfInternal(borrower, repayAmount); return NO_ERROR; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow( address borrower, uint repayAmount, CTokenInterface cTokenCollateral ) external override returns (uint) { liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return NO_ERROR; } /** * @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock) * @param token The address of the ERC-20 token to sweep */ function sweepToken(EIP20NonStandardInterface token) external override { require( msg.sender == admin, "CErc20::sweepToken: only admin can sweep tokens" ); require( address(token) != underlying, "CErc20::sweepToken: can not sweep underlying token" ); uint256 balance = token.balanceOf(address(this)); token.transfer(admin, balance); } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external override returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view virtual override returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn( address from, uint amount ) internal virtual override returns (uint) { // Read from storage once address underlying_ = underlying; EIP20NonStandardInterface token = EIP20NonStandardInterface( underlying_ ); uint balanceBefore = EIP20Interface(underlying_).balanceOf( address(this) ); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of override external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying_).balanceOf( address(this) ); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut( address payable to, uint amount ) internal virtual override { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of override external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./Comptroller.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./EIP20Interface.sol"; import "./InterestRateModel.sol"; import "./ExponentialNoError.sol"; import "./es33/RewardDistributor.sol"; import "./lib/RPow.sol"; import "./Blast.sol"; /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ abstract contract CToken is CTokenInterface, ExponentialNoError, TokenErrorReporter, BlastCommon { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( Comptroller comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { initializeBlast(); require(msg.sender == admin, "only admin may initialize the market"); require( accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once" ); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require( initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero." ); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == NO_ERROR, "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == NO_ERROR, "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; lastObservedRebaseFactor = getRebaseFactor(); } function getRebaseFactor() public virtual returns (uint256) { return 1; } function observeRebase() internal returns (uint256, uint256) { uint256 rebaseFactor = getRebaseFactor(); uint256 lastRebaseFactor = lastObservedRebaseFactor; lastObservedRebaseFactor = rebaseFactor; return (rebaseFactor, lastRebaseFactor); } function updateDistributor(address payable dist_) external { if (msg.sender != admin) { revert SetPendingAdminOwnerCheck(); } dist = RewardDistributor(dist_); } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return 0 if the transfer succeeded, else revert */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256) { /* Fail if transfer not allowed */ uint256 allowed = comptroller.transferAllowed( address(this), src, dst, tokens ); if (allowed != 0) { revert TransferComptrollerRejection(allowed); } /* Do not allow self-transfers */ if (src == dst) { revert TransferNotAllowed(); } /* Get the allowance, infinite for the account owner */ uint256 startingAllowance = 0; if (spender == src) { startingAllowance = type(uint256).max; } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ uint256 allowanceNew = startingAllowance - tokens; uint256 srcTokensNew = accountTokens[src] - tokens; uint256 dstTokensNew = accountTokens[dst] + tokens; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != type(uint256).max) { transferAllowances[src][spender] = allowanceNew; } dist.onAssetDecrease(bytes32("SUPPLY"), src, tokens); dist.onAssetIncrease(bytes32("SUPPLY"), dst, tokens); /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.emitTransfer( src, dst, accountTokens[src], accountTokens[dst] ); // unused function // comptroller.transferVerify(address(this), src, dst, tokens); return NO_ERROR; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer( address dst, uint256 amount ) external override nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == NO_ERROR; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external override nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == NO_ERROR; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (uint256.max means infinite) * @return Whether or not the approval succeeded */ function approve( address spender, uint256 amount ) external override returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance( address owner, address spender ) external view override returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view override returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying( address owner ) external override returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); return mul_ScalarTruncate(exchangeRate, accountTokens[owner]); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot( address account ) external view override returns (uint256, uint256, uint256, uint256) { return ( NO_ERROR, accountTokens[account], borrowBalanceStoredInternal(account), exchangeRateStoredInternal() ); } function getStaticBalance( address acc ) external view returns (uint256, uint256) { return ( accountTokens[acc], accountBorrows[acc].interestIndex == 0 ? 0 : ((accountBorrows[acc].principal * 1e18) / accountBorrows[acc].interestIndex) ); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view virtual returns (uint256) { return block.timestamp; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view override returns (uint256) { return interestRateModel.getBorrowRate( getCashPrior(), totalBorrows, totalReserves ); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view override returns (uint256) { return interestRateModel.getSupplyRate( getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa ); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external override nonReentrant returns (uint256) { accrueInterest(); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent( address account ) external override nonReentrant returns (uint256) { accrueInterest(); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored( address account ) public view override returns (uint256) { return borrowBalanceStoredInternal(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal( address account ) internal view returns (uint256) { /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return 0; } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ uint256 principalTimesIndex = borrowSnapshot.principal * borrowIndex; return principalTimesIndex / borrowSnapshot.interestIndex; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public override nonReentrant returns (uint256) { accrueInterest(); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view override returns (uint256) { return exchangeRateStoredInternal(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return calculated exchange rate scaled by 1e18 */ function exchangeRateStoredInternal() internal view virtual returns (uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return initialExchangeRateMantissa; } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint256 totalCash = getCashPrior(); uint256 cashPlusBorrowsMinusReserves = totalCash + totalBorrows - totalReserves; uint256 exchangeRate = (cashPlusBorrowsMinusReserves * expScale) / _totalSupply; return exchangeRate; } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view override returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public virtual override returns (uint256) { /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return NO_ERROR; } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate( cashPrior, borrowsPrior, reservesPrior ); require( borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high" ); /* Calculate the number of blocks elapsed since the last accrual */ uint256 blockDelta = currentBlockNumber - accrualBlockNumberPrior; /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = (1 + borrowRate) ** blockDelta -- this is different from the original code (1.01 vs 0.01) * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ uint256 simpleInterestFactor = RPow.rpow( 1e18 + borrowRateMantissa, blockDelta, 1e18 ); (uint256 rebaseFactor, uint256 lastRebaseFactor) = observeRebase(); uint256 totalBorrowsNewBeforeRebase = (simpleInterestFactor * borrowsPrior) / 1e18; uint256 interestAccumulated = totalBorrowsNewBeforeRebase - borrowsPrior; uint256 totalReservesNew = (reservesPrior * rebaseFactor) / lastRebaseFactor + ((reserveFactorMantissa * interestAccumulated) / 1e18); uint256 totalBorrowsNew = (totalBorrowsNewBeforeRebase * rebaseFactor) / lastRebaseFactor; uint256 borrowIndexNew = (((simpleInterestFactor * borrowIndexPrior) / 1e18) * rebaseFactor) / lastRebaseFactor; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ comptroller.emitAccrueInterest( interestAccumulated, borrowIndexNew, exchangeRateStoredInternal() ); return NO_ERROR; } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply */ function mintInternal(uint256 mintAmount) internal nonReentrant { accrueInterest(); // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to mintFresh(msg.sender, mintAmount); } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply */ function mintFresh(address minter, uint256 mintAmount) internal { /* Fail if mint not allowed */ uint256 allowed = comptroller.mintAllowed( address(this), minter, mintAmount ); if (allowed != 0) { revert MintComptrollerRejection(allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { revert MintFreshnessCheck(); } Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()}); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ uint256 actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ uint256 mintTokens = div_(actualMintAmount, exchangeRate); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens * And write them into storage */ totalSupply = totalSupply + mintTokens; accountTokens[minter] = accountTokens[minter] + mintTokens; dist.onAssetIncrease(bytes32("SUPPLY"), minter, mintTokens); /* We emit a Mint event, and a Transfer event */ emit Mint(minter, actualMintAmount, mintTokens); comptroller.emitMint(minter, actualMintAmount, mintTokens); emit Transfer(address(0), minter, mintTokens); comptroller.emitTransfer( address(this), minter, 0, accountTokens[minter] ); /* We call the defense hook */ // unused function // comptroller.mintVerify(address(this), minter, actualMintAmount, mintTokens); } event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying */ function redeemInternal(uint256 redeemTokens) internal nonReentrant { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to redeemFresh(payable(msg.sender), redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens */ function redeemUnderlyingInternal( uint256 redeemAmount ) internal nonReentrant { accrueInterest(); // redeemFresh emits redeem-specific logs on errors, so we don't need to redeemFresh(payable(msg.sender), 0, redeemAmount); } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn ) internal { require( redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero" ); /* exchangeRate = invoke Exchange Rate Stored() */ Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()}); uint256 redeemTokens; uint256 redeemAmount; /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ redeemTokens = redeemTokensIn; redeemAmount = mul_ScalarTruncate(exchangeRate, redeemTokensIn); } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ redeemTokens = Math.ceilDiv( redeemAmountIn * 1e18, exchangeRate.mantissa ); redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint256 allowed = comptroller.redeemAllowed( address(this), redeemer, redeemTokens ); if (allowed != 0) { revert RedeemComptrollerRejection(allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { revert RedeemFreshnessCheck(); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < redeemAmount) { revert RedeemTransferOutNotPossible(); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We write the previously calculated values into storage. * Note: Avoid token reentrancy attacks by writing reduced supply before external transfer. */ totalSupply = totalSupply - redeemTokens; accountTokens[redeemer] = accountTokens[redeemer] - redeemTokens; /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, redeemAmount); dist.onAssetDecrease(bytes32("SUPPLY"), redeemer, redeemTokens); /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(0), redeemTokens); comptroller.emitTransfer( redeemer, address(this), accountTokens[redeemer], 0 ); comptroller.emitRedeem(redeemer, redeemAmount, redeemTokens); emit Redeem(redeemer, redeemAmount, redeemTokens); /* We call the defense hook */ comptroller.redeemVerify( address(this), redeemer, redeemAmount, redeemTokens ); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow */ function borrowInternal(uint256 borrowAmount) internal nonReentrant { accrueInterest(); // borrowFresh emits borrow-specific logs on errors, so we don't need to borrowFresh(payable(msg.sender), borrowAmount); } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow */ function borrowFresh( address payable borrower, uint256 borrowAmount ) internal { /* Fail if borrow not allowed */ uint256 allowed = comptroller.borrowAllowed( address(this), borrower, borrowAmount ); if (allowed != 0) { revert BorrowComptrollerRejection(allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { revert BorrowFreshnessCheck(); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { revert BorrowCashNotAvailable(); } /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowNew = accountBorrow + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ uint256 accountBorrowsPrev = borrowBalanceStoredInternal(borrower); uint256 accountBorrowsNew = accountBorrowsPrev + borrowAmount; uint256 totalBorrowsNew = totalBorrows + borrowAmount; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We write the previously calculated values into storage. * Note: Avoid token reentrancy attacks by writing increased borrow before external transfer. `*/ accountBorrows[borrower].principal = accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = totalBorrowsNew; /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); dist.onAssetIncrease( bytes32("BORROW"), borrower, ((borrowAmount * 1e18) / borrowIndex) ); /* We emit a Borrow event */ comptroller.emitBorrow( borrower, borrowAmount, accountBorrowsNew, totalBorrowsNew, (accountBorrowsNew * 1e18) / borrowIndex ); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay, or -1 for the full outstanding amount */ function repayBorrowInternal(uint256 repayAmount) internal nonReentrant { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay, or -1 for the full outstanding amount */ function repayBorrowBehalfInternal( address borrower, uint256 repayAmount ) internal nonReentrant { accrueInterest(); // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to repayBorrowFresh(msg.sender, borrower, repayAmount); } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of underlying tokens being returned, or -1 for the full outstanding amount * @return (uint) the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount ) internal returns (uint256) { /* Fail if repayBorrow not allowed */ uint256 allowed = comptroller.repayBorrowAllowed( address(this), payer, borrower, repayAmount ); if (allowed != 0) { revert RepayBorrowComptrollerRejection(allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { revert RepayBorrowFreshnessCheck(); } /* We fetch the amount the borrower owes, with accumulated interest */ uint256 accountBorrowsPrev = borrowBalanceStoredInternal(borrower); /* If repayAmount == -1, repayAmount = accountBorrows */ uint256 repayAmountFinal = repayAmount == type(uint256).max ? accountBorrowsPrev : repayAmount; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ uint256 actualRepayAmount = doTransferIn(payer, repayAmountFinal); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ uint256 accountBorrowsNew = accountBorrowsPrev - actualRepayAmount; uint256 totalBorrowsNew = totalBorrows - actualRepayAmount; /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = totalBorrowsNew; dist.onAssetChange( bytes32("BORROW"), borrower, ((accountBorrowsNew * 1e18) / borrowIndex) ); /* We emit a RepayBorrow event */ comptroller.emitRepayBorrow( payer, borrower, actualRepayAmount, accountBorrowsNew, totalBorrowsNew, (accountBorrowsNew * 1e18) / borrowIndex ); return actualRepayAmount; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) internal nonReentrant { accrueInterest(); uint256 error = cTokenCollateral.accrueInterest(); if (error != NO_ERROR) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed revert LiquidateAccrueCollateralInterestFailed(error); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to liquidateBorrowFresh( msg.sender, borrower, repayAmount, cTokenCollateral ); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) internal { /* Fail if liquidate not allowed */ uint256 allowed = comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ); if (allowed != 0) { revert LiquidateComptrollerRejection(allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { revert LiquidateFreshnessCheck(); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { revert LiquidateCollateralFreshnessCheck(); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { revert LiquidateLiquidatorIsBorrower(); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { revert LiquidateCloseAmountIsZero(); } /* Fail if repayAmount = -1 */ if (repayAmount == type(uint256).max) { revert LiquidateCloseAmountIsUintMax(); } /* Fail if repayBorrow fails */ uint256 actualRepayAmount = repayBorrowFresh( liquidator, borrower, repayAmount ); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint256 amountSeizeError, uint256 seizeTokens) = comptroller .liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), actualRepayAmount ); require( amountSeizeError == NO_ERROR, "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED" ); /* Revert if borrower collateral token balance < seizeTokens */ require( cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH" ); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call if (address(cTokenCollateral) == address(this)) { seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { require( cTokenCollateral.seize(liquidator, borrower, seizeTokens) == NO_ERROR, "token seizure failed" ); } /* We emit a LiquidateBorrow event */ comptroller.emitLiquidateBorrow( liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens ); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external override nonReentrant returns (uint256) { seizeInternal(msg.sender, liquidator, borrower, seizeTokens); return NO_ERROR; } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal { /* Fail if seize not allowed */ uint256 allowed = comptroller.seizeAllowed( address(this), seizerToken, liquidator, borrower, seizeTokens ); if (allowed != 0) { revert LiquidateSeizeComptrollerRejection(allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { revert LiquidateSeizeLiquidatorIsBorrower(); } /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ uint256 protocolSeizeTokens = mul_( seizeTokens, Exp({mantissa: protocolSeizeShareMantissa}) ); uint256 liquidatorSeizeTokens = seizeTokens - protocolSeizeTokens; Exp memory exchangeRate = Exp({mantissa: exchangeRateStoredInternal()}); uint256 protocolSeizeAmount = mul_ScalarTruncate( exchangeRate, protocolSeizeTokens ); uint256 totalReservesNew = totalReserves + protocolSeizeAmount; ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the calculated values into storage */ totalReserves = totalReservesNew; totalSupply = totalSupply - protocolSeizeTokens; accountTokens[borrower] = accountTokens[borrower] - seizeTokens; accountTokens[liquidator] = accountTokens[liquidator] + liquidatorSeizeTokens; dist.onAssetDecrease(bytes32("SUPPLY"), borrower, seizeTokens); dist.onAssetIncrease( bytes32("SUPPLY"), liquidator, liquidatorSeizeTokens ); /* Emit a Transfer event */ emit Transfer(borrower, liquidator, liquidatorSeizeTokens); comptroller.emitTransfer( borrower, liquidator, accountTokens[borrower], accountTokens[liquidator] ); emit Transfer(borrower, address(0), protocolSeizeTokens); emit ReservesAdded( address(this), protocolSeizeAmount, totalReservesNew ); } /** * Admin Functions ** */ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin( address payable newPendingAdmin ) external override returns (uint256) { // Check caller = admin if (msg.sender != admin) { revert SetPendingAdminOwnerCheck(); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return NO_ERROR; } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external override returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { revert AcceptAdminPendingAdminCheck(); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = payable(address(0)); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return NO_ERROR; } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller( Comptroller newComptroller ) public override returns (uint256) { // Check caller is admin if (msg.sender != admin) { revert SetComptrollerOwnerCheck(); } Comptroller oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return NO_ERROR; } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor( uint256 newReserveFactorMantissa ) external override nonReentrant returns (uint256) { accrueInterest(); // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh( uint256 newReserveFactorMantissa ) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { revert SetReserveFactorAdminCheck(); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { revert SetReserveFactorFreshCheck(); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { revert SetReserveFactorBoundsCheck(); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor( oldReserveFactorMantissa, newReserveFactorMantissa ); return NO_ERROR; } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal( uint256 addAmount ) internal nonReentrant returns (uint256) { accrueInterest(); // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. _addReservesFresh(addAmount); return NO_ERROR; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh( uint256 addAmount ) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { revert AddReservesFactorFreshCheck(actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (NO_ERROR, actualAddAmount); } function takeReserves(address to) external returns (uint256) { // Check caller is admin or distributor if (msg.sender != admin && msg.sender != address(dist)) { revert ReduceReservesAdminCheck(); } // Store reserves[n+1] = reserves[n] - reduceAmount accrueInterest(); uint256 amount = totalReserves; totalReserves = 0; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(payable(address(to)), amount); emit ReservesReduced(msg.sender, totalReserves, 0); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves( uint256 reduceAmount ) external override nonReentrant returns (uint256) { accrueInterest(); // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh( uint256 reduceAmount ) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin or distributor if (msg.sender != admin && msg.sender != address(dist)) { revert ReduceReservesAdminCheck(); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { revert ReduceReservesFreshCheck(); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { revert ReduceReservesCashNotAvailable(); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { revert ReduceReservesCashValidation(); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(payable(address(dist)), reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return NO_ERROR; } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel( InterestRateModel newInterestRateModel ) public override returns (uint256) { accrueInterest(); // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh( InterestRateModel newInterestRateModel ) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { revert SetInterestRateModelOwnerCheck(); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { revert SetInterestRateModelFreshCheck(); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require( newInterestRateModel.isInterestRateModel(), "marker method returned false" ); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel( oldInterestRateModel, newInterestRateModel ); return NO_ERROR; } /** * Safe Token ** */ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view virtual returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn( address from, uint256 amount ) internal virtual returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure rather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint256 amount) internal virtual; /** * Reentrancy Guard ** */ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { enum Rounding { Down, // Toward negative infinity Up, // Toward infinity Zero // Toward zero } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) * with further edits by Uniswap Labs also under MIT license. */ function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 twos = denominator & (~denominator + 1); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv( uint256 x, uint256 y, uint256 denominator, Rounding rounding ) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10**64) { value /= 10**64; result += 64; } if (value >= 10**32) { value /= 10**32; result += 32; } if (value >= 10**16) { value /= 10**16; result += 16; } if (value >= 10**8) { value /= 10**8; result += 8; } if (value >= 10**4) { value /= 10**4; result += 4; } if (value >= 10**2) { value /= 10**2; result += 2; } if (value >= 10**1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0); } } }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./CToken.sol"; import "./ErrorReporter.sol"; import "./PriceOracle.sol"; import "./Comptroller.sol"; import "./ComptrollerStorage.sol"; import "./Unitroller.sol"; import "./ExponentialNoError.sol"; import "./Blast.sol"; /** * @title Compound's Comptroller Contract * @author Compound */ contract Comptroller is ComptrollerV7Storage, ComptrollerErrorReporter, ExponentialNoError, BlastCommon { bool public constant isComptroller = true; /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor( uint oldCloseFactorMantissa, uint newCloseFactorMantissa ); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor( CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa ); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive( uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa ); /// @notice Emitted when price oracle is changed event NewPriceOracle( PriceOracle oldPriceOracle, PriceOracle newPriceOracle ); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when a new borrow-side COMP speed is calculated for a market event CompBorrowSpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when a new supply-side COMP speed is calculated for a market event CompSupplySpeedUpdated(CToken indexed cToken, uint newSpeed); /// @notice Emitted when a new COMP speed is set for a contributor event ContributorCompSpeedUpdated( address indexed contributor, uint newSpeed ); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp( CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex ); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp( CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex ); /// @notice Emitted when borrow cap for a cToken is changed event NewBorrowCap(CToken indexed cToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian( address oldBorrowCapGuardian, address newBorrowCapGuardian ); /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 constructor() { admin = msg.sender; initializeBlastClaimable(); } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn( address account ) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership( address account, CToken cToken ) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets( address[] memory cTokens ) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal( CToken cToken, address borrower ) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = cToken .getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail( Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED ); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal( cTokenAddress, msg.sender, tokensHeld ); if (allowed != 0) { return failOpaque( Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed ); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.pop(); emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed( address cToken, address minter, uint mintAmount ) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify( address cToken, address minter, uint actualMintAmount, uint mintTokens ) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed( address cToken, address redeemer, uint redeemTokens ) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving return uint(Error.NO_ERROR); } function redeemAllowedInternal( address cToken, address redeemer, uint redeemTokens ) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal( redeemer, CToken(cToken), redeemTokens, 0 ); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify( address cToken, address redeemer, uint redeemAmount, uint redeemTokens ) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed( address cToken, address borrower, uint borrowAmount ) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[cToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = CToken(cToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal( borrower, CToken(cToken), 0, borrowAmount ); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify( address cToken, address borrower, uint borrowAmount ) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount ) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex ) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } function whitelistLiquidator(address a) external { require(msg.sender == admin, "unauthorized"); whitelistedLiquidator = a; } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount ) external returns (uint) { // Shh - currently unused if (whitelistedLiquidator != address(0)) { require(liquidator == whitelistedLiquidator, "not whitelisted"); } if ( !markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed ) { return uint(Error.MARKET_NOT_LISTED); } uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored( borrower ); /* allow accounts to be liquidated if the market is deprecated */ if (isDeprecated(CToken(cTokenBorrowed))) { require( borrowBalance >= repayAmount, "Can not repay more than the total borrow" ); } else { /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal( borrower ); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint maxClose = mul_ScalarTruncate( Exp({mantissa: closeFactorMantissa}), borrowBalance ); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens ) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens ) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if ( !markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed ) { return uint(Error.MARKET_NOT_LISTED); } if ( CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller() ) { return uint(Error.COMPTROLLER_MISMATCH); } return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens ) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed( address cToken, address src, address dst, uint transferTokens ) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify( address cToken, address src, address dst, uint transferTokens ) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity( address account ) public view returns (uint, uint, uint) { ( Error err, uint liquidity, uint shortfall ) = getHypotheticalAccountLiquidityInternal( account, CToken(address(0)), 0, 0 ); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal( address account ) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal( account, CToken(address(0)), 0, 0 ); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount ) public view returns (uint, uint, uint) { ( Error err, uint liquidity, uint shortfall ) = getHypotheticalAccountLiquidityInternal( account, CToken(cTokenModify), redeemTokens, borrowAmount ); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount ) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken ( oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa ) = asset.getAccountSnapshot(account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({ mantissa: markets[address(asset)].collateralFactorMantissa }); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) vars.tokensToDenom = mul_( mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice ); // sumCollateral += tokensToDenom * cTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt( vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral ); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects ); // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects ); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt( vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects ); } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return ( Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0 ); } else { return ( Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral ); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount ) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice( CToken(cTokenBorrowed) ); uint priceCollateralMantissa = oracle.getUnderlyingPrice( CToken(cTokenCollateral) ); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral) .exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; numerator = mul_( Exp({mantissa: liquidationIncentiveMantissa}), Exp({mantissa: priceBorrowedMantissa}) ); denominator = mul_( Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}) ); ratio = div_(numerator, denominator); seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount); return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK ); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor( uint newCloseFactorMantissa ) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor( CToken cToken, uint newCollateralFactorMantissa ) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK ); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail( Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS ); } Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa }); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail( Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION ); } /* // If collateral factor != 0, fail if price == 0 if ( newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0 ) { return fail( Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE ); } */ // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor( cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa ); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive( uint newLiquidationIncentiveMantissa ) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK ); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive( oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa ); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK ); } if (markets[address(cToken)].isListed) { return fail( Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS ); } cToken.isCToken(); // Sanity check to make sure its really a CToken // Note that isComped is not in active use anymore Market storage newMarket = markets[address(cToken)]; newMarket.isListed = true; newMarket.collateralFactorMantissa = 0; _addMarketInternal(address(cToken)); emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param cTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps( CToken[] calldata cTokens, uint[] calldata newBorrowCaps ) external { require( msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps" ); uint numMarkets = cTokens.length; uint numBorrowCaps = newBorrowCaps.length; require( numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input" ); for (uint i = 0; i < numMarkets; i++) { borrowCaps[address(cTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(cTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK ); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require( markets[address(cToken)].isListed, "cannot pause a market that is not listed" ); require( msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause" ); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require( markets[address(cToken)].isListed, "cannot pause a market that is not listed" ); require( msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause" ); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit ActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require( msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause" ); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require( msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause" ); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require( msg.sender == unitroller.admin(), "only unitroller admin can change brains" ); require( unitroller._acceptImplementation() == 0, "change not authorized" ); } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getEnteredMarkets( address addr ) public view returns (CToken[] memory) { return accountAssets[addr]; } /** * @notice Returns true if the given cToken market has been deprecated * @dev All borrows in a deprecated cToken market can be immediately liquidated * @param cToken The market to check if deprecated */ function isDeprecated(CToken cToken) public view returns (bool) { return markets[address(cToken)].collateralFactorMantissa == 0 && borrowGuardianPaused[address(cToken)] == true && cToken.reserveFactorMantissa() == 1e18; } function getBlockNumber() public view virtual returns (uint) { return block.timestamp; } /** * @notice Event emitted when tokens are minted */ /** * @notice Event emitted when tokens are redeemed */ event Redeem( address cToken, address redeemer, uint redeemAmount, uint redeemTokens ); function emitRedeem( address redeemer, uint redeemAmount, uint redeemTokens ) external { require(markets[msg.sender].isListed, "unlisted"); emit Redeem(msg.sender, redeemer, redeemAmount, redeemTokens); } event Borrow( address cToken, address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows, uint256 accountStaticBorrows ); function emitBorrow( address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows, uint256 accountStaticBorrows ) external { require(markets[msg.sender].isListed, "unlisted"); emit Borrow( msg.sender, borrower, borrowAmount, accountBorrows, totalBorrows, accountStaticBorrows ); } event Mint( address indexed cToken, address minter, uint mintAmount, uint mintTokens ); function emitMint( address minter, uint mintAmount, uint mintTokens ) external { require(markets[msg.sender].isListed, "unlisted"); emit Mint(msg.sender, minter, mintAmount, mintTokens); } event RepayBorrow( address indexed cToken, address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows, uint accountStaticBorrows ); function emitRepayBorrow( address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows, uint accountStaticBorrows ) external { require(markets[msg.sender].isListed, "unlisted"); emit RepayBorrow( msg.sender, payer, borrower, repayAmount, accountBorrows, totalBorrows, accountStaticBorrows ); } event LiquidateBorrow( address indexed cToken, address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens ); function emitLiquidateBorrow( address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens ) external { require(markets[msg.sender].isListed, "unlisted"); emit LiquidateBorrow( msg.sender, liquidator, borrower, repayAmount, cTokenCollateral, seizeTokens ); } event AccrueInterest( address indexed cToken, uint interestAccumulated, uint borrowIndex, uint exchangeRate ); function emitAccrueInterest(uint256 acc, uint256 bi, uint256 er) external { require(markets[msg.sender].isListed, "unlisted"); emit AccrueInterest(msg.sender, acc, bi, er); } event Transferred( address indexed cToken, address src, address dst, uint256 srcBalance, uint256 dstBalance ); function emitTransfer( address src, address dst, uint srcBalance, uint dstBalance ) external { require(markets[msg.sender].isListed, "unlisted"); emit Transferred(msg.sender, src, dst, srcBalance, dstBalance); } }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; import "./Comptroller.sol"; import "./InterestRateModel.sol"; import "./EIP20NonStandardInterface.sol"; import "./ErrorReporter.sol"; import "./es33/RewardDistributor.sol"; contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; // Maximum borrow rate that can ever be applied (.0005% / block) uint internal constant borrowRateMaxMantissa = 0.0005e16; // Maximum fraction of interest that can be set aside for reserves uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ Comptroller public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; // Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint256 public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; // Official record of token balances for each account mapping(address => uint) internal accountTokens; // Approved token transfer amounts on behalf of others mapping(address => mapping(address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } // Mapping of account addresses to outstanding borrow balances mapping(address => BorrowSnapshot) internal accountBorrows; /** * @notice Share of seized collateral that is added to reserves */ uint public constant protocolSeizeShareMantissa = 2.8e16; //2.8% RewardDistributor public dist; uint lastObservedRebaseFactor; } abstract contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller( Comptroller oldComptroller, Comptroller newComptroller ); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel( InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel ); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor( uint oldReserveFactorMantissa, uint newReserveFactorMantissa ); /** * @notice Event emitted when the reserves are added */ event ReservesAdded( address benefactor, uint addAmount, uint newTotalReserves ); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced( address admin, uint reduceAmount, uint newTotalReserves ); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /*** User Interface ***/ function transfer(address dst, uint amount) external virtual returns (bool); function transferFrom( address src, address dst, uint amount ) external virtual returns (bool); function approve( address spender, uint amount ) external virtual returns (bool); function allowance( address owner, address spender ) external view virtual returns (uint); function balanceOf(address owner) external view virtual returns (uint); function balanceOfUnderlying(address owner) external virtual returns (uint); function getAccountSnapshot( address account ) external view virtual returns (uint, uint, uint, uint); function borrowRatePerBlock() external view virtual returns (uint); function supplyRatePerBlock() external view virtual returns (uint); function totalBorrowsCurrent() external virtual returns (uint); function borrowBalanceCurrent( address account ) external virtual returns (uint); function borrowBalanceStored( address account ) external view virtual returns (uint); function exchangeRateCurrent() external virtual returns (uint); function exchangeRateStored() external view virtual returns (uint); function getCash() external view virtual returns (uint); function accrueInterest() external virtual returns (uint); function seize( address liquidator, address borrower, uint seizeTokens ) external virtual returns (uint); /*** Admin Functions ***/ function _setPendingAdmin( address payable newPendingAdmin ) external virtual returns (uint); function _acceptAdmin() external virtual returns (uint); function _setComptroller( Comptroller newComptroller ) external virtual returns (uint); function _setReserveFactor( uint newReserveFactorMantissa ) external virtual returns (uint); function _reduceReserves(uint reduceAmount) external virtual returns (uint); function _setInterestRateModel( InterestRateModel newInterestRateModel ) external virtual returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } abstract contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external virtual returns (uint); function redeem(uint redeemTokens) external virtual returns (uint); function redeemUnderlying( uint redeemAmount ) external virtual returns (uint); function borrow(uint borrowAmount) external virtual returns (uint); function repayBorrow(uint repayAmount) external virtual returns (uint); function repayBorrowBehalf( address borrower, uint repayAmount ) external virtual returns (uint); function liquidateBorrow( address borrower, uint repayAmount, CTokenInterface cTokenCollateral ) external virtual returns (uint); function sweepToken(EIP20NonStandardInterface token) external virtual; /*** Admin Functions ***/ function _addReserves(uint addAmount) external virtual returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } abstract contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation( address oldImplementation, address newImplementation ); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) external virtual; } abstract contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) external virtual; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() external virtual; }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { uint public constant NO_ERROR = 0; // support legacy return codes error TransferComptrollerRejection(uint256 errorCode); error TransferNotAllowed(); error TransferNotEnough(); error TransferTooMuch(); error MintComptrollerRejection(uint256 errorCode); error MintFreshnessCheck(); error RedeemComptrollerRejection(uint256 errorCode); error RedeemFreshnessCheck(); error RedeemTransferOutNotPossible(); error BorrowComptrollerRejection(uint256 errorCode); error BorrowFreshnessCheck(); error BorrowCashNotAvailable(); error RepayBorrowComptrollerRejection(uint256 errorCode); error RepayBorrowFreshnessCheck(); error LiquidateComptrollerRejection(uint256 errorCode); error LiquidateFreshnessCheck(); error LiquidateCollateralFreshnessCheck(); error LiquidateAccrueBorrowInterestFailed(uint256 errorCode); error LiquidateAccrueCollateralInterestFailed(uint256 errorCode); error LiquidateLiquidatorIsBorrower(); error LiquidateCloseAmountIsZero(); error LiquidateCloseAmountIsUintMax(); error LiquidateRepayBorrowFreshFailed(uint256 errorCode); error LiquidateSeizeComptrollerRejection(uint256 errorCode); error LiquidateSeizeLiquidatorIsBorrower(); error AcceptAdminPendingAdminCheck(); error SetComptrollerOwnerCheck(); error SetPendingAdminOwnerCheck(); error SetReserveFactorAdminCheck(); error SetReserveFactorFreshCheck(); error SetReserveFactorBoundsCheck(); error AddReservesFactorFreshCheck(uint256 actualAddAmount); error ReduceReservesAdminCheck(); error ReduceReservesFreshCheck(); error ReduceReservesCashNotAvailable(); error ReduceReservesCashValidation(); error SetInterestRateModelOwnerCheck(); error SetInterestRateModelFreshCheck(); }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return success Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; /** * @title Compound's InterestRateModel Interface * @author Compound */ abstract contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) virtual external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) virtual external view returns (uint); }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return a + b; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return a * b; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin-upgradeable/contracts/access/OwnableUpgradeable.sol"; import "@openzeppelin-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol"; import "../lib/Ledger.sol"; import "../CToken.sol"; import "../CErc20.sol"; import "../interfaces/IRouter.sol"; import "../IVault.sol"; import "../interfaces/IWETH.sol"; import "./ES33.sol"; import "../SimplePriceOracle.sol"; interface IGauge { function emissionShare(address) external returns (uint256); } interface IComptroller { function getAllMarkets() external view returns (address[] memory); } interface VelocoreLens { function emissionRate(address gauge) external returns (uint256); } contract TokenEmitter is BlastCommon, Ownable { IERC20 public immutable underlying; uint256 public emissionsSoFar; constructor(address owner_, IERC20 underlying_) { underlying = underlying_; _transferOwnership(owner_); } function emissionCurve(uint256 t) public view returns (uint256) { if (t < 1715526000) return 0; return 60_000_000e18 - (60_000_000e18 * RPow.rpow(0.999999971481121650e18, t - 1715526000, 1e18)) / 1e18; } function emissionRate() external view returns (uint256) { return emissionCurve(block.timestamp + 1) - emissionCurve(block.timestamp); } function emitTokens() external onlyOwner returns (uint256) { uint256 emission = emissionCurve(block.timestamp) - emissionsSoFar; emissionsSoFar += emission; underlying.transfer(owner(), emission); return emission; } } contract RewardDistributor is OwnableUpgradeable, ReentrancyGuardUpgradeable, ERC1967Upgrade, BlastCommon { using LedgerLib for Ledger; using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; bytes32 public constant BRIBE_ACCOUNT = bytes32("BRIBE"); ES33 public underlying; address immutable lens; address immutable gauge; address immutable oracle; address immutable vc; address immutable usdc; address immutable vault; IComptroller immutable comptroller; address immutable stakingContract; Ledger weights; mapping(bytes32 => Ledger) assetLedgers; mapping(address => uint256) accruedInterest; uint256 wtlosRate; uint256 lastWTLOSEmission; TokenEmitter emitter; event Harvest(address addr, uint256 amount); constructor( address vault_, address lens_, address gauge_, address usdc_, address vc_, address oracle_, address comptroller_, address stakeContract ) { vault = vault_; lens = lens_; gauge = gauge_; vc = vc_; oracle = oracle_; usdc = usdc_; comptroller = IComptroller(comptroller_); stakingContract = stakeContract; initializeBlastClaimable(); } function upgradeToAndCall( address newImplementation, bytes memory data ) external onlyOwner { ERC1967Upgrade._upgradeToAndCall(newImplementation, data, true); } function upgradeTo(address newImplementation) external onlyOwner { ERC1967Upgrade._upgradeTo(newImplementation); } function initialize(address admin, ES33 underlying_) external initializer { initializeBlastClaimable(); _transferOwnership(admin); __ReentrancyGuard_init(); underlying = underlying_; } // todo: takeLP function slot(address a) internal pure returns (bytes32) { return bytes32(uint256(uint160(a))); } function slot(IERC20 a) internal pure returns (bytes32) { return slot(address(a)); } function slot( address informationSource, bytes32 kind ) public pure returns (bytes32) { return keccak256(abi.encode(informationSource, kind)); } function onAssetIncrease( bytes32 kind, address account, uint256 delta ) external nonReentrant { bytes32[] memory a = new bytes32[](1); a[0] = slot(msg.sender, kind); _harvest(account, a); Ledger storage ledger = assetLedgers[slot(msg.sender, kind)]; ledger.deposit(slot(account), delta); } function onAssetDecrease( bytes32 kind, address account, uint256 delta ) external nonReentrant { bytes32[] memory a = new bytes32[](1); a[0] = slot(msg.sender, kind); _harvest(account, a); Ledger storage ledger = assetLedgers[slot(msg.sender, kind)]; ledger.withdraw(slot(account), delta); } function onAssetChange( bytes32 kind, address account, uint256 amount ) external nonReentrant { bytes32[] memory a = new bytes32[](1); a[0] = slot(msg.sender, kind); _harvest(account, a); Ledger storage ledger = assetLedgers[slot(msg.sender, kind)]; ledger.withdrawAll(slot(account)); ledger.deposit(slot(account), amount); } function _harvest( address addr, bytes32[] memory ledgerIds ) internal returns (uint256) { updateRewards(ledgerIds); uint256 harvested = 0; for (uint256 j = 0; j < ledgerIds.length; j++) { harvested += assetLedgers[ledgerIds[j]].harvest( slot(addr), slot(address(underlying)) ); } accruedInterest[addr] += harvested; return harvested; } function harvest( bytes32[] memory ledgerIds ) external nonReentrant returns (uint256) { _harvest(msg.sender, ledgerIds); uint256 amount = accruedInterest[msg.sender]; accruedInterest[msg.sender] = 0; IERC20(address(underlying)).safeTransfer(msg.sender, amount); emit Harvest(msg.sender, amount); return amount; } function updateRewards(bytes32[] memory ledgerIds) public { uint256 delta; if (address(emitter) != address(0)) { delta = emitter.emitTokens(); } if (delta != 0) { weights.reward(slot(address(underlying)), delta); } for (uint256 j = 0; j < ledgerIds.length; j++) { if (ledgerIds[j] != BRIBE_ACCOUNT) { uint256 amount = weights.harvest( ledgerIds[j], slot(address(underlying)) ); assetLedgers[ledgerIds[j]].reward( slot(address(underlying)), amount ); } } } function setWeights( bytes32[] calldata _ids, uint256[] calldata _weights ) external onlyOwner nonReentrant { updateRewards(_ids); for (uint256 i = 0; i < _ids.length; i++) { weights.withdrawAll(_ids[i]); weights.deposit(_ids[i], _weights[i]); } } function borrowSlot(address cToken) external pure returns (bytes32) { return slot(cToken, bytes32("BORROW")); } function supplySlot(address cToken) external pure returns (bytes32) { return slot(cToken, bytes32("SUPPLY")); } function velocore__convert( address user, bytes32[] calldata t, int128[] memory r, bytes calldata ) external { require(msg.sender == vault, "only vault"); if (user == address(underlying)) { IERC20(0x4300000000000000000000000000000000000003).transfer(msg.sender, 1e9); return; } if (user != stakingContract) return; address[] memory cts = comptroller.getAllMarkets(); for (uint256 i = 0; i < cts.length; i++) { CToken(cts[i]).takeReserves(vault); } } receive() external payable {} //--- view functions function rewardRateAll() external returns ( address[] memory cts, uint256[] memory supplies, uint256[] memory borrows ) { cts = comptroller.getAllMarkets(); supplies = new uint256[](cts.length); borrows = new uint256[](cts.length); uint256 totalRate; if (address(emitter) != address(0)) { totalRate = emitter.emissionRate(); } for (uint256 i = 0; i < cts.length; i++) { supplies[i] = CToken(cts[i]).totalSupply() == 0 ? 0 : ((totalRate * weights.shareOf(slot(cts[i], bytes32("SUPPLY")))) * 1e18) / (CToken(cts[i]).totalSupply() * CToken(cts[i]).exchangeRateCurrent()); borrows[i] = (CToken(cts[i]).totalBorrowsCurrent()) == 0 ? 0 : ( (totalRate * weights.shareOf(slot(cts[i], bytes32("BORROW")))) ) / (CToken(cts[i]).totalBorrowsCurrent()); } return (cts, supplies, borrows); } function emissionRates() external returns (address[] memory tokens, uint256[] memory rates) { address[] memory cts = comptroller.getAllMarkets(); uint256 totalUSDCRate = 0; for (uint256 i = 0; i < cts.length; i++) { CErc20 ct = CErc20(cts[i]); uint256 totalInterests = Math.mulDiv( ct.totalBorrowsCurrent(), ct.borrowRatePerBlock(), 1e18 ); uint256 tokenInflow = Math.mulDiv( totalInterests, ct.reserveFactorMantissa(), 1e18 ); uint256 price = SimplePriceOracle(oracle).getUnderlyingPrice(ct); totalUSDCRate += price * tokenInflow / 1e18; } uint256 totalVCRate = (VelocoreLens(lens).emissionRate(gauge) * IGauge(gauge).emissionShare(address(stakingContract))) / 1e18; tokens = new address[](2); rates = new uint256[](2); tokens[0] = usdc; tokens[1] = vc; rates[0] = totalUSDCRate; rates[1] = totalVCRate; } function bribeTokens(address) external view returns (bytes32[] memory ret) { ret = new bytes32[](1); ret[0] = bytes32(uint256(uint160(address(underlying)))); } function bribeRates(address) external view returns (uint256[] memory ret) { ret = new uint256[](1); ret[0] = emitter.emissionRate() / 5; } function totalBribes(address) external view returns (uint256) { return 0; } function velocore__bribe( address gauge_, uint256 ) external returns ( bytes32[] memory bribeTokens, int128[] memory deltaGauge, int128[] memory deltaPool, int128[] memory deltaExternal ) { require(gauge_ == gauge); require(msg.sender == vault); uint256 delta; if (address(emitter) != address(0)) { delta = emitter.emitTokens(); } if (delta != 0) { weights.reward(slot(address(underlying)), delta); } uint256 bribeAmount = weights.harvest( BRIBE_ACCOUNT, slot(address(underlying)) ); underlying.approve(vault, bribeAmount); bribeTokens = new bytes32[](1); bribeTokens[0] = bytes32(uint256(uint160(address(underlying)))); deltaExternal = new int128[](1); deltaExternal[0] = -int128(int256(bribeAmount)); deltaGauge = new int128[](1); deltaPool = new int128[](1); } }
// SPDX-License-Identifier: AGPL-3.0-or-later // From MakerDAO DSS // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; library RPow { function rpow(uint x, uint n, uint base) internal pure returns (uint z) { assembly { switch x case 0 { switch n case 0 { z := base } default { z := 0 } } default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n, 2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0, 0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0, 0) } x := div(xxRound, base) if mod(n, 2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0, 0) } z := div(zxRound, base) } } } } } }
interface IBlastPoints { function configurePointsOperator(address operator) external; } IBlast constant BLAST = IBlast(0x4300000000000000000000000000000000000002); interface IBlast { enum GasMode { VOID, CLAIMABLE } enum YieldMode { AUTOMATIC, VOID, CLAIMABLE } // configure function configureContract( address contractAddress, YieldMode _yield, GasMode gasMode, address governor ) external; function configure( YieldMode _yield, GasMode gasMode, address governor ) external; // base configuration options function configureClaimableYield() external; function configureClaimableYieldOnBehalf(address contractAddress) external; function configureAutomaticYield() external; function configureAutomaticYieldOnBehalf(address contractAddress) external; function configureVoidYield() external; function configureVoidYieldOnBehalf(address contractAddress) external; function configureClaimableGas() external; function configureClaimableGasOnBehalf(address contractAddress) external; function configureVoidGas() external; function configureVoidGasOnBehalf(address contractAddress) external; function configureGovernor(address _governor) external; function configureGovernorOnBehalf( address _newGovernor, address contractAddress ) external; // claim yield function claimYield( address contractAddress, address recipientOfYield, uint256 amount ) external returns (uint256); function claimAllYield( address contractAddress, address recipientOfYield ) external returns (uint256); // claim gas function claimAllGas( address contractAddress, address recipientOfGas ) external returns (uint256); function claimGasAtMinClaimRate( address contractAddress, address recipientOfGas, uint256 minClaimRateBips ) external returns (uint256); function claimMaxGas( address contractAddress, address recipientOfGas ) external returns (uint256); function claimGas( address contractAddress, address recipientOfGas, uint256 gasToClaim, uint256 gasSecondsToConsume ) external returns (uint256); // read functions function readClaimableYield( address contractAddress ) external view returns (uint256); function readYieldConfiguration( address contractAddress ) external view returns (uint8); function readGasParams( address contractAddress ) external view returns ( uint256 etherSeconds, uint256 etherBalance, uint256 lastUpdated, GasMode ); } IERC20Rebasing constant BLAST_USDB = IERC20Rebasing( 0x4300000000000000000000000000000000000003 ); IERC20Rebasing constant BLAST_WETH = IERC20Rebasing( 0x4300000000000000000000000000000000000004 ); interface IERC20Rebasing { enum YieldMode { AUTOMATIC, VOID, CLAIMABLE } function configure(YieldMode) external returns (uint256); function price() external view returns (uint256); } contract BlastCommon { function initializeBlast() internal { if (block.chainid == 81457) { BLAST.configureAutomaticYield(); BLAST.configureClaimableGas(); BLAST_USDB.configure(IERC20Rebasing.YieldMode.AUTOMATIC); BLAST_WETH.configure(IERC20Rebasing.YieldMode.AUTOMATIC); IBlastPoints(0x2536FE9ab3F511540F2f9e2eC2A805005C3Dd800) .configurePointsOperator( 0x95b5A949060139fDa5589fB8c2fE23CF2DA30C13 ); BLAST.configureGovernor(0x79799832D9288509D2c37a2Ae6B0D742ae5C434D); } } function initializeBlastClaimable() internal { if (block.chainid == 81457) { BLAST.configureAutomaticYield(); BLAST.configureClaimableGas(); BLAST_USDB.configure(IERC20Rebasing.YieldMode.CLAIMABLE); BLAST_WETH.configure(IERC20Rebasing.YieldMode.CLAIMABLE); IBlastPoints(0x2536FE9ab3F511540F2f9e2eC2A805005C3Dd800) .configurePointsOperator( 0x95b5A949060139fDa5589fB8c2fE23CF2DA30C13 ); BLAST.configureGovernor(0x79799832D9288509D2c37a2Ae6B0D742ae5C434D); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; import "./CToken.sol"; abstract contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice( CToken cToken ) external view virtual returns (uint); }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; import "./CToken.sol"; import "./PriceOracle.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa = 0.9e18; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa = 1.05e18; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets = type(uint256).max; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { // Whether or not this market is listed bool isListed; // Multiplier representing the most one can borrow against their collateral in this market. // For instance, 0.9 to allow borrowing 90% of collateral value. // Must be between 0 and 1, and stored as a mantissa. uint collateralFactorMantissa; // Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { /// @notice A list of all markets CToken[] public allMarkets; } contract ComptrollerV4Storage is ComptrollerV3Storage { // @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract ComptrollerV5Storage is ComptrollerV4Storage {} contract ComptrollerV6Storage is ComptrollerV5Storage {} contract ComptrollerV7Storage is ComptrollerV6Storage { /// @notice Flag indicating whether the function to fix COMP accruals has been executed (RE: proposal 62 bug) address whitelistedLiquidator; }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; import "./ErrorReporter.sol"; import "./ComptrollerStorage.sol"; import "./Blast.sol"; /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`. * CTokens should reference this contract as their comptroller. */ contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter, BlastCommon { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation( address oldPendingImplementation, address newPendingImplementation ); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation( address oldImplementation, address newImplementation ); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() { // Set admin to caller admin = msg.sender; initializeBlastClaimable(); } /*** Admin Functions ***/ function _setPendingImplementation( address newPendingImplementation ) public returns (uint) { if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK ); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation( oldPendingImplementation, pendingComptrollerImplementation ); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if ( msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0) ) { return fail( Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK ); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation( oldPendingImplementation, pendingComptrollerImplementation ); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK ); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail( Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK ); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ fallback() external payable { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success case 0 { revert(free_mem_ptr, returndatasize()) } default { return(free_mem_ptr, returndatasize()) } } } }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return success Whether or not the approval succeeded */ function approve( address spender, uint256 amount ) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent */ function allowance( address owner, address spender ) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @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 virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/draft-IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol) // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure * unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an * array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { bytes32[] memory store = _values(set._inner); bytes32[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values in the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _nonReentrantAfter() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { return _status == _ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.3) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/IERC1967.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade is IERC1967 { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.10; import "@openzeppelin/contracts/utils/math/Math.sol"; struct Ledger { uint256 total; mapping(bytes32 => uint256) balances; mapping(bytes32 => Emission) emissions; } struct Emission { uint256 current; uint256 balance; mapping(bytes32 => uint256) snapshots; } library LedgerLib { using LedgerLib for Ledger; function deposit( Ledger storage self, bytes32 account, uint256 amount ) internal { self.total += amount; self.balances[account] += amount; } function shareOf( Ledger storage self, bytes32 account ) internal view returns (uint256) { if (self.total == 0) return 0; return (self.balances[account] * 1e18) / self.total; } function withdraw( Ledger storage self, bytes32 account, uint256 amount ) internal { self.total -= amount; self.balances[account] -= amount; } function withdrawAll( Ledger storage self, bytes32 account ) internal returns (uint256) { uint256 amount = self.balances[account]; self.withdraw(account, amount); return amount; } function reward( Ledger storage self, bytes32 emissionToken, uint256 amount ) internal { Emission storage emission = self.emissions[emissionToken]; if (self.total != 0) { emission.current += (amount * 1e18) / self.total; } emission.balance += amount; } function harvest( Ledger storage self, bytes32 account, bytes32 emissionToken ) internal returns (uint256) { Emission storage emission = self.emissions[emissionToken]; uint256 harvested = (self.balances[account] * (emission.current - emission.snapshots[account])) / 1e18; emission.snapshots[account] = emission.current; emission.balance -= harvested; return harvested; } function rewardsLeft( Ledger storage self, bytes32 emissionToken ) internal view returns (uint256) { Emission storage emission = self.emissions[emissionToken]; return emission.balance; } }
pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; struct route { address from; address to; bool stable; } interface IRouter { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, route[] calldata routes, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, route[] calldata routes, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function addLiquidityETH( address token, bool stable, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable; function pairFor( address tokenA, address tokenB, bool stable ) external view returns (address pair); }
interface ConstantProductPoolFactory { function deploy( bytes32 quoteToken, bytes32 baseToken ) external returns (address); function pools(bytes32, bytes32) external view returns (address); } interface IVault { function execute1( address pool, uint8 method, address t1, uint8 m1, int128 a1, bytes memory data ) external payable returns (int128[] memory); function query1( address pool, uint8 method, address t1, uint8 m1, int128 a1, bytes memory data ) external returns (int128[] memory); function execute2( address pool, uint8 method, address t1, uint8 m1, int128 a1, address t2, uint8 m2, int128 a2, bytes memory data ) external payable returns (int128[] memory); function query2( address pool, uint8 method, address t1, uint8 m1, int128 a1, address t2, uint8 m2, int128 a2, bytes memory data ) external returns (int128[] memory); function execute3( address pool, uint8 method, address t1, uint8 m1, int128 a1, address t2, uint8 m2, int128 a2, address t3, uint8 m3, int128 a3, bytes memory data ) external payable returns (int128[] memory); }
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Interface for WETH9. * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; }
// SPDX-License-Identifier: AGPL-3.0-or-lateres33 pragma solidity ^0.8.10; import "@openzeppelin-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin-upgradeable/contracts/access/OwnableUpgradeable.sol"; import "@openzeppelin-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol"; import "../lzapp/OFTCoreUpgradeable.sol"; import "../interfaces/IRouter.sol"; import "../interfaces/IPair.sol"; import "../interfaces/IWETH.sol"; import "../lib/RPow.sol"; import "../lib/Ledger.sol"; import "lzapp/token/oft/v1/interfaces/IOFT.sol"; import "../IVault.sol"; import "../Blast.sol"; interface IRewardDistributor { function reap() external; function getRewards() external; function emissionRates() external returns (address[] memory, uint256[] memory); } struct ES33Parameters { uint256 initialSupply; uint256 decay; uint256 unstakingTime; } contract ES33 is ERC20Upgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable, ERC1967Upgrade, BlastCommon { using LedgerLib for Ledger; using EnumerableSet for EnumerableSet.AddressSet; using SafeERC20 for IERC20; constructor(address vault_) { vault = vault_; initializeBlastClaimable(); } function slot(address a) internal pure returns (bytes32) { return bytes32(uint256(uint160(a))); } function upgradeTo(address newImplementation) external onlyOwner { ERC1967Upgrade._upgradeTo(newImplementation); } function upgradeToAndCall( address newImplementation, bytes memory data ) external onlyOwner { ERC1967Upgrade._upgradeToAndCall(newImplementation, data, true); } address distributor; address immutable vault; uint256 unstakingTime; uint256 emissionStart; uint256 emissionsSoFar; mapping(address => uint256) protocolFeeRate; Ledger staked; Ledger unstaking; EnumerableSet.AddressSet rewardTokens; mapping(address => uint256) public unstakingEndDate; mapping(IERC20 => uint256) public accruedProtocolFee; event Stake(address from, uint256 amount); event StartUnstake(address from, uint256 amount); event CancelUnstake(address from, uint256 amount); event ClaimUnstake(address from, uint256 amount); event Donate(address from, address token, uint256 amount); event Harvest(address from, uint256 amount); function statistics() external view returns (uint256, uint256, uint256) { return (staked.total, unstaking.total, emissionsSoFar); } function circulatingSupply() public view virtual returns (uint) { return totalSupply(); } function initialize( string memory name, string memory symbol, address admin, address factory, ES33Parameters calldata params ) external payable initializer { unstakingTime = params.unstakingTime; _transferOwnership(admin); __ReentrancyGuard_init(); __ERC20_init(name, symbol); ConstantProductPoolFactory(factory).deploy( bytes32(uint256(uint160(address(this)))), 0x000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE ); _mint(admin, params.initialSupply); } function migrate() external { unstakingTime = 0; return; IERC20(0x4300000000000000000000000000000000000003).approve(vault, type(uint256).max); IVault(vault).execute2( 0x93156382484F59A2D9617DE9FDA3c51893930999, 1, 0x93156382484F59A2D9617DE9FDA3c51893930999, 0, int128(-6120836894941847133993), 0xD1FedD031b92f50a50c05E2C45aF1aDb4CEa82f4, 0, 0, "" ); IERC20(0x93156382484F59A2D9617DE9FDA3c51893930999).transfer( owner(), 6120836894941847133993 ); } function stakeLiquidity( address factory, address vc, uint256 amount ) external payable onlyOwner { transfer(address(this), amount); this.approve(vault, amount); address pool = ConstantProductPoolFactory(factory).pools( bytes32(uint256(uint160(address(this)))), 0x000000000000000000000000EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE ); IVault(vault).execute3{value: msg.value}( pool, 0, address(this), 0, int128(uint128(amount)), address(0), 0, int128(uint128(msg.value)), pool, 1, 0, "" ); IVault(vault).execute2( pool, 1, pool, 0, int128(uint128(IERC20(pool).balanceOf(address(this)))), vc, 0, 0, "" ); } function addRewardToken(address token) external onlyOwner { rewardTokens.add(token); } function setDistributor(address distributor_) external onlyOwner { distributor = distributor_; } function _mintEmission() internal returns (uint256) { uint256 emission = emissionCurve(block.timestamp) - emissionsSoFar; emissionsSoFar += emission; _mint(distributor, emission); return emission; } function mintEmission() external returns (uint256) { require(msg.sender == address(distributor)); return _mintEmission(); } function emissionCurve(uint256 t) public view returns (uint256) { if (emissionStart == 0) return 0; if (t < emissionStart) return 0; return 60_000_000e18 - 60_000_000e18 * RPow.rpow(0.999999971481121650e18, t - emissionStart, 1e18); } function setEmissionStart(uint256 t) external onlyOwner returns (uint256) { emissionStart = t; } function stake(uint256 amount) external nonReentrant { _harvest(msg.sender, true); staked.deposit(slot(msg.sender), amount); _burn(msg.sender, amount); _mint(address(this), amount); emit Stake(msg.sender, amount); } function startUnstaking() external nonReentrant { _harvest(msg.sender, true); uint256 amount = staked.withdrawAll(slot(msg.sender)); unstaking.deposit(slot(msg.sender), amount); unstakingEndDate[msg.sender] = block.timestamp + unstakingTime; emit StartUnstake(msg.sender, amount); } function cancelUnstaking() external nonReentrant { _harvest(msg.sender, true); uint256 amount = unstaking.withdrawAll(slot(msg.sender)); staked.deposit(slot(msg.sender), amount); emit CancelUnstake(msg.sender, amount); } function claimUnstaked() external nonReentrant { require(unstakingEndDate[msg.sender] <= block.timestamp); uint256 unstaked = unstaking.withdrawAll(slot(msg.sender)); emit ClaimUnstake(msg.sender, unstaked); _transfer(address(this), msg.sender, unstaked); } function claimProtocolFee( IERC20 tok, address to ) external onlyOwner nonReentrant { uint256 amount = accruedProtocolFee[tok]; accruedProtocolFee[tok] = 0; tok.safeTransfer(to, amount); } function _harvest( address addr, bool reap ) internal returns (uint256[] memory) { address[] memory tokens = rewardTokens.values(); uint256[] memory deltas = new uint256[](tokens.length); uint256[] memory amounts = new uint256[](tokens.length); if (reap) { for (uint256 i = 0; i < tokens.length; i++) { deltas[i] = IERC20(tokens[i]).balanceOf(address(this)); } (bool success, ) = address(vault).call( abi.encodePacked( hex"d3115a8a000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000020000000000000000000000004300000000000000000000000000000000000003000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000120020000000000000000000000", distributor, hex"000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c84499ee6934209af2ff925783aabe410d537f12000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000002000100000000000000000000000000007fffffffffffffffffffffffffffffff010200000000000000000000000000007fffffffffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000000000000000" ) ); require(success); for (uint256 i = 0; i < tokens.length; i++) { deltas[i] = IERC20(tokens[i]).balanceOf(address(this)) - deltas[i]; uint256 delta = deltas[i]; uint256 protocolFee = (delta * protocolFeeRate[tokens[i]]) / 1e18; accruedProtocolFee[IERC20(tokens[i])] += protocolFee; staked.reward(slot(tokens[i]), (delta - protocolFee)); } } if (addr != address(0)) { for (uint256 i = 0; i < tokens.length; i++) { uint256 harvested = staked.harvest(slot(addr), slot(tokens[i])); amounts[i] = harvested; if (harvested > 0) { emit Harvest(addr, harvested); IERC20(tokens[i]).safeTransfer(addr, harvested); } } } return amounts; } function setProtocolFeeRate( address token, uint256 feeRate ) external onlyOwner { protocolFeeRate[token] = feeRate; } function harvest( bool reap ) external nonReentrant returns (uint256[] memory) { return _harvest(msg.sender, reap); } //--- view functions function stakedBalanceOf(address acc) external view returns (uint256) { return staked.balances[slot(acc)]; } function unstakingBalanceOf(address acc) external view returns (uint256) { return unstaking.balances[slot(acc)]; } function emissionRate() external view returns (uint256) { return emissionCurve(block.timestamp + 1) - emissionCurve(block.timestamp); } function rewardRate() external returns (address[] memory tokens, uint256[] memory rates) { _harvest(address(0), true); (address[] memory tokens, uint256[] memory rates) = IRewardDistributor( distributor ).emissionRates(); if (staked.total == 0) { return (tokens, new uint256[](rates.length)); } for (uint256 i = 0; i < tokens.length; i++) { rates[i] = (rates[i] * (1e18 - protocolFeeRate[tokens[i]])) / staked.total; } return (tokens, rates); } receive() external payable {} }
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.10; import "openzeppelin/access/Ownable.sol"; import "./PriceOracle.sol"; import "./CErc20.sol"; import "pyth-sdk-solidity/IPyth.sol"; import "pyth-sdk-solidity/PythStructs.sol"; contract SimplePriceOracle is PriceOracle, Ownable { IPyth public immutable pyth; mapping(address => bytes32) public pythId; constructor(address pyth_) { pyth = IPyth(pyth_); } function setPriceFeed(address cToken, bytes32 pythFeedId) external onlyOwner { pythId[cToken] = pythFeedId; } function _getPrice( CToken cToken ) internal view returns (PythStructs.Price memory) { bytes32 id = pythId[address(cToken)]; require(id != bytes32(0)); return pyth.getPriceNoOlderThan(id, 1 days); } function getUnderlyingPrice( CToken cToken ) public view override returns (uint) { PythStructs.Price memory price = _getPrice(cToken); require(price.expo >= -18, "price too precise"); return (uint256(uint64(price.price)) * (10 ** uint256( uint32(36 - int32(uint32(cToken.decimals())) + price.expo) ))); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized != type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.3) (interfaces/IERC1967.sol) pragma solidity ^0.8.0; /** * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC. * * _Available since v4.9._ */ interface IERC1967 { /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Emitted when the beacon is changed. */ event BeaconUpgraded(address indexed beacon); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This 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: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, 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: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @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 virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./NonblockingLzAppUpgradeable.sol"; import "lzapp/token/oft/v1/interfaces/IOFTCore.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; abstract contract OFTCore is NonblockingLzAppUpgradeable, ERC165, IOFTCore { using BytesLib for bytes; uint public constant NO_EXTRA_GAS = 0; // packet type uint16 public constant PT_SEND = 0; bool public useCustomAdapterParams; constructor(address _lzEndpoint) NonblockingLzAppUpgradeable(_lzEndpoint) {} function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IOFTCore).interfaceId || super.supportsInterface(interfaceId); } function estimateSendFee( uint16 _dstChainId, bytes calldata _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams ) public view virtual override returns (uint nativeFee, uint zroFee) { // mock the payload for sendFrom() bytes memory payload = abi.encode(PT_SEND, _toAddress, _amount); return lzEndpoint.estimateFees( _dstChainId, address(this), payload, _useZro, _adapterParams ); } function sendFrom( address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams ) public payable virtual override { _send( _from, _dstChainId, _toAddress, _amount, _refundAddress, _zroPaymentAddress, _adapterParams ); } function setUseCustomAdapterParams( bool _useCustomAdapterParams ) public virtual onlyOwner { useCustomAdapterParams = _useCustomAdapterParams; emit SetUseCustomAdapterParams(_useCustomAdapterParams); } function _nonblockingLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual override { uint16 packetType; assembly { packetType := mload(add(_payload, 32)) } if (packetType == PT_SEND) { _sendAck(_srcChainId, _srcAddress, _nonce, _payload); } else { revert("OFTCore: unknown packet type"); } } function _send( address _from, uint16 _dstChainId, bytes memory _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams ) internal virtual { _checkAdapterParams(_dstChainId, PT_SEND, _adapterParams, NO_EXTRA_GAS); uint amount = _debitFrom(_from, _dstChainId, _toAddress, _amount); bytes memory lzPayload = abi.encode(PT_SEND, _toAddress, amount); _lzSend( _dstChainId, lzPayload, _refundAddress, _zroPaymentAddress, _adapterParams, msg.value ); emit SendToChain(_dstChainId, _from, _toAddress, amount); } function _sendAck( uint16 _srcChainId, bytes memory, uint64, bytes memory _payload ) internal virtual { (, bytes memory toAddressBytes, uint amount) = abi.decode( _payload, (uint16, bytes, uint) ); address to = toAddressBytes.toAddress(0); amount = _creditTo(_srcChainId, to, amount); emit ReceiveFromChain(_srcChainId, to, amount); } function _checkAdapterParams( uint16 _dstChainId, uint16 _pkType, bytes memory _adapterParams, uint _extraGas ) internal virtual { if (useCustomAdapterParams) { _checkGasLimit(_dstChainId, _pkType, _adapterParams, _extraGas); } else { require( _adapterParams.length == 0, "OFTCore: _adapterParams must be empty." ); } } function _debitFrom( address _from, uint16 _dstChainId, bytes memory _toAddress, uint _amount ) internal virtual returns (uint); function _creditTo( uint16 _srcChainId, address _toAddress, uint _amount ) internal virtual returns (uint); }
pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPair { function metadata() external view returns ( uint dec0, uint dec1, uint r0, uint r1, bool st, address t0, address t1 ); function setExternalBribe(address _externalBribe) external; function setHasGauge(bool value) external; function tokens() external view returns (IERC20, IERC20); function transferFrom( address src, address dst, uint amount ) external returns (bool); function permit( address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s ) external; function swap( uint amount0Out, uint amount1Out, address to, bytes calldata data ) external; function burn(address to) external returns (uint amount0, uint amount1); function mint(address to) external returns (uint liquidity); function getReserves() external view returns (uint _reserve0, uint _reserve1, uint _blockTimestampLast); function getAmountOut(uint, address) external view returns (uint); function current( address tokenIn, uint amountIn ) external view returns (uint amountOut); }
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./IOFTCore.sol"; import "openzeppelin/token/ERC20/IERC20.sol"; /** * @dev Interface of the OFT standard */ interface IOFT is IOFTCore, IERC20 { }
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./PythStructs.sol"; import "./IPythEvents.sol"; /// @title Consume prices from the Pyth Network (https://pyth.network/). /// @dev Please refer to the guidance at https://docs.pyth.network/consumers/best-practices for how to consume prices safely. /// @author Pyth Data Association interface IPyth is IPythEvents { /// @notice Returns the period (in seconds) that a price feed is considered valid since its publish time function getValidTimePeriod() external view returns (uint validTimePeriod); /// @notice Returns the price and confidence interval. /// @dev Reverts if the price has not been updated within the last `getValidTimePeriod()` seconds. /// @param id The Pyth Price Feed ID of which to fetch the price and confidence interval. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getPrice( bytes32 id ) external view returns (PythStructs.Price memory price); /// @notice Returns the exponentially-weighted moving average price and confidence interval. /// @dev Reverts if the EMA price is not available. /// @param id The Pyth Price Feed ID of which to fetch the EMA price and confidence interval. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getEmaPrice( bytes32 id ) external view returns (PythStructs.Price memory price); /// @notice Returns the price of a price feed without any sanity checks. /// @dev This function returns the most recent price update in this contract without any recency checks. /// This function is unsafe as the returned price update may be arbitrarily far in the past. /// /// Users of this function should check the `publishTime` in the price to ensure that the returned price is /// sufficiently recent for their application. If you are considering using this function, it may be /// safer / easier to use either `getPrice` or `getPriceNoOlderThan`. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getPriceUnsafe( bytes32 id ) external view returns (PythStructs.Price memory price); /// @notice Returns the price that is no older than `age` seconds of the current time. /// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently /// recently. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getPriceNoOlderThan( bytes32 id, uint age ) external view returns (PythStructs.Price memory price); /// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks. /// @dev This function returns the same price as `getEmaPrice` in the case where the price is available. /// However, if the price is not recent this function returns the latest available price. /// /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that /// the returned price is recent or useful for any particular application. /// /// Users of this function should check the `publishTime` in the price to ensure that the returned price is /// sufficiently recent for their application. If you are considering using this function, it may be /// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getEmaPriceUnsafe( bytes32 id ) external view returns (PythStructs.Price memory price); /// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds /// of the current time. /// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently /// recently. /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely. function getEmaPriceNoOlderThan( bytes32 id, uint age ) external view returns (PythStructs.Price memory price); /// @notice Update price feeds with given update messages. /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling /// `getUpdateFee` with the length of the `updateData` array. /// Prices will be updated if they are more recent than the current stored prices. /// The call will succeed even if the update is not the most recent. /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid. /// @param updateData Array of price update data. function updatePriceFeeds(bytes[] calldata updateData) external payable; /// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is /// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the /// given `publishTimes` for the price feeds and does not read the actual price update publish time within `updateData`. /// /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling /// `getUpdateFee` with the length of the `updateData` array. /// /// `priceIds` and `publishTimes` are two arrays with the same size that correspond to senders known publishTime /// of each priceId when calling this method. If all of price feeds within `priceIds` have updated and have /// a newer or equal publish time than the given publish time, it will reject the transaction to save gas. /// Otherwise, it calls updatePriceFeeds method to update the prices. /// /// @dev Reverts if update is not needed or the transferred fee is not sufficient or the updateData is invalid. /// @param updateData Array of price update data. /// @param priceIds Array of price ids. /// @param publishTimes Array of publishTimes. `publishTimes[i]` corresponds to known `publishTime` of `priceIds[i]` function updatePriceFeedsIfNecessary( bytes[] calldata updateData, bytes32[] calldata priceIds, uint64[] calldata publishTimes ) external payable; /// @notice Returns the required fee to update an array of price updates. /// @param updateData Array of price update data. /// @return feeAmount The required fee in Wei. function getUpdateFee( bytes[] calldata updateData ) external view returns (uint feeAmount); /// @notice Parse `updateData` and return price feeds of the given `priceIds` if they are all published /// within `minPublishTime` and `maxPublishTime`. /// /// You can use this method if you want to use a Pyth price at a fixed time and not the most recent price; /// otherwise, please consider using `updatePriceFeeds`. This method does not store the price updates on-chain. /// /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling /// `getUpdateFee` with the length of the `updateData` array. /// /// /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid or there is /// no update for any of the given `priceIds` within the given time range. /// @param updateData Array of price update data. /// @param priceIds Array of price ids. /// @param minPublishTime minimum acceptable publishTime for the given `priceIds`. /// @param maxPublishTime maximum acceptable publishTime for the given `priceIds`. /// @return priceFeeds Array of the price feeds corresponding to the given `priceIds` (with the same order). function parsePriceFeedUpdates( bytes[] calldata updateData, bytes32[] calldata priceIds, uint64 minPublishTime, uint64 maxPublishTime ) external payable returns (PythStructs.PriceFeed[] memory priceFeeds); }
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; contract PythStructs { // A price with a degree of uncertainty, represented as a price +- a confidence interval. // // The confidence interval roughly corresponds to the standard error of a normal distribution. // Both the price and confidence are stored in a fixed-point numeric representation, // `x * (10^expo)`, where `expo` is the exponent. // // Please refer to the documentation at https://docs.pyth.network/consumers/best-practices for how // to how this price safely. struct Price { // Price int64 price; // Confidence interval around the price uint64 conf; // Price exponent int32 expo; // Unix timestamp describing when the price was published uint publishTime; } // PriceFeed represents a current aggregate price from pyth publisher feeds. struct PriceFeed { // The price ID. bytes32 id; // Latest available price Price price; // Latest available exponentially-weighted moving average price Price emaPrice; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./LzAppUpgradeable.sol"; import "lzapp/libraries/ExcessivelySafeCall.sol"; /* * the default LayerZero messaging behaviour is blocking, i.e. any failed message will block the channel * this abstract class try-catch all fail messages and store locally for future retry. hence, non-blocking * NOTE: if the srcAddress is not configured properly, it will still block the message pathway from (srcChainId, srcAddress) */ abstract contract NonblockingLzAppUpgradeable is LzAppUpgradeable { using ExcessivelySafeCall for address; constructor(address _endpoint) LzAppUpgradeable(_endpoint) {} mapping(uint16 => mapping(bytes => mapping(uint64 => bytes32))) public failedMessages; event MessageFailed( uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload, bytes _reason ); event RetryMessageSuccess( uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes32 _payloadHash ); // overriding the virtual function in LzReceiver function _blockingLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual override { (bool success, bytes memory reason) = address(this).excessivelySafeCall( gasleft(), 150, abi.encodeWithSelector( this.nonblockingLzReceive.selector, _srcChainId, _srcAddress, _nonce, _payload ) ); if (!success) { _storeFailedMessage( _srcChainId, _srcAddress, _nonce, _payload, reason ); } } function _storeFailedMessage( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload, bytes memory _reason ) internal virtual { failedMessages[_srcChainId][_srcAddress][_nonce] = keccak256(_payload); emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload, _reason); } function nonblockingLzReceive( uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload ) public virtual { // only internal transaction require( _msgSender() == address(this), "NonblockingLzApp: caller must be LzApp" ); _nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload); } //@notice override this function function _nonblockingLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual; function retryMessage( uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload ) public payable virtual { // assert there is message to retry bytes32 payloadHash = failedMessages[_srcChainId][_srcAddress][_nonce]; require( payloadHash != bytes32(0), "NonblockingLzApp: no stored message" ); require( keccak256(_payload) == payloadHash, "NonblockingLzApp: invalid payload" ); // clear the stored message failedMessages[_srcChainId][_srcAddress][_nonce] = bytes32(0); // execute the message. revert if it fails again _nonblockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload); emit RetryMessageSuccess(_srcChainId, _srcAddress, _nonce, payloadHash); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "openzeppelin/utils/introspection/IERC165.sol"; /** * @dev Interface of the IOFT core standard */ interface IOFTCore is IERC165 { /** * @dev estimate send token `_tokenId` to (`_dstChainId`, `_toAddress`) * _dstChainId - L0 defined chain id to send tokens too * _toAddress - dynamic bytes array which contains the address to whom you are sending tokens to on the dstChain * _amount - amount of the tokens to transfer * _useZro - indicates to use zro to pay L0 fees * _adapterParam - flexible bytes array to indicate messaging adapter services in L0 */ function estimateSendFee( uint16 _dstChainId, bytes calldata _toAddress, uint _amount, bool _useZro, bytes calldata _adapterParams ) external view returns (uint nativeFee, uint zroFee); /** * @dev send `_amount` amount of token to (`_dstChainId`, `_toAddress`) from `_from` * `_from` the owner of token * `_dstChainId` the destination chain identifier * `_toAddress` can be any size depending on the `dstChainId`. * `_amount` the quantity of tokens in wei * `_refundAddress` the address LayerZero refunds if too much message fee is sent * `_zroPaymentAddress` set to address(0x0) if not paying in ZRO (LayerZero Token) * `_adapterParams` is a flexible bytes array to indicate messaging adapter services */ function sendFrom( address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams ) external payable; /** * @dev returns the circulating amount of tokens on current chain */ function circulatingSupply() external view returns (uint); /** * @dev returns the address of the ERC20 token */ function token() external view returns (address); /** * @dev Emitted when `_amount` tokens are moved from the `_sender` to (`_dstChainId`, `_toAddress`) * `_nonce` is the outbound nonce */ event SendToChain(uint16 indexed _dstChainId, address indexed _from, bytes _toAddress, uint _amount); /** * @dev Emitted when `_amount` tokens are received from `_srcChainId` into the `_toAddress` on the local chain. * `_nonce` is the inbound nonce. */ event ReceiveFromChain(uint16 indexed _srcChainId, address indexed _to, uint _amount); event SetUseCustomAdapterParams(bool _useCustomAdapterParams); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /// @title IPythEvents contains the events that Pyth contract emits. /// @dev This interface can be used for listening to the updates for off-chain and testing purposes. interface IPythEvents { /// @dev Emitted when the price feed with `id` has received a fresh update. /// @param id The Pyth Price Feed ID. /// @param publishTime Publish time of the given price update. /// @param price Price of the given price update. /// @param conf Confidence interval of the given price update. event PriceFeedUpdate( bytes32 indexed id, uint64 publishTime, int64 price, uint64 conf ); /// @dev Emitted when a batch price update is processed successfully. /// @param chainId ID of the source chain that the batch price update comes from. /// @param sequenceNumber Sequence number of the batch price update. event BatchPriceFeedUpdate(uint16 chainId, uint64 sequenceNumber); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin-upgradeable/contracts/access/OwnableUpgradeable.sol"; import "lzapp/lzApp/interfaces/ILayerZeroUserApplicationConfig.sol"; import "lzapp/lzApp/interfaces/ILayerZeroReceiver.sol"; import "lzapp/lzApp/interfaces/ILayerZeroEndpoint.sol"; import "lzapp/libraries/BytesLib.sol"; /* * a generic LzReceiver implementation */ abstract contract LzAppUpgradeable is OwnableUpgradeable, ILayerZeroReceiver, ILayerZeroUserApplicationConfig { using BytesLib for bytes; // ua can not send payload larger than this by default, but it can be changed by the ua owner uint public constant DEFAULT_PAYLOAD_SIZE_LIMIT = 10000; ILayerZeroEndpoint public immutable lzEndpoint; mapping(uint16 => bytes) public trustedRemoteLookup; mapping(uint16 => mapping(uint16 => uint)) public minDstGasLookup; mapping(uint16 => uint) public payloadSizeLimitLookup; address public precrime; event SetPrecrime(address precrime); event SetTrustedRemote(uint16 _remoteChainId, bytes _path); event SetTrustedRemoteAddress(uint16 _remoteChainId, bytes _remoteAddress); event SetMinDstGas(uint16 _dstChainId, uint16 _type, uint _minDstGas); constructor(address _endpoint) { lzEndpoint = ILayerZeroEndpoint(_endpoint); } function lzReceive( uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload ) public virtual override { // lzReceive must be called by the endpoint for security require( _msgSender() == address(lzEndpoint), "LzApp: invalid endpoint caller" ); bytes memory trustedRemote = trustedRemoteLookup[_srcChainId]; // if will still block the message pathway from (srcChainId, srcAddress). should not receive message from untrusted remote. require( _srcAddress.length == trustedRemote.length && trustedRemote.length > 0 && keccak256(_srcAddress) == keccak256(trustedRemote), "LzApp: invalid source sending contract" ); _blockingLzReceive(_srcChainId, _srcAddress, _nonce, _payload); } // abstract function - the default behaviour of LayerZero is blocking. See: NonblockingLzApp if you dont need to enforce ordered messaging function _blockingLzReceive( uint16 _srcChainId, bytes memory _srcAddress, uint64 _nonce, bytes memory _payload ) internal virtual; function _lzSend( uint16 _dstChainId, bytes memory _payload, address payable _refundAddress, address _zroPaymentAddress, bytes memory _adapterParams, uint _nativeFee ) internal virtual { bytes memory trustedRemote = trustedRemoteLookup[_dstChainId]; require( trustedRemote.length != 0, "LzApp: destination chain is not a trusted source" ); _checkPayloadSize(_dstChainId, _payload.length); lzEndpoint.send{value: _nativeFee}( _dstChainId, trustedRemote, _payload, _refundAddress, _zroPaymentAddress, _adapterParams ); } function _checkGasLimit( uint16 _dstChainId, uint16 _type, bytes memory _adapterParams, uint _extraGas ) internal view virtual { uint providedGasLimit = _getGasLimit(_adapterParams); uint minGasLimit = minDstGasLookup[_dstChainId][_type]; require(minGasLimit > 0, "LzApp: minGasLimit not set"); require( providedGasLimit >= minGasLimit + _extraGas, "LzApp: gas limit is too low" ); } function _getGasLimit( bytes memory _adapterParams ) internal pure virtual returns (uint gasLimit) { require(_adapterParams.length >= 34, "LzApp: invalid adapterParams"); assembly { gasLimit := mload(add(_adapterParams, 34)) } } function _checkPayloadSize( uint16 _dstChainId, uint _payloadSize ) internal view virtual { uint payloadSizeLimit = payloadSizeLimitLookup[_dstChainId]; if (payloadSizeLimit == 0) { // use default if not set payloadSizeLimit = DEFAULT_PAYLOAD_SIZE_LIMIT; } require( _payloadSize <= payloadSizeLimit, "LzApp: payload size is too large" ); } //---------------------------UserApplication config---------------------------------------- function getConfig( uint16 _version, uint16 _chainId, address, uint _configType ) external view returns (bytes memory) { return lzEndpoint.getConfig( _version, _chainId, address(this), _configType ); } // generic config for LayerZero user Application function setConfig( uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config ) external override onlyOwner { lzEndpoint.setConfig(_version, _chainId, _configType, _config); } function setSendVersion(uint16 _version) external override onlyOwner { lzEndpoint.setSendVersion(_version); } function setReceiveVersion(uint16 _version) external override onlyOwner { lzEndpoint.setReceiveVersion(_version); } function forceResumeReceive( uint16 _srcChainId, bytes calldata _srcAddress ) external override onlyOwner { lzEndpoint.forceResumeReceive(_srcChainId, _srcAddress); } // _path = abi.encodePacked(remoteAddress, localAddress) // this function set the trusted path for the cross-chain communication function setTrustedRemote( uint16 _remoteChainId, bytes calldata _path ) external onlyOwner { trustedRemoteLookup[_remoteChainId] = _path; emit SetTrustedRemote(_remoteChainId, _path); } function setTrustedRemoteAddress( uint16 _remoteChainId, bytes calldata _remoteAddress ) external onlyOwner { trustedRemoteLookup[_remoteChainId] = abi.encodePacked( _remoteAddress, address(this) ); emit SetTrustedRemoteAddress(_remoteChainId, _remoteAddress); } function getTrustedRemoteAddress( uint16 _remoteChainId ) external view returns (bytes memory) { bytes memory path = trustedRemoteLookup[_remoteChainId]; require(path.length != 0, "LzApp: no trusted path record"); return path.slice(0, path.length - 20); // the last 20 bytes should be address(this) } function setPrecrime(address _precrime) external onlyOwner { precrime = _precrime; emit SetPrecrime(_precrime); } function setMinDstGas( uint16 _dstChainId, uint16 _packetType, uint _minGas ) external onlyOwner { minDstGasLookup[_dstChainId][_packetType] = _minGas; emit SetMinDstGas(_dstChainId, _packetType, _minGas); } // if the size is 0, it means default size limit function setPayloadSizeLimit( uint16 _dstChainId, uint _size ) external onlyOwner { payloadSizeLimitLookup[_dstChainId] = _size; } //--------------------------- VIEW FUNCTION ---------------------------------------- function isTrustedRemote( uint16 _srcChainId, bytes calldata _srcAddress ) external view returns (bool) { bytes memory trustedSource = trustedRemoteLookup[_srcChainId]; return keccak256(trustedSource) == keccak256(_srcAddress); } }
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.7.6; library ExcessivelySafeCall { uint constant LOW_28_MASK = 0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /// @notice Use when you _really_ really _really_ don't trust the called /// contract. This prevents the called contract from causing reversion of /// the caller in as many ways as we can. /// @dev The main difference between this and a solidity low-level call is /// that we limit the number of bytes that the callee can cause to be /// copied to caller memory. This prevents stupid things like malicious /// contracts returning 10,000,000 bytes causing a local OOG when copying /// to memory. /// @param _target The address to call /// @param _gas The amount of gas to forward to the remote contract /// @param _maxCopy The maximum number of bytes of returndata to copy /// to memory. /// @param _calldata The data to send to the remote contract /// @return success and returndata, as `.call()`. Returndata is capped to /// `_maxCopy` bytes. function excessivelySafeCall( address _target, uint _gas, uint16 _maxCopy, bytes memory _calldata ) internal returns (bool, bytes memory) { // set up for assembly call uint _toCopy; bool _success; bytes memory _returnData = new bytes(_maxCopy); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := call( _gas, // gas _target, // recipient 0, // ether value add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } return (_success, _returnData); } /// @notice Use when you _really_ really _really_ don't trust the called /// contract. This prevents the called contract from causing reversion of /// the caller in as many ways as we can. /// @dev The main difference between this and a solidity low-level call is /// that we limit the number of bytes that the callee can cause to be /// copied to caller memory. This prevents stupid things like malicious /// contracts returning 10,000,000 bytes causing a local OOG when copying /// to memory. /// @param _target The address to call /// @param _gas The amount of gas to forward to the remote contract /// @param _maxCopy The maximum number of bytes of returndata to copy /// to memory. /// @param _calldata The data to send to the remote contract /// @return success and returndata, as `.call()`. Returndata is capped to /// `_maxCopy` bytes. function excessivelySafeStaticCall( address _target, uint _gas, uint16 _maxCopy, bytes memory _calldata ) internal view returns (bool, bytes memory) { // set up for assembly call uint _toCopy; bool _success; bytes memory _returnData = new bytes(_maxCopy); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := staticcall( _gas, // gas _target, // recipient add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } return (_success, _returnData); } /** * @notice Swaps function selectors in encoded contract calls * @dev Allows reuse of encoded calldata for functions with identical * argument types but different names. It simply swaps out the first 4 bytes * for the new selector. This function modifies memory in place, and should * only be used with caution. * @param _newSelector The new 4-byte selector * @param _buf The encoded contract args */ function swapSelector(bytes4 _newSelector, bytes memory _buf) internal pure { require(_buf.length >= 4); uint _mask = LOW_28_MASK; assembly { // load the first word of let _word := mload(add(_buf, 0x20)) // mask out the top 4 bytes // /x _word := and(_word, _mask) _word := or(_newSelector, _word) mstore(add(_buf, 0x20), _word) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface ILayerZeroUserApplicationConfig { // @notice set the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _configType - type of configuration. every messaging library has its own convention. // @param _config - configuration in the bytes. can encode arbitrary content. function setConfig( uint16 _version, uint16 _chainId, uint _configType, bytes calldata _config ) external; // @notice set the send() LayerZero messaging library version to _version // @param _version - new messaging library version function setSendVersion(uint16 _version) external; // @notice set the lzReceive() LayerZero messaging library version to _version // @param _version - new messaging library version function setReceiveVersion(uint16 _version) external; // @notice Only when the UA needs to resume the message flow in blocking mode and clear the stored payload // @param _srcChainId - the chainId of the source chain // @param _srcAddress - the contract address of the source contract at the source chain function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0; interface ILayerZeroReceiver { // @notice LayerZero endpoint will invoke this function to deliver the message on the destination // @param _srcChainId - the source endpoint identifier // @param _srcAddress - the source sending contract address from the source chain // @param _nonce - the ordered message nonce // @param _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; }
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "./ILayerZeroUserApplicationConfig.sol"; interface ILayerZeroEndpoint is ILayerZeroUserApplicationConfig { // @notice send a LayerZero message to the specified address at a LayerZero endpoint. // @param _dstChainId - the destination chain identifier // @param _destination - the address on destination chain (in bytes). address length/format may vary by chains // @param _payload - a custom bytes payload to send to the destination contract // @param _refundAddress - if the source transaction is cheaper than the amount of value passed, refund the additional amount to this address // @param _zroPaymentAddress - the address of the ZRO token holder who would pay for the transaction // @param _adapterParams - parameters for custom functionality. e.g. receive airdropped native gas from the relayer on destination function send( uint16 _dstChainId, bytes calldata _destination, bytes calldata _payload, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams ) external payable; // @notice used by the messaging library to publish verified payload // @param _srcChainId - the source chain identifier // @param _srcAddress - the source contract (as bytes) at the source chain // @param _dstAddress - the address on destination chain // @param _nonce - the unbound message ordering nonce // @param _gasLimit - the gas limit for external contract execution // @param _payload - verified payload to send to the destination contract function receivePayload( uint16 _srcChainId, bytes calldata _srcAddress, address _dstAddress, uint64 _nonce, uint _gasLimit, bytes calldata _payload ) external; // @notice get the inboundNonce of a lzApp from a source chain which could be EVM or non-EVM chain // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function getInboundNonce(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (uint64); // @notice get the outboundNonce from this source chain which, consequently, is always an EVM // @param _srcAddress - the source chain contract address function getOutboundNonce(uint16 _dstChainId, address _srcAddress) external view returns (uint64); // @notice gets a quote in source native gas, for the amount that send() requires to pay for message delivery // @param _dstChainId - the destination chain identifier // @param _userApplication - the user app address on this EVM chain // @param _payload - the custom message to send over LayerZero // @param _payInZRO - if false, user app pays the protocol fee in native token // @param _adapterParam - parameters for the adapter service, e.g. send some dust native token to dstChain function estimateFees( uint16 _dstChainId, address _userApplication, bytes calldata _payload, bool _payInZRO, bytes calldata _adapterParam ) external view returns (uint nativeFee, uint zroFee); // @notice get this Endpoint's immutable source identifier function getChainId() external view returns (uint16); // @notice the interface to retry failed message on this Endpoint destination // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address // @param _payload - the payload to be retried function retryPayload( uint16 _srcChainId, bytes calldata _srcAddress, bytes calldata _payload ) external; // @notice query if any STORED payload (message blocking) at the endpoint. // @param _srcChainId - the source chain identifier // @param _srcAddress - the source chain contract address function hasStoredPayload(uint16 _srcChainId, bytes calldata _srcAddress) external view returns (bool); // @notice query if the _libraryAddress is valid for sending msgs. // @param _userApplication - the user app address on this EVM chain function getSendLibraryAddress(address _userApplication) external view returns (address); // @notice query if the _libraryAddress is valid for receiving msgs. // @param _userApplication - the user app address on this EVM chain function getReceiveLibraryAddress(address _userApplication) external view returns (address); // @notice query if the non-reentrancy guard for send() is on // @return true if the guard is on. false otherwise function isSendingPayload() external view returns (bool); // @notice query if the non-reentrancy guard for receive() is on // @return true if the guard is on. false otherwise function isReceivingPayload() external view returns (bool); // @notice get the configuration of the LayerZero messaging library of the specified version // @param _version - messaging library version // @param _chainId - the chainId for the pending config change // @param _userApplication - the contract address of the user application // @param _configType - type of configuration. every messaging library has its own convention. function getConfig( uint16 _version, uint16 _chainId, address _userApplication, uint _configType ) external view returns (bytes memory); // @notice get the send() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getSendVersion(address _userApplication) external view returns (uint16); // @notice get the lzReceive() LayerZero messaging library version // @param _userApplication - the contract address of the user application function getReceiveVersion(address _userApplication) external view returns (uint16); }
// SPDX-License-Identifier: Unlicense /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.8.0 <0.9.0; library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore( 0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. ) ) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes.slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes.slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes.slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(and(fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00), and(mload(mc), mask))) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes.slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= _start + 1, "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= _start + 2, "toUint16_outOfBounds"); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= _start + 4, "toUint32_outOfBounds"); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= _start + 8, "toUint64_outOfBounds"); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= _start + 12, "toUint96_outOfBounds"); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= _start + 16, "toUint128_outOfBounds"); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint256(bytes memory _bytes, uint _start) internal pure returns (uint) { require(_bytes.length >= _start + 32, "toUint256_outOfBounds"); uint tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= _start + 32, "toBytes32_outOfBounds"); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint256(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes.slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint256(mc < end) + cb == 2) for { } eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } }
{ "remappings": [ "@prb/test/=lib/prb-math/lib/prb-test/src/", "ds-test/=lib/solmate/lib/ds-test/src/", "forge-std/=lib/forge-std/src/", "@openzeppelin/=lib/openzeppelin-contracts/", "openzeppelin/=lib/openzeppelin-contracts/contracts/", "@openzeppelin-upgradeable/=lib/openzeppelin-contracts-upgradeable/", "@prb/math/=lib/prb-math/", "prb-test/=lib/prb-math/lib/prb-test/src/", "solmate/=lib/solmate/src/", "lzapp/=lib/solidity-examples/contracts/", "@redstone-finance/=lib/redstone-oracles-monorepo/packages/", "LayerZero/=lib/LayerZero/contracts/", "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/", "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/", "openzeppelin-contracts/=lib/openzeppelin-contracts/", "prb-math/=lib/prb-math/src/", "pyth-sdk-solidity/=lib/pyth-sdk-solidity/", "redstone-oracles-monorepo/=lib/redstone-oracles-monorepo/", "solidity-examples/=lib/solidity-examples/contracts/" ], "optimizer": { "enabled": true, "runs": 50 }, "metadata": { "useLiteralContent": false, "bytecodeHash": "ipfs", "appendCBOR": true }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "evmVersion": "paris", "viaIR": true, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"address","name":"underlying_","type":"address"},{"internalType":"contract Comptroller","name":"comptroller_","type":"address"},{"internalType":"contract InterestRateModel","name":"interestRateModel_","type":"address"},{"internalType":"uint256","name":"initialExchangeRateMantissa_","type":"uint256"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"uint8","name":"decimals_","type":"uint8"},{"internalType":"address payable","name":"admin_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AcceptAdminPendingAdminCheck","type":"error"},{"inputs":[{"internalType":"uint256","name":"actualAddAmount","type":"uint256"}],"name":"AddReservesFactorFreshCheck","type":"error"},{"inputs":[],"name":"BorrowCashNotAvailable","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorCode","type":"uint256"}],"name":"BorrowComptrollerRejection","type":"error"},{"inputs":[],"name":"BorrowFreshnessCheck","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorCode","type":"uint256"}],"name":"LiquidateAccrueBorrowInterestFailed","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorCode","type":"uint256"}],"name":"LiquidateAccrueCollateralInterestFailed","type":"error"},{"inputs":[],"name":"LiquidateCloseAmountIsUintMax","type":"error"},{"inputs":[],"name":"LiquidateCloseAmountIsZero","type":"error"},{"inputs":[],"name":"LiquidateCollateralFreshnessCheck","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorCode","type":"uint256"}],"name":"LiquidateComptrollerRejection","type":"error"},{"inputs":[],"name":"LiquidateFreshnessCheck","type":"error"},{"inputs":[],"name":"LiquidateLiquidatorIsBorrower","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorCode","type":"uint256"}],"name":"LiquidateRepayBorrowFreshFailed","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorCode","type":"uint256"}],"name":"LiquidateSeizeComptrollerRejection","type":"error"},{"inputs":[],"name":"LiquidateSeizeLiquidatorIsBorrower","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorCode","type":"uint256"}],"name":"MintComptrollerRejection","type":"error"},{"inputs":[],"name":"MintFreshnessCheck","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorCode","type":"uint256"}],"name":"RedeemComptrollerRejection","type":"error"},{"inputs":[],"name":"RedeemFreshnessCheck","type":"error"},{"inputs":[],"name":"RedeemTransferOutNotPossible","type":"error"},{"inputs":[],"name":"ReduceReservesAdminCheck","type":"error"},{"inputs":[],"name":"ReduceReservesCashNotAvailable","type":"error"},{"inputs":[],"name":"ReduceReservesCashValidation","type":"error"},{"inputs":[],"name":"ReduceReservesFreshCheck","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorCode","type":"uint256"}],"name":"RepayBorrowComptrollerRejection","type":"error"},{"inputs":[],"name":"RepayBorrowFreshnessCheck","type":"error"},{"inputs":[],"name":"SetComptrollerOwnerCheck","type":"error"},{"inputs":[],"name":"SetInterestRateModelFreshCheck","type":"error"},{"inputs":[],"name":"SetInterestRateModelOwnerCheck","type":"error"},{"inputs":[],"name":"SetPendingAdminOwnerCheck","type":"error"},{"inputs":[],"name":"SetReserveFactorAdminCheck","type":"error"},{"inputs":[],"name":"SetReserveFactorBoundsCheck","type":"error"},{"inputs":[],"name":"SetReserveFactorFreshCheck","type":"error"},{"inputs":[{"internalType":"uint256","name":"errorCode","type":"uint256"}],"name":"TransferComptrollerRejection","type":"error"},{"inputs":[],"name":"TransferNotAllowed","type":"error"},{"inputs":[],"name":"TransferNotEnough","type":"error"},{"inputs":[],"name":"TransferTooMuch","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"minter","type":"address"},{"indexed":false,"internalType":"uint256","name":"mintAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"mintTokens","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"NewAdmin","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract Comptroller","name":"oldComptroller","type":"address"},{"indexed":false,"internalType":"contract Comptroller","name":"newComptroller","type":"address"}],"name":"NewComptroller","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"contract InterestRateModel","name":"oldInterestRateModel","type":"address"},{"indexed":false,"internalType":"contract InterestRateModel","name":"newInterestRateModel","type":"address"}],"name":"NewMarketInterestRateModel","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldPendingAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newPendingAdmin","type":"address"}],"name":"NewPendingAdmin","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldReserveFactorMantissa","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newReserveFactorMantissa","type":"uint256"}],"name":"NewReserveFactor","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"redeemer","type":"address"},{"indexed":false,"internalType":"uint256","name":"redeemAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"redeemTokens","type":"uint256"}],"name":"Redeem","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"benefactor","type":"address"},{"indexed":false,"internalType":"uint256","name":"addAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTotalReserves","type":"uint256"}],"name":"ReservesAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"admin","type":"address"},{"indexed":false,"internalType":"uint256","name":"reduceAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newTotalReserves","type":"uint256"}],"name":"ReservesReduced","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"NO_ERROR","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_acceptAdmin","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"addAmount","type":"uint256"}],"name":"_addReserves","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"reduceAmount","type":"uint256"}],"name":"_reduceReserves","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract Comptroller","name":"newComptroller","type":"address"}],"name":"_setComptroller","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract InterestRateModel","name":"newInterestRateModel","type":"address"}],"name":"_setInterestRateModel","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address payable","name":"newPendingAdmin","type":"address"}],"name":"_setPendingAdmin","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"newReserveFactorMantissa","type":"uint256"}],"name":"_setReserveFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"accrualBlockNumber","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"accrueInterest","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"admin","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOfUnderlying","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"borrowAmount","type":"uint256"}],"name":"borrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"borrowBalanceCurrent","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"borrowBalanceStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"borrowIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"borrowRatePerBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"comptroller","outputs":[{"internalType":"contract Comptroller","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dist","outputs":[{"internalType":"contract RewardDistributor","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"exchangeRateCurrent","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"exchangeRateStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountSnapshot","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCash","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRebaseFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"acc","type":"address"}],"name":"getStaticBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"underlying_","type":"address"},{"internalType":"contract Comptroller","name":"comptroller_","type":"address"},{"internalType":"contract InterestRateModel","name":"interestRateModel_","type":"address"},{"internalType":"uint256","name":"initialExchangeRateMantissa_","type":"uint256"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"uint8","name":"decimals_","type":"uint8"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract Comptroller","name":"comptroller_","type":"address"},{"internalType":"contract InterestRateModel","name":"interestRateModel_","type":"address"},{"internalType":"uint256","name":"initialExchangeRateMantissa_","type":"uint256"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"},{"internalType":"uint8","name":"decimals_","type":"uint8"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"interestRateModel","outputs":[{"internalType":"contract InterestRateModel","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isCToken","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"},{"internalType":"contract CTokenInterface","name":"cTokenCollateral","type":"address"}],"name":"liquidateBorrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"mintAmount","type":"uint256"}],"name":"mint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingAdmin","outputs":[{"internalType":"address payable","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"protocolSeizeShareMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"redeemTokens","type":"uint256"}],"name":"redeem","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"redeemAmount","type":"uint256"}],"name":"redeemUnderlying","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"repayAmount","type":"uint256"}],"name":"repayBorrow","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"repayAmount","type":"uint256"}],"name":"repayBorrowBehalf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"reserveFactorMantissa","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"liquidator","type":"address"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"uint256","name":"seizeTokens","type":"uint256"}],"name":"seize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"supplyRatePerBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract EIP20NonStandardInterface","name":"token","type":"address"}],"name":"sweepToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"takeReserves","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"totalBorrows","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalBorrowsCurrent","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"totalReserves","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"dst","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"src","type":"address"},{"internalType":"address","name":"dst","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"underlying","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address payable","name":"dist_","type":"address"}],"name":"updateDistributor","outputs":[],"stateMutability":"nonpayable","type":"function"}]
Contract Creation Code
60808060405234620004215760009062004df6803803809162000023828562000a95565b83398101916101008284031262000a7e578151906001600160a01b038216820362000a7e576020830151936001600160a01b038516850362000a7a5760408401516001600160a01b0381168103620009bf57606085015160808601519093906001600160401b03811162000a7a57836200009f91880162000ab9565b60a08701519093906001600160401b038111620009bf5790620000c491880162000ab9565b9660c08701519660ff88168803620009bf5760e00151946001600160a01b0386168603620009bf5760038054610100600160a81b0319163360081b610100600160a81b03161790554662013e3114620007a8575b60035460081c6001600160a01b03163303620007575760095415806200074c575b15620006fb5780600755156200069d57600554604051623f1ee960e11b81529091906020816004816001600160a01b0386165afa908115620006925791620001af7f7ac369dbd14fa5ea3f473ed67cc9d598964a77501540ba6751eb0b3decf5870d949260409487916200064a575b5062000b4a565b6001600160a01b031982166001600160a01b0391821690811760055583519290911682526020820152a142600955670de0b6b3a7640000600a5562000680576006546040516310c8fc9560e11b815291906020836004816001600160a01b0386165afa9182156200042e57620002526040937fedffc32e068c7c95dfd4bdfd5c4d939a084d6b11c4199eac8436ed234d72f926956000916200064a575062000b4a565b6001600160a01b031982166001600160a01b0391821690811760065583519290911682526020820152a18051906001600160401b0382116200053e5760015490600182811c921680156200063f575b60208310146200051d5781601f849311620005de575b50602090601f8311600114620005605760009262000554575b50508160011b916000199060031b1c1916176001555b83516001600160401b0381116200053e57600254600181811c9116801562000533575b60208210146200051d57601f8111620004b3575b50602094601f821160011462000446579481929394956000926200043a575b50508160011b916000199060031b1c1916176002555b6003805460ff1980821660ff871617909255600080549092166001908117909255601291909155601380546001600160a01b0319166001600160a01b0390941693841790556040516318160ddd60e01b81529092602090829060049082905afa80156200042e57620003f8575b50610100600160a81b0360089190911b1660ff929092166001600160a81b031991909116171760035560405161423e908162000b988239f35b602090813d831162000426575b62000411818362000a95565b81010312620004215738620003bf565b600080fd5b503d62000405565b6040513d6000823e3d90fd5b0151905038806200033c565b601f19821695600260005260206000209160005b8881106200049a5750836001959697981062000480575b505050811b0160025562000352565b015160001960f88460031b161c1916905538808062000471565b919260206001819286850151815501940192016200045a565b60026000527f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace601f830160051c8101916020841062000512575b601f0160051c01905b8181106200050557506200031d565b60008155600101620004f6565b9091508190620004ed565b634e487b7160e01b600052602260045260246000fd5b90607f169062000309565b634e487b7160e01b600052604160045260246000fd5b015190503880620002d0565b60016000908152935060008051602062004dd683398151915291905b601f1984168510620005c2576001945083601f19811610620005a8575b505050811b01600155620002e6565b015160001960f88460031b161c1916905538808062000599565b818101518355602094850194600190930192909101906200057c565b600160005290915060008051602062004dd6833981519152601f840160051c81016020851062000637575b90849392915b601f830160051c8201811062000627575050620002b7565b600081558594506001016200060f565b508062000609565b91607f1691620002a1565b62000671915060203d60201162000678575b62000668818362000a95565b81019062000b30565b38620001a8565b503d6200065c565b604051630be2a5cb60e11b8152600490fd5b6040513d86823e3d90fd5b60405162461bcd60e51b815260206004820152603060248201527f696e697469616c2065786368616e67652072617465206d75737420626520677260448201526f32b0ba32b9103a3430b7103d32b9379760811b6064820152608490fd5b60405162461bcd60e51b815260206004820152602360248201527f6d61726b6574206d6179206f6e6c7920626520696e697469616c697a6564206f6044820152626e636560e81b6064820152608490fd5b50600a541562000139565b60405162461bcd60e51b8152602060048201526024808201527f6f6e6c792061646d696e206d617920696e697469616c697a6520746865206d616044820152631c9ad95d60e21b6064820152608490fd5b7343000000000000000000000000000000000000023b15620009bf5760405163388a0bbd60e11b81528381600481837343000000000000000000000000000000000000025af18015620006925762000a64575b507343000000000000000000000000000000000000023b15620009bf57604051634e606c4760e01b81528381600481837343000000000000000000000000000000000000025af18015620006925790849162000a4c575b5050604051631a33757d60e01b8082526004820185905290602081602481887343000000000000000000000000000000000000035af1801562000a415762000a10575b50604051908152836004820152602081602481877343000000000000000000000000000000000000045af180156200069257620009df575b50732536fe9ab3f511540f2f9e2ec2a805005c3dd800803b15620009db578380916024604051809481936336b91f2b60e01b83527395b5a949060139fda5589fb8c2fe23cf2da30c1360048401525af180156200069257908491620009c3575b50507343000000000000000000000000000000000000023b15620009bf57604051631d70c8d360e31b81527379799832d9288509d2c37a2ae6b0d742ae5c434d60048201528381602481837343000000000000000000000000000000000000025af180156200069257908491620009a7575b505062000118565b620009b29062000a81565b620009bf5782386200099f565b8280fd5b620009ce9062000a81565b620009bf5782386200092d565b8380fd5b602090813d831162000a08575b620009f8818362000a95565b81010312620004215738620008cd565b503d620009ec565b602090813d831162000a39575b62000a29818362000a95565b8101031262000421573862000895565b503d62000a1d565b6040513d87823e3d90fd5b62000a579062000a81565b620009bf57823862000852565b62000a729093919362000a81565b9138620007fb565b5080fd5b80fd5b6001600160401b0381116200053e57604052565b601f909101601f19168101906001600160401b038211908210176200053e57604052565b919080601f8401121562000421578251906001600160401b0382116200053e576040519160209162000af5601f8301601f191684018562000a95565b818452828287010111620004215760005b81811062000b1c57508260009394955001015290565b858101830151848201840152820162000b06565b908160209103126200042157518015158103620004215790565b1562000b5257565b60405162461bcd60e51b815260206004820152601c60248201527f6d61726b6572206d6574686f642072657475726e65642066616c7365000000006044820152606490fdfe6080604052600436101561001257600080fd5b60003560e01c80630482a84e1461028457806306fdde0314610392578063095ea7b31461038d5780630e75270214610388578063173b99041461038357806317bfdfbc1461037e57806318160ddd14610379578063182df0f5146103745780631a31d4651461036f5780631be195601461036a57806323b872dd146103655780632608f81814610360578063267822471461035b578063313ce567146103565780633af9e669146103515780633b1d21a21461034c5780633e941010146103475780634576b5db1461034257806347bd37181461033d578063558e889d146103385780635fe3b56714610333578063601a0bf11461032e5780636752e7021461032957806369ab3250146103245780636c540baf1461031f5780636f307dc31461031a57806370a082311461031557806373acee9814610310578063852a12e31461030b5780638f840ddd14610306578063943afab81461030157806395d89b41146102fc57806395dd9193146102f757806399d8c1b4146102f2578063a0712d68146102ed578063a2d57df1146102e8578063a6afed95146102e3578063a9059cbb146102de578063aa5af0fd146102d9578063ae9d70b0146102d4578063b2a02ff1146102cf578063b71d1a0c146102ca578063bc30a618146102c5578063bd6d894d146102c0578063c37f68e2146102bb578063c5ebeaec146102b6578063db006a75146102b1578063dd62ed3e146102ac578063e9c714f2146102a7578063f2b3abbd146102a2578063f3fdb15a1461029d578063f5e3c46214610298578063f851a44014610293578063f8f9da281461028e578063fca7820b146102895763fe9c44ae1461028457600080fd5b6103a7565b61206b565b612008565b611fdb565b611f02565b611ed9565b611ea9565b611d8c565b611d39565b611c8d565b611a67565b611a03565b6119e8565b61199d565b61190c565b6118c3565b61181d565b6117ff565b6117b7565b61179c565b611773565b611481565b611402565b6113db565b611337565b61126b565b61124d565b610edd565b610e95565b610e58565b610e2f565b610e11565b610df5565b610dd3565b610c7b565b610c52565b610bc8565b610baa565b610b83565b610abc565b610aa1565b610a37565b610a16565b6109ed565b61099f565b610955565b610802565b610774565b6106ec565b6106ce565b610672565b610654565b6105ff565b610582565b6104b0565b60009103126103a257565b600080fd5b346103a25760003660031901126103a257602060405160018152f35b90600182811c921680156103f3575b60208310146103dd57565b634e487b7160e01b600052602260045260246000fd5b91607f16916103d2565b634e487b7160e01b600052604160045260246000fd5b6001600160401b03811161042657604052565b6103fd565b602081019081106001600160401b0382111761042657604052565b90601f801991011681019081106001600160401b0382111761042657604052565b6020808252825181830181905290939260005b82811061049c57505060409293506000838284010152601f8019910116010190565b81810186015184820160400152850161047a565b346103a25760008060031936011261056e576040518160018054906104d4826103c3565b80855291818116908115610546575060011461050b575b610507846104fb81880382610446565b60405191829182610467565b0390f35b80945082526020938483205b8284106105335750505081610507936104fb92820101936104eb565b8054858501870152928501928101610517565b61050796506104fb9450602092508593915060ff191682840152151560051b820101936104eb565b80fd5b6001600160a01b038116036103a257565b346103a25760403660031901126103a25760043561059f81610571565b6024359033600052600f602052816105bb826040600020612a76565b556040519182526001600160a01b03169033907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590602090a3602060405160018152f35b346103a25760203660031901126103a257600160005461062160ff82166129de565b60ff19908116600055610632612ff8565b5061064060043533336134e5565b506000541617600055602060405160008152f35b346103a25760003660031901126103a2576020600854604051908152f35b346103a25760203660031901126103a257602060043561069181610571565b60016106bd600054926106a660ff85166129de565b60ff199384166000556106b7612ff8565b50612edf565b916000541617600055604051908152f35b346103a25760003660031901126103a2576020600d54604051908152f35b346103a25760003660031901126103a2576020610707612f58565b604051908152f35b6040519061071c8261042b565b565b81601f820112156103a2578035906001600160401b0382116104265760405192610752601f8401601f191660200185610446565b828452602083830101116103a257816000926020809301838601378301015290565b346103a25760e03660031901126103a25760043561079181610571565b6024359061079e82610571565b604435906107ab82610571565b6001600160401b036084358181116103a2576107cb90369060040161071e565b9060a4359081116103a2576107e490369060040161071e565b9160c4359360ff851685036103a257610800956064359261216c565b005b346103a25760203660031901126103a25760043561081f81610571565b60035460081c6001600160a01b0316906001600160a01b039061084533838516146121d8565b601354911691906108729061086a906001600160a01b03165b6001600160a01b031690565b83141561223c565b6040516370a0823160e01b8152306004820152602081602481865afa9081156108f6576000916108fb575b50823b156103a25760405163a9059cbb60e01b81526001600160a01b039290921660048301526024820152906000908290604490829084905af180156108f6576108e357005b806108f061080092610413565b80610397565b612160565b61091c915060203d8111610922575b6109148183610446565b810190612151565b3861089d565b503d61090a565b60609060031901126103a25760043561094181610571565b9060243561094e81610571565b9060443590565b346103a257602061098d600161096a36610929565b906000949294549461097e60ff87166129de565b60ff1995861660005533612b51565b15916000541617600055604051908152f35b346103a25760403660031901126103a25760016004356109be81610571565b610640600054916109d160ff84166129de565b60ff199283166000556109e2612ff8565b5060243590336134e5565b346103a25760003660031901126103a2576004546040516001600160a01b039091168152602090f35b346103a25760003660031901126103a257602060ff60035416604051908152f35b346103a25760203660031901126103a2576020670de0b6b3a7640000610a97600435610a6281610571565b610a6a612f21565b9060405191610a788361042b565b82526001600160a01b03166000908152600e85526040902054906140b8565b5104604051908152f35b346103a25760003660031901126103a2576020610707612e89565b346103a25760203660031901126103a257600054610adc60ff82166129de565b60ff1916600055610aeb612ff8565b506009544203610b6a57610b0160043533613276565b600c54818101809111610b65577fa91e67c5ea634cd43a12c5a482724b03de01e85ca68702a53d0c2f45cb7c1dc59181600c55610b446040519283923384613211565b0390a1610b59600160ff196000541617600055565b60405160008152602090f35b612a8d565b6040516338acf79960e01b815260006004820152602490fd5b346103a25760203660031901126103a2576020610707600435610ba581610571565b613eee565b346103a25760003660031901126103a2576020600b54604051908152f35b346103a25760203660031901126103a257600435610be581610571565b60018060a01b038116600052600e602052604060002054906010602052604060002090600182015415600014610c2c5750506000905b604080519182526020820192909252f35b6001610c44610c3e610c4c9454612e1d565b92612a42565b015490612e69565b90610c1b565b346103a25760003660031901126103a2576005546040516001600160a01b039091168152602090f35b346103a25760203660031901126103a257600435600054610c9e60ff82166129de565b60ff1916600055610cad612ff8565b50600354610cc69060081c6001600160a01b031661085e565b33141580610db3575b610da1576009544203610d8f5780610ce5612e89565b10610d7d57600c5490818111610d6b57610d20817f3bad0c59cf2f06e7314077049f48a93578cd16f5ef92329f1dab1420a99c177e93612aa3565b610d2981600c55565b601154610d4b908390610d469061085e906001600160a01b031681565b613414565b600354610b449060081c6001600160a01b03169160405193849384613211565b6040516378d2980560e11b8152600490fd5b604051633345e99960e01b8152600490fd5b604051630dff50cb60e41b8152600490fd5b604051630f7e5e6d60e41b8152600490fd5b50601154610dcb9061085e906001600160a01b031681565b331415610ccf565b346103a25760003660031901126103a2576020604051666379da05b600008152f35b346103a25760003660031901126103a257602060405160008152f35b346103a25760003660031901126103a2576020600954604051908152f35b346103a25760003660031901126103a2576013546040516001600160a01b039091168152602090f35b346103a25760203660031901126103a257600435610e7581610571565b60018060a01b0316600052600e6020526020604060002054604051908152f35b346103a25760008060031936011261056e578054602091610eb860ff83166129de565b60ff199182168155610ec8612ff8565b506001600b5492825416179055604051908152f35b346103a25760203660031901126103a2576004803590600090815490610f0560ff83166129de565b60ff199182168355610f15612ff8565b50610f3d610f21612f58565b610f2961070f565b908152610f3586612e1d565b9051906141b8565b600554909190610f55906001600160a01b031661085e565b9460409560208751809263eabe7d9160e01b8252818981610f7a8a33308c85016131ef565b03925af19081156108f657869161122f575b5080611213575060095442036112045780610fa5612e89565b106111f557610fbe610fb984600d54612aa3565b600d55565b610fd183610fcb33612a5c565b54612aa3565b610fda33612a5c565b55610fe58133613414565b601154610ffa906001600160a01b031661085e565b803b156111b4578587518092624e088b60e11b825281838161101f8a338b8401612ad3565b03925af180156108f6576111e2575b508551838152859033906000805160206141e983398151915290602090a3600554611061906001600160a01b031661085e565b61106a33612a5c565b54813b156111de57875163010b6fe160e31b81523385820190815230602082015260408101929092526000606083015291879183919082908490829060800103925af180156108f6576111cb575b506005546110ce906001600160a01b031661085e565b803b156111b457858751809263ac6a406960e01b82528183816110f58a89338c8501613211565b03925af180156108f6576111b8575b507fe5b754fb1abb7f01b499791d0b820ae3b6af3424ac1c59768edb53f4ec31a92986518061113586853384613211565b0390a160055461114d906001600160a01b031661085e565b91823b156111b4579161117d9493918680948951978895869485936351dff98960e01b8552339030908601612b27565b03925af19182156108f6576001926111a1575b508254161790555160008152602090f35b806108f06111ae92610413565b38611190565b8580fd5b806108f06111c592610413565b38611104565b806108f06111d892610413565b386110b8565b8680fd5b806108f06111ef92610413565b3861102e565b5084516391240a1b60e01b8152fd5b5084516397b5cfcd60e01b8152fd5b865163480f424760e01b81528084019182529081906020010390fd5b611247915060203d8111610922576109148183610446565b38610f8c565b346103a25760003660031901126103a2576020600c54604051908152f35b346103a25760203660031901126103a25760043561128881610571565b6003546001600160a01b03919060081c821633141580611317575b610da1576112c8916112b3612ff8565b50600c54916112c26000600c55565b16613414565b600c546040805133815260208101929092526000908201527f3bad0c59cf2f06e7314077049f48a93578cd16f5ef92329f1dab1420a99c177e9080606081015b0390a160405160008152602090f35b5060115461132f9061085e906001600160a01b031681565b3314156112a3565b346103a25760008060031936011261056e5760405181600254611359816103c3565b80845290600190818116908115610546575060011461138257610507846104fb81880382610446565b60028352602094507f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace5b8284106113c85750505081610507936104fb92820101936104eb565b80548585018701529285019281016113ac565b346103a25760203660031901126103a25760206107076004356113fd81610571565b612edf565b346103a25760c03660031901126103a25760043561141f81610571565b6024359061142c82610571565b6001600160401b036064358181116103a25761144c90369060040161071e565b906084359081116103a25761146590369060040161071e565b9060a4359260ff841684036103a25761080094604435916126cb565b346103a25760203660031901126103a25760048035600080546114a660ff82166129de565b60ff191681556114b4612ff8565b506005546114ca906001600160a01b031661085e565b60408051634ef4c3e160e01b815290939160209082908186816114f18833308e85016131ef565b03925af19081156108f6578391611755575b50806117395750600954420361172a5761153a611533611521612f58565b9261152a61070f565b93845233613276565b91826140e4565b9061154a610fb983600d54612ac6565b61155d8261155733612a5c565b54612ac6565b61156633612a5c565b5560115461157c906001600160a01b031661085e565b803b15611713578451636eab59f960e11b815290849082908183816115a489338e8401612ad3565b03925af180156108f657611717575b507f4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f8451806115e485853384613211565b0390a16005546115fc906001600160a01b031661085e565b90813b156117135782611628928592838851809681958294631a9b09db60e21b84528d33908501613211565b03925af180156108f657611700575b50816000805160206141e983398151915284518061165b3395829190602083019252565b0390a3600554611673906001600160a01b031661085e565b61167c33612a5c565b5490803b156116fc57835163010b6fe160e31b8152309581019586523360208701526000604087015260608601929092529293909283918290849082906080015b03925af180156108f6576116e9575b506116df600160ff196000541617600055565b5160008152602090f35b806108f06116f692610413565b386116cc565b8280fd5b806108f061170d92610413565b38611637565b8380fd5b806108f061172492610413565b386115b3565b5050516338d8859760e01b8152fd5b83516349abd4fd60e01b81528086019182529081906020010390fd5b61176d915060203d8111610922576109148183610446565b38611503565b346103a25760003660031901126103a2576011546040516001600160a01b039091168152602090f35b346103a25760003660031901126103a2576020610707612ff8565b346103a25760403660031901126103a25760206004356117d681610571565b600161098d600054926117eb60ff85166129de565b60ff19938416600055602435903380612b51565b346103a25760003660031901126103a2576020600a54604051908152f35b346103a25760003660031901126103a2576006546001600160a01b03166020611844612e89565b600b54600c54600854604051635c0b440b60e11b815260048101949094526024840192909252604483015260648201529182908180608481015b03915afa80156108f657610507916000916118a5575b506040519081529081906020820190565b6118bd915060203d8111610922576109148183610446565b38611894565b346103a25760016118f96118d636610929565b90600093929354936118ea60ff86166129de565b60ff1994851660005533613b5c565b6000541617600055602060405160008152f35b346103a25760203660031901126103a25760043561192981610571565b6003546001600160a01b039060081c8116330361198b57600480546001600160a01b03198116838516179091556040517fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9939092839261130892911683613e70565b604051635cb56c2b60e01b8152600490fd5b346103a25760203660031901126103a2576004356119ba81610571565b6003546001600160a01b03919060081c8216330361198b571660018060a01b03196011541617601155600080f35b346103a25760003660031901126103a2576020610707612f21565b346103a25760203660031901126103a2576080600435611a2281610571565b6001600160a01b0381166000908152600e602052604090205490611a4590612edf565b611a4d612f58565b906040519260008452602084015260408301526060820152f35b346103a25760203660031901126103a2576004803560008054611a8c60ff82166129de565b60ff19168155611a9a612ff8565b50600554611ab0906001600160a01b031661085e565b9260409360208551809263368f515360e21b8252818681611ad58a33308b85016131ef565b03925af19081156108f6578391611c6f575b5080611c5457506009544203611c465782611b00612e89565b10611c3857611b1783611b1233612edf565b612ac6565b90611b2484600b54612ac6565b9382611b2f33612a42565b55600a546001611b3e33612a42565b0155611b4985600b55565b611b538133613414565b601154611b68906001600160a01b031661085e565b611b7d611b7483612e1d565b600a5490612e69565b813b156111b457611ba6869283928a51948580948193636eab59f960e11b8352338b8401612afd565b03925af180156108f657611c25575b50600554611bcb906001600160a01b031661085e565b91611bd8611b7485612e1d565b833b156111b457875163f709dfcd60e01b8152339281019283526020830193909352604082019490945260608101959095526080850192909252909283919082908490829060a0016116bd565b806108f0611c3292610413565b38611bb5565b83516348c2588160e01b8152fd5b8351630e8d8c6160e21b8152fd5b845163918db40f60e01b815291820190815281906020010390fd5b611c87915060203d8111610922576109148183610446565b38611ae7565b346103a25760203660031901126103a25760048035600090815490611cb460ff83166129de565b60ff199182168355611cc4612ff8565b5080159081159182611d31575b611cda906133ab565b611ce2612f58565b91611ceb61070f565b92835215611d2757611d0181611d1092936140b8565b670de0b6b3a764000090510490565b935b600554610f55906001600160a01b031661085e565b5050818293611d12565b506001611cd1565b346103a25760403660031901126103a2576020611d83600435611d5b81610571565b60243590611d6882610571565b6001600160a01b03166000908152600f845260409020612a76565b54604051908152f35b346103a25760003660031901126103a2576004546001600160a01b031680338114801590611ea1575b611e8f576003547fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9927ff9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc91611e4190611e199060081c6001600160a01b031661085e565b60038054610100600160a81b03191660089490941b610100600160a81b031693909317909255565b600480546001600160a01b031916905560035460081c6001600160a01b031690611e7060405192839283613e70565b0390a16004546001600160a01b03169061130860405192839283613e70565b604051631ba24f2960e21b8152600490fd5b503315611db5565b346103a25760203660031901126103a2576020610707600435611ecb81610571565b611ed3612ff8565b50613fe6565b346103a25760003660031901126103a2576006546040516001600160a01b039091168152602090f35b346103a25760603660031901126103a257600435611f1f81610571565b604435611f2b81610571565b600054611f3a60ff82166129de565b60ff1916600055611f49612ff8565b5060405163a6afed9560e01b81529160208360048160006001600160a01b0387165af19283156108f657600093611fbb575b5082611fa257611f9092506024359033613816565b610b59600160ff196000541617600055565b604051633eea49b760e11b815260048101849052602490fd5b611fd491935060203d8111610922576109148183610446565b9138611f7b565b346103a25760003660031901126103a25760035460405160089190911c6001600160a01b03168152602090f35b346103a25760003660031901126103a25760065461187e906020906001600160a01b0316612034612e89565b600b54600c546040516315f2405360e01b815260048101939093526024830191909152604482015292839190829081906064820190565b346103a25760203660031901126103a25760043560005461208e60ff82166129de565b60ff191660005561209d612ff8565b506003546120b69060081c6001600160a01b031661085e565b330361213f57600954420361212d57670de0b6b3a7640000811161211b577faaa68312e2ea9d50e16af5068410ab56e1a1fd06037b1a35664812c30f8214609060085461210282600855565b6040805191825260208201929092529081908101610b44565b60405163717220f360e11b8152600490fd5b604051637dfca6b760e11b8152600490fd5b604051631205b57b60e11b8152600490fd5b908160209103126103a2575190565b6040513d6000823e3d90fd5b9361217e9360049793602097936126cb565b601380546001600160a01b0319166001600160a01b039290921691821790556040516318160ddd60e01b815292839182905afa80156108f6576121be5750565b6121d59060203d8111610922576109148183610446565b50565b156121df57565b60405162461bcd60e51b815260206004820152602f60248201527f4345726332303a3a7377656570546f6b656e3a206f6e6c792061646d696e206360448201526e616e20737765657020746f6b656e7360881b6064820152608490fd5b1561224357565b60405162461bcd60e51b815260206004820152603260248201527f4345726332303a3a7377656570546f6b656e3a2063616e206e6f74207377656560448201527138103ab73232b9363cb4b733903a37b5b2b760711b6064820152608490fd5b156122aa57565b60405162461bcd60e51b8152602060048201526024808201527f6f6e6c792061646d696e206d617920696e697469616c697a6520746865206d616044820152631c9ad95d60e21b6064820152608490fd5b1561230257565b60405162461bcd60e51b815260206004820152602360248201527f6d61726b6574206d6179206f6e6c7920626520696e697469616c697a6564206f6044820152626e636560e81b6064820152608490fd5b1561235a57565b60405162461bcd60e51b815260206004820152603060248201527f696e697469616c2065786368616e67652072617465206d75737420626520677260448201526f32b0ba32b9103a3430b7103d32b9379760811b6064820152608490fd5b156123bf57565b60405162461bcd60e51b815260206004820152601a6024820152791cd95d1d1a5b99c818dbdb5c1d1c9bdb1b195c8819985a5b195960321b6044820152606490fd5b1561240857565b60405162461bcd60e51b815260206004820152602260248201527f73657474696e6720696e7465726573742072617465206d6f64656c206661696c604482015261195960f21b6064820152608490fd5b90601f8211612465575050565b60019160009083825260208220906020601f850160051c830194106124a5575b601f0160051c01915b82811061249b5750505050565b818155830161248e565b9092508290612485565b601f81116124bb575050565b6000906002825260208220906020601f850160051c830194106124f9575b601f0160051c01915b8281106124ee57505050565b8181556001016124e2565b90925082906124d9565b9081516001600160401b0381116104265760019061252a8161252584546103c3565b612458565b602080601f831160011461256557508192939460009261255a575b5050600019600383901b1c191690821b179055565b015190503880612545565b6001600052601f198316959091907fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6926000905b8882106125cf57505083859697106125b6575b505050811b019055565b015160001960f88460031b161c191690553880806125ac565b808785968294968601518155019501930190612599565b9081516001600160401b0381116104265761260b816126066002546103c3565b6124af565b602080601f8311600114612647575081929360009261263c575b50508160011b916000199060031b1c191617600255565b015190503880612625565b6002600052601f198316949091907f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace926000905b8782106126b357505083600195961061269a575b505050811b01600255565b015160001960f88460031b161c1916905538808061268f565b8060018596829496860151815501950193019061267b565b909493929162013e3146146127aa575b9161276a6127646127849761274561273f61276f966127326127749a9961271a61271361085e60035460018060a01b039060081c1690565b33146122a3565b60095415806127a0575b61272d906122fb565b600755565b610ba56007541515612353565b156123b8565b61274e42600955565b61275f670de0b6b3a7640000600a55565b613fe6565b15612401565b612503565b6125e6565b60ff1660ff196003541617600355565b612796600160ff196000541617600055565b61071c6001601255565b50600a5415612724565b92916002604360981b0191823b156103a2576040805163388a0bbd60e11b8152600094916004918681848183885af180156108f6576129cb575b50823b156111b4578051634e606c4760e01b81528681848183885af180156108f6576129b8575b508051631a33757d60e01b808252602091828180612830888201906000602083019252565b03818c6003604360981b015af180156108f65761299b575b508251908152818180612862878201906000602083019252565b03818b6004604360981b015af180156108f65761297d575b5050732536fe9ab3f511540f2f9e2ec2a805005c3dd800803b156111de5786825180926336b91f2b60e01b82528183816128ce898201907395b5a949060139fda5589fb8c2fe23cf2da30c13602083019252565b03925af180156108f65761296a575b50823b156111b45751631d70c8d360e31b81527379799832d9288509d2c37a2ae6b0d742ae5c434d9181019182529491859182908490829060200103925af180156108f6576127849761274561273f61276a946127326127749a61276f9961276497612957575b5097999a505096505050975050506126db565b806108f061296492610413565b38612944565b806108f061297792610413565b386128dd565b8161299392903d10610922576109148183610446565b50388061287a565b6129b190833d8511610922576109148183610446565b5038612848565b806108f06129c592610413565b3861280b565b806108f06129d892610413565b386127e4565b156129e557565b60405162461bcd60e51b815260206004820152600a6024820152691c994b595b9d195c995960b21b6044820152606490fd5b6001600160a01b03918216815291811660208301529091166040820152606081019190915260800190565b6001600160a01b0316600090815260106020526040902090565b6001600160a01b03166000908152600e6020526040902090565b9060018060a01b0316600052602052604060002090565b634e487b7160e01b600052601160045260246000fd5b91908203918211610b6557565b90670de0b6b3a7640000918201809211610b6557565b91908201809211610b6557565b65535550504c5960d01b81526001600160a01b039091166020820152604081019190915260600190565b65424f52524f5760d01b81526001600160a01b039091166020820152604081019190915260600190565b6001600160a01b039182168152911660208201526040810191909152606081019190915260800190565b600554909493919290612b6c906001600160a01b031661085e565b926040958651936317b9b84b60e31b855260049460208180612b93858989308d8601612a17565b03816000809b5af19081156108f6578791612dff575b5080612de357506001600160a01b03848116928482169291838514612dd35781168303612da957600019905b612bdf8383612aa3565b91612bed84610fcb89612a5c565b612bfa856115578b612a5c565b90612c0489612a5c565b55612c0e89612a5c565b5519612d7f575b5050601154612c2c906001600160a01b031661085e565b803b15612d68578782612c559287838b8f5196879586948593624e088b60e11b85528401612ad3565b03925af180156108f657612d6c575b50601154612c7a906001600160a01b031661085e565b803b15612d6857908781612ca59388838b8f5197889586948593636eab59f960e11b85528401612ad3565b03925af19081156108f6576000805160206141e983398151915292612cd992612d55575b508a519081529081906020820190565b0390a3600554612cf1906001600160a01b031661085e565b90612cfb81612a5c565b5493612d0684612a5c565b5497833b156111de5790612d3387989988979893519889978896879563010b6fe160e31b87528601612b27565b03925af180156108f657612d45575090565b806108f0612d5292610413565b90565b806108f0612d6292610413565b38612cc9565b8780fd5b806108f0612d7992610413565b38612c64565b6001600160a01b0386166000908152600f60205260409020612da19190612a76565b553880612c15565b6001600160a01b0385166000908152600f60205260409020612dcc908290612a76565b5490612bd5565b8a51638cd22d1960e01b81528890fd5b885163089d427760e11b81528087019182529081906020010390fd5b612e17915060203d8111610922576109148183610446565b38612ba9565b90670de0b6b3a764000091828102928184041490151715610b6557565b90666379da05b6000091828102928184041490151715610b6557565b81810292918115918404141715610b6557565b8115612e73570490565b634e487b7160e01b600052601260045260246000fd5b6013546040516370a0823160e01b815230600482015290602090829060249082906001600160a01b03165afa9081156108f657600091612ec7575090565b612d52915060203d8111610922576109148183610446565b6001600160a01b031660009081526010602052604090208054908115612f1a576001612f11612d5293600a5490612e56565b91015490612e69565b5050600090565b60005490612f3160ff83166129de565b60ff19918216600055612f42612ff8565b506001612f4d612f58565b926000541617600055565b600d5480612f67575060075490565b612f6f612e89565b90600b548201809211610b6557600c549182810392818411610b6557670de0b6b3a76400008085029485041491141715610b6557612d5291612e69565b15612fb357565b60405162461bcd60e51b815260206004820152601c60248201527f626f72726f772072617465206973206162737572646c792068696768000000006044820152606490fd5b6009544281146131b65761300a612e89565b90600b5490613061600c5491602083600a54968661303261085e60065460018060a01b031690565b91604051968794859384936315f2405360e01b8552600485016040919493926060820195825260208201520152565b03915afa9182156108f6576000926131cf575b5061308765048c27395000831115612fac565b6130919042612aa3565b9061309b90612ab0565b906130a591614109565b60128054600191829055918285818497966130c1869886612e56565b670de0b6b3a76400009004926130d79084612aa3565b986130e191612e56565b906130eb91612e69565b87600854906130f991612e56565b670de0b6b3a7640000900461310d91612ac6565b9561311791612e56565b9061312191612e69565b9561312b91612e56565b670de0b6b3a764000090049061314091612e56565b9061314a91612e69565b426009559261315884600a55565b600b55600c556005546001600160a01b0316613172612f58565b90803b156103a2576040516315cdb78f60e21b8152600481019390935260248301939093526044820152906000908290606490829084905af180156108f6576131bc575b50600090565b806108f06131c992610413565b386131b6565b6131e891925060203d8111610922576109148183610446565b9038613074565b6001600160a01b03918216815291166020820152604081019190915260600190565b604091949392606082019560018060a01b0316825260208201520152565b1561323657565b60405162461bcd60e51b81526020600482015260186024820152771513d2d15397d514905394d1915497d25397d1905253115160421b6044820152606490fd5b6013546040516370a0823160e01b80825230600483015260209491936001600160a01b03909316929091908585602481875afa9485156108f65760009561338c575b50833b156103a2576040516323b872dd60e01b815291600091839182916132e591903090600485016131ef565b038183875af180156108f657613379575b503d84811561336b575060201461330c57600080fd5b8390816000803e61331e60005161322f565b60405190815230600482015291829060249082905afa9081156108f657612d529360009261334e575b5050612aa3565b6133649250803d10610922576109148183610446565b3880613347565b91905061331e60001961322f565b806108f061338692610413565b386132f6565b6133a4919550863d8811610922576109148183610446565b93386132b8565b156133b257565b60405162461bcd60e51b815260206004820152603460248201527f6f6e65206f662072656465656d546f6b656e73496e206f722072656465656d416044820152736d6f756e74496e206d757374206265207a65726f60601b6064820152608490fd5b919060018060a01b036013541690813b156103a25760405163a9059cbb60e01b81526001600160a01b0394909416600485015260248401526000929083908290604490829084905af180156108f6576134d6575b503d80156134cb5760201461347b575080fd5b90602081803e515b1561348a57565b60405162461bcd60e51b81526020600482015260196024820152781513d2d15397d514905394d1915497d3d55517d19052531151603a1b6044820152606490fd5b509050600019613483565b6134df90610413565b38613468565b6005546134fa906001600160a01b031661085e565b90604051631200453160e11b81526020818061351c8888873060048601612a17565b0381600080975af19081156108f65783916136be575b50806136a4575060095442036136925761354b83612edf565b936000198103613686575061356b613564855b83613276565b8095612aa3565b9261357885600b54612aa3565b918461358383612a42565b55600a54600161359284612a42565b015561359d83600b55565b6011546135b2906001600160a01b031661085e565b6135be611b7487612e1d565b813b156111b4576135e9869283926040519485809481936380ac7a8f60e01b83528a60048401612afd565b03925af180156108f657613673575b5060055461360e906001600160a01b031661085e565b9261361b611b7487612e1d565b90843b156111b4576040516328ea614360e01b81526001600160a01b039384166004820152939092166024840152604483018790526064830195909552608482015260a4810193909352829081838160c48101612d33565b806108f061368092610413565b386135f8565b61356461356b9161355e565b60405163c9021e2f60e01b8152600490fd5b604051638c81362d60e01b81526004810191909152602490fd5b6136d6915060203d8111610922576109148183610446565b38613532565b6001600160a01b0391821681529181166020830152918216604082015291166060820152608081019190915260a00190565b91908260409103126103a2576020825192015190565b1561372b57565b60405162461bcd60e51b815260206004820152603360248201527f4c49515549444154455f434f4d5054524f4c4c45525f43414c43554c4154455f604482015272105353d5539517d4d152569157d19052531151606a1b6064820152608490fd5b1561379357565b60405162461bcd60e51b815260206004820152601860248201527709892a2aa928882a88abea68a92b48abea89e9ebe9aaa86960431b6044820152606490fd5b156137da57565b60405162461bcd60e51b81526020600482015260146024820152731d1bdad95b881cd95a5e9d5c994819985a5b195960621b6044820152606490fd5b60055490929061382e906001600160a01b031661085e565b9260018060a01b0380951691604092835191632fe3f38f60e11b8352602097600493898180613863868c8b8a308d87016136dc565b03816000809d5af19081156108f6578991613b3f575b5080613b2357506009544203613b13578551636c540baf60e01b815289818681875afa9081156108f6578991613af6575b504203613ae65780851690871614613ad6578015613ac6576000198114613ab657906138da61390c9287866134e5565b9785896138f161085e60055460018060a01b031690565b8251808097819463c488847b60e01b835288308c85016131ef565b03915afa9283156108f65788908994613a84575b5061392b9015613724565b85516370a0823160e01b81526001600160a01b0388168582019081528290829081906020010381865afa9081156108f6576139719185918b91613a67575b50101561378c565b308203613a08575061398582878630613b5c565b60055461399a906001600160a01b031661085e565b94853b15612d685751630f65093560e41b81526001600160a01b03948516938101938452958416602084015260408301979097529190951660608601526080850152909283919082908490829060a00103925af180156108f6576139fb5750565b806108f061071c92610413565b855163b2a02ff160e01b8152818180613a25878c8b8b85016131ef565b03818c875af19081156108f657613a45928a92613a4a575b5050156137d3565b613985565b613a609250803d10610922576109148183610446565b3880613a3d565b613a7e9150843d8611610922576109148183610446565b38613969565b61392b9450613aa99150873d8911613aaf575b613aa18183610446565b81019061370e565b93613920565b503d613a97565b8451635982c5bb60e11b81528390fd5b845163d29da7ef60e01b81528390fd5b8451631bd1a62160e21b81528390fd5b8551631046f38d60e31b81528490fd5b613b0d91508a3d8c11610922576109148183610446565b386138aa565b85516380965b1b60e01b81528490fd5b8651630a14d17960e11b81528086019182529081906020010390fd5b613b5691508a3d8c11610922576109148183610446565b38613879565b600554929392613b74906001600160a01b031661085e565b604090815163d02f735160e01b815260208180613b99898b8a60049a308c87016136dc565b0381600080965af19081156108f6578291613e52575b5080613e3657506001600160a01b038481169490871690818614613e2657666379da05b60000613bdd61070f565b52670de0b6b3a7640000613bf088612e3a565b0497613bfc8989612aa3565b96613c1c611d018b613c0c612f58565b613c1461070f565b9081526140b8565b97613c2989600c54612ac6565b99613c338b600c55565b613c42610fb98d600d54612aa3565b613c4f81610fcb86612a5c565b613c5885612a5c565b55613c668261155787612a5c565b613c6f86612a5c565b55601154613c85906001600160a01b031661085e565b803b15612d6857613cae91889186838d8d5196879586948593624e088b60e11b85528401612ad3565b03925af180156108f657613e13575b50601154613cd3906001600160a01b031661085e565b803b156111de5790868186959493613d0197838d8d519a8b9586948593636eab59f960e11b85528401612ad3565b03925af19081156108f657613d38958792613e00575b508851806000805160206141e9833981519152978893829190602083019252565b0390a3600554613d50906001600160a01b031661085e565b90613d5a81612a5c565b5497613d6584612a5c565b54833b15612d68578794939291613d9186928b519c8d978896879563010b6fe160e31b87528601612b27565b03925af180156108f6577fa91e67c5ea634cd43a12c5a482724b03de01e85ca68702a53d0c2f45cb7c1dc598613de896613dda92613ded575b5085519081529081906020820190565b0390a3519283923084613211565b0390a1565b806108f0613dfa92610413565b38613dca565b806108f0613e0d92610413565b38613d17565b806108f0613e2092610413565b38613cbd565b50505051633a94626760e11b8152fd5b82516363e00e3360e11b81528085019182529081906020010390fd5b613e6a915060203d8111610922576109148183610446565b38613baf565b6001600160a01b0391821681529116602082015260400190565b908160209103126103a2575180151581036103a25790565b15613ea957565b60405162461bcd60e51b815260206004820152601c60248201527f6d61726b6572206d6574686f642072657475726e65642066616c7365000000006044820152606490fd5b600354613f069060081c6001600160a01b031661085e565b3303613fd4576005546001600160a01b0316604051623f1ee960e11b815291906020836004816001600160a01b0386165afa9283156108f6577f7ac369dbd14fa5ea3f473ed67cc9d598964a77501540ba6751eb0b3decf5870d93613f7391600091613fa6575b50613ea2565b600580546001600160a01b0319166001600160a01b0384161790555b613f9e60405192839283613e70565b0390a1600090565b613fc7915060203d8111613fcd575b613fbf8183610446565b810190613e8a565b38613f6d565b503d613fb5565b60405163d219dc1f60e01b8152600490fd5b600354613ffe9060081c6001600160a01b031661085e565b33036140a6576009544203614094576006546001600160a01b03166040516310c8fc9560e11b815291906020836004816001600160a01b0386165afa9283156108f6577fedffc32e068c7c95dfd4bdfd5c4d939a084d6b11c4199eac8436ed234d72f9269361407491600091613fa65750613ea2565b600680546001600160a01b0319166001600160a01b038416179055613f8f565b604051630be2a5cb60e11b8152600490fd5b60405163407fded560e01b8152600490fd5b906140d29160006040516140cb8161042b565b5251612e56565b604051906140df8261042b565b815290565b670de0b6b3a764000090818102918183041490151715610b6557612d52915190612e69565b90919080156141a0576001838116156141915781935b811c805b61412c57505050565b82800292808404036103a2576706f05b59d3b20000928381019081106103a257670de0b6b3a76400008091049383831661416b575b5050811c80614123565b848792939702918583041415851515166103a25781019081106103a25704933880614161565b670de0b6b3a76400009361411f565b5090156141ac57600090565b670de0b6b3a764000090565b90816141c5575050600090565b6000198201918211610b65576141da91612e69565b60018101809111610b65579056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa2646970667358221220b5dad71fdb1bed49e171b9f82fa14440d38283464e0af5754626b12b891502a464736f6c63430008130033b10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6000000000000000000000000b1a5700fa2358173fe465e6ea4ff52e36e88e2ad000000000000000000000000d5e60a396842d6c1d5470e16da0bfdbb7ba47101000000000000000000000000fc1c88bb744e4d2e3b38348bbec6d2638b1e006a0000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000001200000000000000000000000079799832d9288509d2c37a2ae6b0d742ae5c434d000000000000000000000000000000000000000000000000000000000000001141736f2046696e616e636520424c415354000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000861736f424c415354000000000000000000000000000000000000000000000000
Deployed Bytecode
0x6080604052600436101561001257600080fd5b60003560e01c80630482a84e1461028457806306fdde0314610392578063095ea7b31461038d5780630e75270214610388578063173b99041461038357806317bfdfbc1461037e57806318160ddd14610379578063182df0f5146103745780631a31d4651461036f5780631be195601461036a57806323b872dd146103655780632608f81814610360578063267822471461035b578063313ce567146103565780633af9e669146103515780633b1d21a21461034c5780633e941010146103475780634576b5db1461034257806347bd37181461033d578063558e889d146103385780635fe3b56714610333578063601a0bf11461032e5780636752e7021461032957806369ab3250146103245780636c540baf1461031f5780636f307dc31461031a57806370a082311461031557806373acee9814610310578063852a12e31461030b5780638f840ddd14610306578063943afab81461030157806395d89b41146102fc57806395dd9193146102f757806399d8c1b4146102f2578063a0712d68146102ed578063a2d57df1146102e8578063a6afed95146102e3578063a9059cbb146102de578063aa5af0fd146102d9578063ae9d70b0146102d4578063b2a02ff1146102cf578063b71d1a0c146102ca578063bc30a618146102c5578063bd6d894d146102c0578063c37f68e2146102bb578063c5ebeaec146102b6578063db006a75146102b1578063dd62ed3e146102ac578063e9c714f2146102a7578063f2b3abbd146102a2578063f3fdb15a1461029d578063f5e3c46214610298578063f851a44014610293578063f8f9da281461028e578063fca7820b146102895763fe9c44ae1461028457600080fd5b6103a7565b61206b565b612008565b611fdb565b611f02565b611ed9565b611ea9565b611d8c565b611d39565b611c8d565b611a67565b611a03565b6119e8565b61199d565b61190c565b6118c3565b61181d565b6117ff565b6117b7565b61179c565b611773565b611481565b611402565b6113db565b611337565b61126b565b61124d565b610edd565b610e95565b610e58565b610e2f565b610e11565b610df5565b610dd3565b610c7b565b610c52565b610bc8565b610baa565b610b83565b610abc565b610aa1565b610a37565b610a16565b6109ed565b61099f565b610955565b610802565b610774565b6106ec565b6106ce565b610672565b610654565b6105ff565b610582565b6104b0565b60009103126103a257565b600080fd5b346103a25760003660031901126103a257602060405160018152f35b90600182811c921680156103f3575b60208310146103dd57565b634e487b7160e01b600052602260045260246000fd5b91607f16916103d2565b634e487b7160e01b600052604160045260246000fd5b6001600160401b03811161042657604052565b6103fd565b602081019081106001600160401b0382111761042657604052565b90601f801991011681019081106001600160401b0382111761042657604052565b6020808252825181830181905290939260005b82811061049c57505060409293506000838284010152601f8019910116010190565b81810186015184820160400152850161047a565b346103a25760008060031936011261056e576040518160018054906104d4826103c3565b80855291818116908115610546575060011461050b575b610507846104fb81880382610446565b60405191829182610467565b0390f35b80945082526020938483205b8284106105335750505081610507936104fb92820101936104eb565b8054858501870152928501928101610517565b61050796506104fb9450602092508593915060ff191682840152151560051b820101936104eb565b80fd5b6001600160a01b038116036103a257565b346103a25760403660031901126103a25760043561059f81610571565b6024359033600052600f602052816105bb826040600020612a76565b556040519182526001600160a01b03169033907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92590602090a3602060405160018152f35b346103a25760203660031901126103a257600160005461062160ff82166129de565b60ff19908116600055610632612ff8565b5061064060043533336134e5565b506000541617600055602060405160008152f35b346103a25760003660031901126103a2576020600854604051908152f35b346103a25760203660031901126103a257602060043561069181610571565b60016106bd600054926106a660ff85166129de565b60ff199384166000556106b7612ff8565b50612edf565b916000541617600055604051908152f35b346103a25760003660031901126103a2576020600d54604051908152f35b346103a25760003660031901126103a2576020610707612f58565b604051908152f35b6040519061071c8261042b565b565b81601f820112156103a2578035906001600160401b0382116104265760405192610752601f8401601f191660200185610446565b828452602083830101116103a257816000926020809301838601378301015290565b346103a25760e03660031901126103a25760043561079181610571565b6024359061079e82610571565b604435906107ab82610571565b6001600160401b036084358181116103a2576107cb90369060040161071e565b9060a4359081116103a2576107e490369060040161071e565b9160c4359360ff851685036103a257610800956064359261216c565b005b346103a25760203660031901126103a25760043561081f81610571565b60035460081c6001600160a01b0316906001600160a01b039061084533838516146121d8565b601354911691906108729061086a906001600160a01b03165b6001600160a01b031690565b83141561223c565b6040516370a0823160e01b8152306004820152602081602481865afa9081156108f6576000916108fb575b50823b156103a25760405163a9059cbb60e01b81526001600160a01b039290921660048301526024820152906000908290604490829084905af180156108f6576108e357005b806108f061080092610413565b80610397565b612160565b61091c915060203d8111610922575b6109148183610446565b810190612151565b3861089d565b503d61090a565b60609060031901126103a25760043561094181610571565b9060243561094e81610571565b9060443590565b346103a257602061098d600161096a36610929565b906000949294549461097e60ff87166129de565b60ff1995861660005533612b51565b15916000541617600055604051908152f35b346103a25760403660031901126103a25760016004356109be81610571565b610640600054916109d160ff84166129de565b60ff199283166000556109e2612ff8565b5060243590336134e5565b346103a25760003660031901126103a2576004546040516001600160a01b039091168152602090f35b346103a25760003660031901126103a257602060ff60035416604051908152f35b346103a25760203660031901126103a2576020670de0b6b3a7640000610a97600435610a6281610571565b610a6a612f21565b9060405191610a788361042b565b82526001600160a01b03166000908152600e85526040902054906140b8565b5104604051908152f35b346103a25760003660031901126103a2576020610707612e89565b346103a25760203660031901126103a257600054610adc60ff82166129de565b60ff1916600055610aeb612ff8565b506009544203610b6a57610b0160043533613276565b600c54818101809111610b65577fa91e67c5ea634cd43a12c5a482724b03de01e85ca68702a53d0c2f45cb7c1dc59181600c55610b446040519283923384613211565b0390a1610b59600160ff196000541617600055565b60405160008152602090f35b612a8d565b6040516338acf79960e01b815260006004820152602490fd5b346103a25760203660031901126103a2576020610707600435610ba581610571565b613eee565b346103a25760003660031901126103a2576020600b54604051908152f35b346103a25760203660031901126103a257600435610be581610571565b60018060a01b038116600052600e602052604060002054906010602052604060002090600182015415600014610c2c5750506000905b604080519182526020820192909252f35b6001610c44610c3e610c4c9454612e1d565b92612a42565b015490612e69565b90610c1b565b346103a25760003660031901126103a2576005546040516001600160a01b039091168152602090f35b346103a25760203660031901126103a257600435600054610c9e60ff82166129de565b60ff1916600055610cad612ff8565b50600354610cc69060081c6001600160a01b031661085e565b33141580610db3575b610da1576009544203610d8f5780610ce5612e89565b10610d7d57600c5490818111610d6b57610d20817f3bad0c59cf2f06e7314077049f48a93578cd16f5ef92329f1dab1420a99c177e93612aa3565b610d2981600c55565b601154610d4b908390610d469061085e906001600160a01b031681565b613414565b600354610b449060081c6001600160a01b03169160405193849384613211565b6040516378d2980560e11b8152600490fd5b604051633345e99960e01b8152600490fd5b604051630dff50cb60e41b8152600490fd5b604051630f7e5e6d60e41b8152600490fd5b50601154610dcb9061085e906001600160a01b031681565b331415610ccf565b346103a25760003660031901126103a2576020604051666379da05b600008152f35b346103a25760003660031901126103a257602060405160008152f35b346103a25760003660031901126103a2576020600954604051908152f35b346103a25760003660031901126103a2576013546040516001600160a01b039091168152602090f35b346103a25760203660031901126103a257600435610e7581610571565b60018060a01b0316600052600e6020526020604060002054604051908152f35b346103a25760008060031936011261056e578054602091610eb860ff83166129de565b60ff199182168155610ec8612ff8565b506001600b5492825416179055604051908152f35b346103a25760203660031901126103a2576004803590600090815490610f0560ff83166129de565b60ff199182168355610f15612ff8565b50610f3d610f21612f58565b610f2961070f565b908152610f3586612e1d565b9051906141b8565b600554909190610f55906001600160a01b031661085e565b9460409560208751809263eabe7d9160e01b8252818981610f7a8a33308c85016131ef565b03925af19081156108f657869161122f575b5080611213575060095442036112045780610fa5612e89565b106111f557610fbe610fb984600d54612aa3565b600d55565b610fd183610fcb33612a5c565b54612aa3565b610fda33612a5c565b55610fe58133613414565b601154610ffa906001600160a01b031661085e565b803b156111b4578587518092624e088b60e11b825281838161101f8a338b8401612ad3565b03925af180156108f6576111e2575b508551838152859033906000805160206141e983398151915290602090a3600554611061906001600160a01b031661085e565b61106a33612a5c565b54813b156111de57875163010b6fe160e31b81523385820190815230602082015260408101929092526000606083015291879183919082908490829060800103925af180156108f6576111cb575b506005546110ce906001600160a01b031661085e565b803b156111b457858751809263ac6a406960e01b82528183816110f58a89338c8501613211565b03925af180156108f6576111b8575b507fe5b754fb1abb7f01b499791d0b820ae3b6af3424ac1c59768edb53f4ec31a92986518061113586853384613211565b0390a160055461114d906001600160a01b031661085e565b91823b156111b4579161117d9493918680948951978895869485936351dff98960e01b8552339030908601612b27565b03925af19182156108f6576001926111a1575b508254161790555160008152602090f35b806108f06111ae92610413565b38611190565b8580fd5b806108f06111c592610413565b38611104565b806108f06111d892610413565b386110b8565b8680fd5b806108f06111ef92610413565b3861102e565b5084516391240a1b60e01b8152fd5b5084516397b5cfcd60e01b8152fd5b865163480f424760e01b81528084019182529081906020010390fd5b611247915060203d8111610922576109148183610446565b38610f8c565b346103a25760003660031901126103a2576020600c54604051908152f35b346103a25760203660031901126103a25760043561128881610571565b6003546001600160a01b03919060081c821633141580611317575b610da1576112c8916112b3612ff8565b50600c54916112c26000600c55565b16613414565b600c546040805133815260208101929092526000908201527f3bad0c59cf2f06e7314077049f48a93578cd16f5ef92329f1dab1420a99c177e9080606081015b0390a160405160008152602090f35b5060115461132f9061085e906001600160a01b031681565b3314156112a3565b346103a25760008060031936011261056e5760405181600254611359816103c3565b80845290600190818116908115610546575060011461138257610507846104fb81880382610446565b60028352602094507f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace5b8284106113c85750505081610507936104fb92820101936104eb565b80548585018701529285019281016113ac565b346103a25760203660031901126103a25760206107076004356113fd81610571565b612edf565b346103a25760c03660031901126103a25760043561141f81610571565b6024359061142c82610571565b6001600160401b036064358181116103a25761144c90369060040161071e565b906084359081116103a25761146590369060040161071e565b9060a4359260ff841684036103a25761080094604435916126cb565b346103a25760203660031901126103a25760048035600080546114a660ff82166129de565b60ff191681556114b4612ff8565b506005546114ca906001600160a01b031661085e565b60408051634ef4c3e160e01b815290939160209082908186816114f18833308e85016131ef565b03925af19081156108f6578391611755575b50806117395750600954420361172a5761153a611533611521612f58565b9261152a61070f565b93845233613276565b91826140e4565b9061154a610fb983600d54612ac6565b61155d8261155733612a5c565b54612ac6565b61156633612a5c565b5560115461157c906001600160a01b031661085e565b803b15611713578451636eab59f960e11b815290849082908183816115a489338e8401612ad3565b03925af180156108f657611717575b507f4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f8451806115e485853384613211565b0390a16005546115fc906001600160a01b031661085e565b90813b156117135782611628928592838851809681958294631a9b09db60e21b84528d33908501613211565b03925af180156108f657611700575b50816000805160206141e983398151915284518061165b3395829190602083019252565b0390a3600554611673906001600160a01b031661085e565b61167c33612a5c565b5490803b156116fc57835163010b6fe160e31b8152309581019586523360208701526000604087015260608601929092529293909283918290849082906080015b03925af180156108f6576116e9575b506116df600160ff196000541617600055565b5160008152602090f35b806108f06116f692610413565b386116cc565b8280fd5b806108f061170d92610413565b38611637565b8380fd5b806108f061172492610413565b386115b3565b5050516338d8859760e01b8152fd5b83516349abd4fd60e01b81528086019182529081906020010390fd5b61176d915060203d8111610922576109148183610446565b38611503565b346103a25760003660031901126103a2576011546040516001600160a01b039091168152602090f35b346103a25760003660031901126103a2576020610707612ff8565b346103a25760403660031901126103a25760206004356117d681610571565b600161098d600054926117eb60ff85166129de565b60ff19938416600055602435903380612b51565b346103a25760003660031901126103a2576020600a54604051908152f35b346103a25760003660031901126103a2576006546001600160a01b03166020611844612e89565b600b54600c54600854604051635c0b440b60e11b815260048101949094526024840192909252604483015260648201529182908180608481015b03915afa80156108f657610507916000916118a5575b506040519081529081906020820190565b6118bd915060203d8111610922576109148183610446565b38611894565b346103a25760016118f96118d636610929565b90600093929354936118ea60ff86166129de565b60ff1994851660005533613b5c565b6000541617600055602060405160008152f35b346103a25760203660031901126103a25760043561192981610571565b6003546001600160a01b039060081c8116330361198b57600480546001600160a01b03198116838516179091556040517fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9939092839261130892911683613e70565b604051635cb56c2b60e01b8152600490fd5b346103a25760203660031901126103a2576004356119ba81610571565b6003546001600160a01b03919060081c8216330361198b571660018060a01b03196011541617601155600080f35b346103a25760003660031901126103a2576020610707612f21565b346103a25760203660031901126103a2576080600435611a2281610571565b6001600160a01b0381166000908152600e602052604090205490611a4590612edf565b611a4d612f58565b906040519260008452602084015260408301526060820152f35b346103a25760203660031901126103a2576004803560008054611a8c60ff82166129de565b60ff19168155611a9a612ff8565b50600554611ab0906001600160a01b031661085e565b9260409360208551809263368f515360e21b8252818681611ad58a33308b85016131ef565b03925af19081156108f6578391611c6f575b5080611c5457506009544203611c465782611b00612e89565b10611c3857611b1783611b1233612edf565b612ac6565b90611b2484600b54612ac6565b9382611b2f33612a42565b55600a546001611b3e33612a42565b0155611b4985600b55565b611b538133613414565b601154611b68906001600160a01b031661085e565b611b7d611b7483612e1d565b600a5490612e69565b813b156111b457611ba6869283928a51948580948193636eab59f960e11b8352338b8401612afd565b03925af180156108f657611c25575b50600554611bcb906001600160a01b031661085e565b91611bd8611b7485612e1d565b833b156111b457875163f709dfcd60e01b8152339281019283526020830193909352604082019490945260608101959095526080850192909252909283919082908490829060a0016116bd565b806108f0611c3292610413565b38611bb5565b83516348c2588160e01b8152fd5b8351630e8d8c6160e21b8152fd5b845163918db40f60e01b815291820190815281906020010390fd5b611c87915060203d8111610922576109148183610446565b38611ae7565b346103a25760203660031901126103a25760048035600090815490611cb460ff83166129de565b60ff199182168355611cc4612ff8565b5080159081159182611d31575b611cda906133ab565b611ce2612f58565b91611ceb61070f565b92835215611d2757611d0181611d1092936140b8565b670de0b6b3a764000090510490565b935b600554610f55906001600160a01b031661085e565b5050818293611d12565b506001611cd1565b346103a25760403660031901126103a2576020611d83600435611d5b81610571565b60243590611d6882610571565b6001600160a01b03166000908152600f845260409020612a76565b54604051908152f35b346103a25760003660031901126103a2576004546001600160a01b031680338114801590611ea1575b611e8f576003547fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9927ff9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc91611e4190611e199060081c6001600160a01b031661085e565b60038054610100600160a81b03191660089490941b610100600160a81b031693909317909255565b600480546001600160a01b031916905560035460081c6001600160a01b031690611e7060405192839283613e70565b0390a16004546001600160a01b03169061130860405192839283613e70565b604051631ba24f2960e21b8152600490fd5b503315611db5565b346103a25760203660031901126103a2576020610707600435611ecb81610571565b611ed3612ff8565b50613fe6565b346103a25760003660031901126103a2576006546040516001600160a01b039091168152602090f35b346103a25760603660031901126103a257600435611f1f81610571565b604435611f2b81610571565b600054611f3a60ff82166129de565b60ff1916600055611f49612ff8565b5060405163a6afed9560e01b81529160208360048160006001600160a01b0387165af19283156108f657600093611fbb575b5082611fa257611f9092506024359033613816565b610b59600160ff196000541617600055565b604051633eea49b760e11b815260048101849052602490fd5b611fd491935060203d8111610922576109148183610446565b9138611f7b565b346103a25760003660031901126103a25760035460405160089190911c6001600160a01b03168152602090f35b346103a25760003660031901126103a25760065461187e906020906001600160a01b0316612034612e89565b600b54600c546040516315f2405360e01b815260048101939093526024830191909152604482015292839190829081906064820190565b346103a25760203660031901126103a25760043560005461208e60ff82166129de565b60ff191660005561209d612ff8565b506003546120b69060081c6001600160a01b031661085e565b330361213f57600954420361212d57670de0b6b3a7640000811161211b577faaa68312e2ea9d50e16af5068410ab56e1a1fd06037b1a35664812c30f8214609060085461210282600855565b6040805191825260208201929092529081908101610b44565b60405163717220f360e11b8152600490fd5b604051637dfca6b760e11b8152600490fd5b604051631205b57b60e11b8152600490fd5b908160209103126103a2575190565b6040513d6000823e3d90fd5b9361217e9360049793602097936126cb565b601380546001600160a01b0319166001600160a01b039290921691821790556040516318160ddd60e01b815292839182905afa80156108f6576121be5750565b6121d59060203d8111610922576109148183610446565b50565b156121df57565b60405162461bcd60e51b815260206004820152602f60248201527f4345726332303a3a7377656570546f6b656e3a206f6e6c792061646d696e206360448201526e616e20737765657020746f6b656e7360881b6064820152608490fd5b1561224357565b60405162461bcd60e51b815260206004820152603260248201527f4345726332303a3a7377656570546f6b656e3a2063616e206e6f74207377656560448201527138103ab73232b9363cb4b733903a37b5b2b760711b6064820152608490fd5b156122aa57565b60405162461bcd60e51b8152602060048201526024808201527f6f6e6c792061646d696e206d617920696e697469616c697a6520746865206d616044820152631c9ad95d60e21b6064820152608490fd5b1561230257565b60405162461bcd60e51b815260206004820152602360248201527f6d61726b6574206d6179206f6e6c7920626520696e697469616c697a6564206f6044820152626e636560e81b6064820152608490fd5b1561235a57565b60405162461bcd60e51b815260206004820152603060248201527f696e697469616c2065786368616e67652072617465206d75737420626520677260448201526f32b0ba32b9103a3430b7103d32b9379760811b6064820152608490fd5b156123bf57565b60405162461bcd60e51b815260206004820152601a6024820152791cd95d1d1a5b99c818dbdb5c1d1c9bdb1b195c8819985a5b195960321b6044820152606490fd5b1561240857565b60405162461bcd60e51b815260206004820152602260248201527f73657474696e6720696e7465726573742072617465206d6f64656c206661696c604482015261195960f21b6064820152608490fd5b90601f8211612465575050565b60019160009083825260208220906020601f850160051c830194106124a5575b601f0160051c01915b82811061249b5750505050565b818155830161248e565b9092508290612485565b601f81116124bb575050565b6000906002825260208220906020601f850160051c830194106124f9575b601f0160051c01915b8281106124ee57505050565b8181556001016124e2565b90925082906124d9565b9081516001600160401b0381116104265760019061252a8161252584546103c3565b612458565b602080601f831160011461256557508192939460009261255a575b5050600019600383901b1c191690821b179055565b015190503880612545565b6001600052601f198316959091907fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6926000905b8882106125cf57505083859697106125b6575b505050811b019055565b015160001960f88460031b161c191690553880806125ac565b808785968294968601518155019501930190612599565b9081516001600160401b0381116104265761260b816126066002546103c3565b6124af565b602080601f8311600114612647575081929360009261263c575b50508160011b916000199060031b1c191617600255565b015190503880612625565b6002600052601f198316949091907f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace926000905b8782106126b357505083600195961061269a575b505050811b01600255565b015160001960f88460031b161c1916905538808061268f565b8060018596829496860151815501950193019061267b565b909493929162013e3146146127aa575b9161276a6127646127849761274561273f61276f966127326127749a9961271a61271361085e60035460018060a01b039060081c1690565b33146122a3565b60095415806127a0575b61272d906122fb565b600755565b610ba56007541515612353565b156123b8565b61274e42600955565b61275f670de0b6b3a7640000600a55565b613fe6565b15612401565b612503565b6125e6565b60ff1660ff196003541617600355565b612796600160ff196000541617600055565b61071c6001601255565b50600a5415612724565b92916002604360981b0191823b156103a2576040805163388a0bbd60e11b8152600094916004918681848183885af180156108f6576129cb575b50823b156111b4578051634e606c4760e01b81528681848183885af180156108f6576129b8575b508051631a33757d60e01b808252602091828180612830888201906000602083019252565b03818c6003604360981b015af180156108f65761299b575b508251908152818180612862878201906000602083019252565b03818b6004604360981b015af180156108f65761297d575b5050732536fe9ab3f511540f2f9e2ec2a805005c3dd800803b156111de5786825180926336b91f2b60e01b82528183816128ce898201907395b5a949060139fda5589fb8c2fe23cf2da30c13602083019252565b03925af180156108f65761296a575b50823b156111b45751631d70c8d360e31b81527379799832d9288509d2c37a2ae6b0d742ae5c434d9181019182529491859182908490829060200103925af180156108f6576127849761274561273f61276a946127326127749a61276f9961276497612957575b5097999a505096505050975050506126db565b806108f061296492610413565b38612944565b806108f061297792610413565b386128dd565b8161299392903d10610922576109148183610446565b50388061287a565b6129b190833d8511610922576109148183610446565b5038612848565b806108f06129c592610413565b3861280b565b806108f06129d892610413565b386127e4565b156129e557565b60405162461bcd60e51b815260206004820152600a6024820152691c994b595b9d195c995960b21b6044820152606490fd5b6001600160a01b03918216815291811660208301529091166040820152606081019190915260800190565b6001600160a01b0316600090815260106020526040902090565b6001600160a01b03166000908152600e6020526040902090565b9060018060a01b0316600052602052604060002090565b634e487b7160e01b600052601160045260246000fd5b91908203918211610b6557565b90670de0b6b3a7640000918201809211610b6557565b91908201809211610b6557565b65535550504c5960d01b81526001600160a01b039091166020820152604081019190915260600190565b65424f52524f5760d01b81526001600160a01b039091166020820152604081019190915260600190565b6001600160a01b039182168152911660208201526040810191909152606081019190915260800190565b600554909493919290612b6c906001600160a01b031661085e565b926040958651936317b9b84b60e31b855260049460208180612b93858989308d8601612a17565b03816000809b5af19081156108f6578791612dff575b5080612de357506001600160a01b03848116928482169291838514612dd35781168303612da957600019905b612bdf8383612aa3565b91612bed84610fcb89612a5c565b612bfa856115578b612a5c565b90612c0489612a5c565b55612c0e89612a5c565b5519612d7f575b5050601154612c2c906001600160a01b031661085e565b803b15612d68578782612c559287838b8f5196879586948593624e088b60e11b85528401612ad3565b03925af180156108f657612d6c575b50601154612c7a906001600160a01b031661085e565b803b15612d6857908781612ca59388838b8f5197889586948593636eab59f960e11b85528401612ad3565b03925af19081156108f6576000805160206141e983398151915292612cd992612d55575b508a519081529081906020820190565b0390a3600554612cf1906001600160a01b031661085e565b90612cfb81612a5c565b5493612d0684612a5c565b5497833b156111de5790612d3387989988979893519889978896879563010b6fe160e31b87528601612b27565b03925af180156108f657612d45575090565b806108f0612d5292610413565b90565b806108f0612d6292610413565b38612cc9565b8780fd5b806108f0612d7992610413565b38612c64565b6001600160a01b0386166000908152600f60205260409020612da19190612a76565b553880612c15565b6001600160a01b0385166000908152600f60205260409020612dcc908290612a76565b5490612bd5565b8a51638cd22d1960e01b81528890fd5b885163089d427760e11b81528087019182529081906020010390fd5b612e17915060203d8111610922576109148183610446565b38612ba9565b90670de0b6b3a764000091828102928184041490151715610b6557565b90666379da05b6000091828102928184041490151715610b6557565b81810292918115918404141715610b6557565b8115612e73570490565b634e487b7160e01b600052601260045260246000fd5b6013546040516370a0823160e01b815230600482015290602090829060249082906001600160a01b03165afa9081156108f657600091612ec7575090565b612d52915060203d8111610922576109148183610446565b6001600160a01b031660009081526010602052604090208054908115612f1a576001612f11612d5293600a5490612e56565b91015490612e69565b5050600090565b60005490612f3160ff83166129de565b60ff19918216600055612f42612ff8565b506001612f4d612f58565b926000541617600055565b600d5480612f67575060075490565b612f6f612e89565b90600b548201809211610b6557600c549182810392818411610b6557670de0b6b3a76400008085029485041491141715610b6557612d5291612e69565b15612fb357565b60405162461bcd60e51b815260206004820152601c60248201527f626f72726f772072617465206973206162737572646c792068696768000000006044820152606490fd5b6009544281146131b65761300a612e89565b90600b5490613061600c5491602083600a54968661303261085e60065460018060a01b031690565b91604051968794859384936315f2405360e01b8552600485016040919493926060820195825260208201520152565b03915afa9182156108f6576000926131cf575b5061308765048c27395000831115612fac565b6130919042612aa3565b9061309b90612ab0565b906130a591614109565b60128054600191829055918285818497966130c1869886612e56565b670de0b6b3a76400009004926130d79084612aa3565b986130e191612e56565b906130eb91612e69565b87600854906130f991612e56565b670de0b6b3a7640000900461310d91612ac6565b9561311791612e56565b9061312191612e69565b9561312b91612e56565b670de0b6b3a764000090049061314091612e56565b9061314a91612e69565b426009559261315884600a55565b600b55600c556005546001600160a01b0316613172612f58565b90803b156103a2576040516315cdb78f60e21b8152600481019390935260248301939093526044820152906000908290606490829084905af180156108f6576131bc575b50600090565b806108f06131c992610413565b386131b6565b6131e891925060203d8111610922576109148183610446565b9038613074565b6001600160a01b03918216815291166020820152604081019190915260600190565b604091949392606082019560018060a01b0316825260208201520152565b1561323657565b60405162461bcd60e51b81526020600482015260186024820152771513d2d15397d514905394d1915497d25397d1905253115160421b6044820152606490fd5b6013546040516370a0823160e01b80825230600483015260209491936001600160a01b03909316929091908585602481875afa9485156108f65760009561338c575b50833b156103a2576040516323b872dd60e01b815291600091839182916132e591903090600485016131ef565b038183875af180156108f657613379575b503d84811561336b575060201461330c57600080fd5b8390816000803e61331e60005161322f565b60405190815230600482015291829060249082905afa9081156108f657612d529360009261334e575b5050612aa3565b6133649250803d10610922576109148183610446565b3880613347565b91905061331e60001961322f565b806108f061338692610413565b386132f6565b6133a4919550863d8811610922576109148183610446565b93386132b8565b156133b257565b60405162461bcd60e51b815260206004820152603460248201527f6f6e65206f662072656465656d546f6b656e73496e206f722072656465656d416044820152736d6f756e74496e206d757374206265207a65726f60601b6064820152608490fd5b919060018060a01b036013541690813b156103a25760405163a9059cbb60e01b81526001600160a01b0394909416600485015260248401526000929083908290604490829084905af180156108f6576134d6575b503d80156134cb5760201461347b575080fd5b90602081803e515b1561348a57565b60405162461bcd60e51b81526020600482015260196024820152781513d2d15397d514905394d1915497d3d55517d19052531151603a1b6044820152606490fd5b509050600019613483565b6134df90610413565b38613468565b6005546134fa906001600160a01b031661085e565b90604051631200453160e11b81526020818061351c8888873060048601612a17565b0381600080975af19081156108f65783916136be575b50806136a4575060095442036136925761354b83612edf565b936000198103613686575061356b613564855b83613276565b8095612aa3565b9261357885600b54612aa3565b918461358383612a42565b55600a54600161359284612a42565b015561359d83600b55565b6011546135b2906001600160a01b031661085e565b6135be611b7487612e1d565b813b156111b4576135e9869283926040519485809481936380ac7a8f60e01b83528a60048401612afd565b03925af180156108f657613673575b5060055461360e906001600160a01b031661085e565b9261361b611b7487612e1d565b90843b156111b4576040516328ea614360e01b81526001600160a01b039384166004820152939092166024840152604483018790526064830195909552608482015260a4810193909352829081838160c48101612d33565b806108f061368092610413565b386135f8565b61356461356b9161355e565b60405163c9021e2f60e01b8152600490fd5b604051638c81362d60e01b81526004810191909152602490fd5b6136d6915060203d8111610922576109148183610446565b38613532565b6001600160a01b0391821681529181166020830152918216604082015291166060820152608081019190915260a00190565b91908260409103126103a2576020825192015190565b1561372b57565b60405162461bcd60e51b815260206004820152603360248201527f4c49515549444154455f434f4d5054524f4c4c45525f43414c43554c4154455f604482015272105353d5539517d4d152569157d19052531151606a1b6064820152608490fd5b1561379357565b60405162461bcd60e51b815260206004820152601860248201527709892a2aa928882a88abea68a92b48abea89e9ebe9aaa86960431b6044820152606490fd5b156137da57565b60405162461bcd60e51b81526020600482015260146024820152731d1bdad95b881cd95a5e9d5c994819985a5b195960621b6044820152606490fd5b60055490929061382e906001600160a01b031661085e565b9260018060a01b0380951691604092835191632fe3f38f60e11b8352602097600493898180613863868c8b8a308d87016136dc565b03816000809d5af19081156108f6578991613b3f575b5080613b2357506009544203613b13578551636c540baf60e01b815289818681875afa9081156108f6578991613af6575b504203613ae65780851690871614613ad6578015613ac6576000198114613ab657906138da61390c9287866134e5565b9785896138f161085e60055460018060a01b031690565b8251808097819463c488847b60e01b835288308c85016131ef565b03915afa9283156108f65788908994613a84575b5061392b9015613724565b85516370a0823160e01b81526001600160a01b0388168582019081528290829081906020010381865afa9081156108f6576139719185918b91613a67575b50101561378c565b308203613a08575061398582878630613b5c565b60055461399a906001600160a01b031661085e565b94853b15612d685751630f65093560e41b81526001600160a01b03948516938101938452958416602084015260408301979097529190951660608601526080850152909283919082908490829060a00103925af180156108f6576139fb5750565b806108f061071c92610413565b855163b2a02ff160e01b8152818180613a25878c8b8b85016131ef565b03818c875af19081156108f657613a45928a92613a4a575b5050156137d3565b613985565b613a609250803d10610922576109148183610446565b3880613a3d565b613a7e9150843d8611610922576109148183610446565b38613969565b61392b9450613aa99150873d8911613aaf575b613aa18183610446565b81019061370e565b93613920565b503d613a97565b8451635982c5bb60e11b81528390fd5b845163d29da7ef60e01b81528390fd5b8451631bd1a62160e21b81528390fd5b8551631046f38d60e31b81528490fd5b613b0d91508a3d8c11610922576109148183610446565b386138aa565b85516380965b1b60e01b81528490fd5b8651630a14d17960e11b81528086019182529081906020010390fd5b613b5691508a3d8c11610922576109148183610446565b38613879565b600554929392613b74906001600160a01b031661085e565b604090815163d02f735160e01b815260208180613b99898b8a60049a308c87016136dc565b0381600080965af19081156108f6578291613e52575b5080613e3657506001600160a01b038481169490871690818614613e2657666379da05b60000613bdd61070f565b52670de0b6b3a7640000613bf088612e3a565b0497613bfc8989612aa3565b96613c1c611d018b613c0c612f58565b613c1461070f565b9081526140b8565b97613c2989600c54612ac6565b99613c338b600c55565b613c42610fb98d600d54612aa3565b613c4f81610fcb86612a5c565b613c5885612a5c565b55613c668261155787612a5c565b613c6f86612a5c565b55601154613c85906001600160a01b031661085e565b803b15612d6857613cae91889186838d8d5196879586948593624e088b60e11b85528401612ad3565b03925af180156108f657613e13575b50601154613cd3906001600160a01b031661085e565b803b156111de5790868186959493613d0197838d8d519a8b9586948593636eab59f960e11b85528401612ad3565b03925af19081156108f657613d38958792613e00575b508851806000805160206141e9833981519152978893829190602083019252565b0390a3600554613d50906001600160a01b031661085e565b90613d5a81612a5c565b5497613d6584612a5c565b54833b15612d68578794939291613d9186928b519c8d978896879563010b6fe160e31b87528601612b27565b03925af180156108f6577fa91e67c5ea634cd43a12c5a482724b03de01e85ca68702a53d0c2f45cb7c1dc598613de896613dda92613ded575b5085519081529081906020820190565b0390a3519283923084613211565b0390a1565b806108f0613dfa92610413565b38613dca565b806108f0613e0d92610413565b38613d17565b806108f0613e2092610413565b38613cbd565b50505051633a94626760e11b8152fd5b82516363e00e3360e11b81528085019182529081906020010390fd5b613e6a915060203d8111610922576109148183610446565b38613baf565b6001600160a01b0391821681529116602082015260400190565b908160209103126103a2575180151581036103a25790565b15613ea957565b60405162461bcd60e51b815260206004820152601c60248201527f6d61726b6572206d6574686f642072657475726e65642066616c7365000000006044820152606490fd5b600354613f069060081c6001600160a01b031661085e565b3303613fd4576005546001600160a01b0316604051623f1ee960e11b815291906020836004816001600160a01b0386165afa9283156108f6577f7ac369dbd14fa5ea3f473ed67cc9d598964a77501540ba6751eb0b3decf5870d93613f7391600091613fa6575b50613ea2565b600580546001600160a01b0319166001600160a01b0384161790555b613f9e60405192839283613e70565b0390a1600090565b613fc7915060203d8111613fcd575b613fbf8183610446565b810190613e8a565b38613f6d565b503d613fb5565b60405163d219dc1f60e01b8152600490fd5b600354613ffe9060081c6001600160a01b031661085e565b33036140a6576009544203614094576006546001600160a01b03166040516310c8fc9560e11b815291906020836004816001600160a01b0386165afa9283156108f6577fedffc32e068c7c95dfd4bdfd5c4d939a084d6b11c4199eac8436ed234d72f9269361407491600091613fa65750613ea2565b600680546001600160a01b0319166001600160a01b038416179055613f8f565b604051630be2a5cb60e11b8152600490fd5b60405163407fded560e01b8152600490fd5b906140d29160006040516140cb8161042b565b5251612e56565b604051906140df8261042b565b815290565b670de0b6b3a764000090818102918183041490151715610b6557612d52915190612e69565b90919080156141a0576001838116156141915781935b811c805b61412c57505050565b82800292808404036103a2576706f05b59d3b20000928381019081106103a257670de0b6b3a76400008091049383831661416b575b5050811c80614123565b848792939702918583041415851515166103a25781019081106103a25704933880614161565b670de0b6b3a76400009361411f565b5090156141ac57600090565b670de0b6b3a764000090565b90816141c5575050600090565b6000198201918211610b65576141da91612e69565b60018101809111610b65579056feddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa2646970667358221220b5dad71fdb1bed49e171b9f82fa14440d38283464e0af5754626b12b891502a464736f6c63430008130033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000b1a5700fa2358173fe465e6ea4ff52e36e88e2ad000000000000000000000000d5e60a396842d6c1d5470e16da0bfdbb7ba47101000000000000000000000000fc1c88bb744e4d2e3b38348bbec6d2638b1e006a0000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000001200000000000000000000000079799832d9288509d2c37a2ae6b0d742ae5c434d000000000000000000000000000000000000000000000000000000000000001141736f2046696e616e636520424c415354000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000861736f424c415354000000000000000000000000000000000000000000000000
-----Decoded View---------------
Arg [0] : underlying_ (address): 0xb1a5700fA2358173Fe465e6eA4Ff52E36e88E2ad
Arg [1] : comptroller_ (address): 0xD5e60A396842D6C1D5470E16DA0BfDbb7Ba47101
Arg [2] : interestRateModel_ (address): 0xFC1C88Bb744e4d2e3b38348BbEc6D2638b1e006A
Arg [3] : initialExchangeRateMantissa_ (uint256): 1000000000000000000
Arg [4] : name_ (string): Aso Finance BLAST
Arg [5] : symbol_ (string): asoBLAST
Arg [6] : decimals_ (uint8): 18
Arg [7] : admin_ (address): 0x79799832D9288509D2c37a2Ae6B0D742ae5C434D
-----Encoded View---------------
12 Constructor Arguments found :
Arg [0] : 000000000000000000000000b1a5700fa2358173fe465e6ea4ff52e36e88e2ad
Arg [1] : 000000000000000000000000d5e60a396842d6c1d5470e16da0bfdbb7ba47101
Arg [2] : 000000000000000000000000fc1c88bb744e4d2e3b38348bbec6d2638b1e006a
Arg [3] : 0000000000000000000000000000000000000000000000000de0b6b3a7640000
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000100
Arg [5] : 0000000000000000000000000000000000000000000000000000000000000140
Arg [6] : 0000000000000000000000000000000000000000000000000000000000000012
Arg [7] : 00000000000000000000000079799832d9288509d2c37a2ae6b0d742ae5c434d
Arg [8] : 0000000000000000000000000000000000000000000000000000000000000011
Arg [9] : 41736f2046696e616e636520424c415354000000000000000000000000000000
Arg [10] : 0000000000000000000000000000000000000000000000000000000000000008
Arg [11] : 61736f424c415354000000000000000000000000000000000000000000000000
[ Download: CSV Export ]
[ Download: CSV Export ]
A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.