Source Code
Overview
ETH Balance
0 ETH
ETH Value
$0.00
Cross-Chain Transactions
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Name:
BondToken
Compiler Version
v0.8.30+commit.73712a01
Optimization Enabled:
Yes with 200 runs
Other Settings:
prague EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {Decimals} from "./lib/Decimals.sol";
import {PoolFactory} from "./PoolFactory.sol";
import {Pool} from "./Pool.sol";
import {Auction} from "./Auction.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {ERC20PermitUpgradeable} from
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
/**
* @title BondToken
* @dev This contract implements a bond token with upgradeable capabilities, access control, and
* pausability.
* It includes functionality for managing indexed user assets and global asset pools.
*/
contract BondToken is
Initializable,
ERC20Upgradeable,
AccessControlUpgradeable,
ERC20PermitUpgradeable,
UUPSUpgradeable,
PausableUpgradeable
{
using Decimals for uint256;
/**
* @dev Struct to represent a pool's outstanding shares and shares per bond at a specific period
* @param period The period of the pool amount
* @param amount The total amount in the pool
* @param sharesPerToken The number of shares per token (base 10000)
*/
struct PoolAmount {
uint256 period;
uint256 amount;
uint256 sharesPerToken;
}
/**
* @dev Struct to represent the global asset pool, including the current period, shares per token,
* and previous pool amounts.
* @param currentPeriod The current period of the global pool
* @param sharesPerToken The current number of shares per token (base 1e6)
* @param previousPoolAmounts An array of previous pool amounts
*/
struct IndexedGlobalAssetPool {
uint256 currentPeriod;
uint256 sharesPerToken;
PoolAmount[] previousPoolAmounts;
}
/**
* @dev Struct to represent a user's indexed assets, which are the user's shares
* @param lastUpdatedPeriod The last GLOBAL period when the user's assets were updated, NOT the
* user's last period accounted for
* @param indexedAmountShares The user's indexed amount of shares, which does not include the last
* indexed period's shares
* @param lastIndexedPeriodShares The user's shares from the last indexed period. See
* getIndexedUserAmount for why this is kept separate.
*/
struct IndexedUserAssets {
uint256 lastUpdatedPeriod;
uint256 indexedAmountShares;
uint256 lastIndexedPeriodBalance;
}
/// @dev The global asset pool
IndexedGlobalAssetPool public globalPool;
/// @dev Pool factory address
PoolFactory public poolFactory;
Pool public pool;
/// @dev Mapping of user addresses to their indexed assets
mapping(address => IndexedUserAssets) public userAssets;
/// @dev The number of blocks before transfers are re-enabled after an auction start
uint256 auctionStartTransfersPause;
uint256 auctionStartBlock;
/// @dev Mapping of addresses that can receive tokens even when paused
mapping(address => bool) public toWhitelist;
/// @dev Mapping of addresses that can send tokens even when paused
mapping(address => bool) public fromWhitelist;
/// @dev Role identifier for accounts with minting privileges
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
/// @dev Role identifier for accounts with governance privileges
bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE");
/// @dev Role identifier for the distributor
bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE");
/// @dev The number of decimals for shares
uint8 public constant SHARES_DECIMALS = 6;
/// @dev Error thrown when the caller is not the security council
error CallerIsNotSecurityCouncil();
/// @dev Error thrown when the caller is not the pool factory
error CallerIsNotPoolFactory();
/// @dev Error thrown when the caller is not the pool
error CallerIsNotPool();
/// @dev Error thrown when an auction has recently started
error AuctionRecentlyStarted();
/// @dev Emitted when the asset period is increased
event IncreasedAssetPeriod(uint256 currentPeriod, uint256 sharesPerToken);
/// @dev Emitted when a user's assets are updated
event UpdatedUserAssets(address user, uint256 lastUpdatedPeriod, uint256 indexedAmountShares);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @dev Initializes the contract with a name, symbol, minter, governance address, distributor, and
* initial shares per token.
* @param name The name of the token
* @param symbol The symbol of the token
* @param minter The address that will have minting privileges
* @param governance The address that will have governance privileges
* @param sharesPerToken The initial number of shares per token
*/
function initialize(
string memory name,
string memory symbol,
address minter,
address governance,
address _poolFactory,
uint256 sharesPerToken
) public initializer {
__ERC20_init(name, symbol);
__ERC20Permit_init(name);
__UUPSUpgradeable_init();
__Pausable_init();
poolFactory = PoolFactory(_poolFactory);
globalPool.sharesPerToken = sharesPerToken;
_grantRole(MINTER_ROLE, minter);
_grantRole(GOV_ROLE, governance);
_setRoleAdmin(GOV_ROLE, GOV_ROLE);
_setRoleAdmin(DISTRIBUTOR_ROLE, GOV_ROLE);
_setRoleAdmin(MINTER_ROLE, MINTER_ROLE);
auctionStartTransfersPause = 3;
}
/**
* @dev Mints new tokens to the specified address.
* @param to The address that will receive the minted tokens
* @param amount The amount of tokens to mint
* @notice Can only be called by addresses with the MINTER_ROLE.
*/
function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
_mint(to, amount);
}
/**
* @dev Burns tokens from the specified account.
* @param account The account from which tokens will be burned
* @param amount The amount of tokens to burn
* @notice Can only be called by addresses with the MINTER_ROLE.
*/
function burn(address account, uint256 amount) public onlyRole(MINTER_ROLE) {
_burn(account, amount);
}
/**
* @dev Returns the previous pool amounts from the global pool.
* @return An array of PoolAmount structs representing the previous pool amounts
*/
function getPreviousPoolAmounts() external view returns (PoolAmount[] memory) {
return globalPool.previousPoolAmounts;
}
/**
* @dev Internal function to update user assets after a transfer. Also checks if an auction was recently started.
* @param from The address tokens are transferred from
* @param to The address tokens are transferred to
* @param amount The amount of tokens transferred
* @notice This function is called during token transfer and is paused when the contract is
* paused, unless the from or to address is whitelisted.
*/
function _update(address from, address to, uint256 amount) internal virtual override {
// Check if transfer is allowed when paused
if (paused()) {
bool isWhitelistedTransfer = fromWhitelist[from] || toWhitelist[to];
if (!isWhitelistedTransfer) {
revert EnforcedPause();
}
}
if (auctionStartBlock + auctionStartTransfersPause > block.number) revert AuctionRecentlyStarted();
if (from != address(0)) updateIndexedUserAssets(from, balanceOf(from));
if (to != address(0)) updateIndexedUserAssets(to, balanceOf(to));
super._update(from, to, amount);
}
/**
* @dev Updates the indexed user assets for a specific user.
* @param user The address of the user
* @param balance The current balance of the user
* @notice This function updates the number of shares held by the user based on the current
* period.
*/
function updateIndexedUserAssets(address user, uint256 balance) internal {
uint256 currentPeriod = globalPool.currentPeriod;
(uint256 shares, uint256 lastIndexedPeriodBalance) = getIndexedUserAmount(user, balance, currentPeriod);
userAssets[user].indexedAmountShares = shares;
userAssets[user].lastUpdatedPeriod = currentPeriod;
userAssets[user].lastIndexedPeriodBalance = lastIndexedPeriodBalance;
emit UpdatedUserAssets(user, currentPeriod, shares);
}
function getIndexedUserAmount(address user) public view returns (uint256, uint256) {
return getIndexedUserAmount(user, balanceOf(user), globalPool.currentPeriod);
}
/**
* @dev Returns the indexed amount of shares for a specific user.
* @param user The address of the user
* @param balance The current balance of the user
* @return The indexed amount of shares for the user
* @notice This function calculates the number of shares based on the current period and the
* previous pool amounts.
* We separate the last indexed period shares from the total shares to account for ongoing
* auctions.
* Contracts calling this function should be aware that shares should not be paid out for bidding
* auctions. We currently handle this in the Distributor by checking if the last auction is still active.
* For RemoteDistributor, we simply track a nonce, which gets incremented on every USDC bridging, or sharesPerToken
* reset to zero if auction fails.
*/
function getIndexedUserAmount(address user, uint256 balance, uint256 currentPeriod)
public
view
returns (uint256, uint256)
{
IndexedUserAssets memory userPool = userAssets[user];
uint256 lastUpdatedPeriod = userPool.lastUpdatedPeriod;
uint256 shares = userPool.indexedAmountShares;
uint256 lastIndexedPeriodBalance = userPool.lastIndexedPeriodBalance;
// No indexing if the last updated period is the current period
if (currentPeriod == 0) return (0, 0);
if (lastUpdatedPeriod == currentPeriod) return (shares, lastIndexedPeriodBalance);
// loop through all previous periods except the last one being accounted for
for (uint256 i = lastUpdatedPeriod; i < currentPeriod - 1; i++) {
shares += (balance * globalPool.previousPoolAmounts[i].sharesPerToken).toBaseUnit(SHARES_DECIMALS);
}
// We need to backtrack to when the last time lastIndexedPeriodShares was recorded, and
// confirm that the corresponding auction was successful in order to add the amount to the
// 'normal' shares counter. This amount is not accounted for in the loop above.
if (lastUpdatedPeriod > 0) {
shares += (lastIndexedPeriodBalance * globalPool.previousPoolAmounts[lastUpdatedPeriod - 1].sharesPerToken)
.toBaseUnit(SHARES_DECIMALS);
}
return (shares, balance);
}
/**
* @dev Resets the indexed user assets for a specific user.
* @param user The address of the user
* @notice This function resets the last updated period and indexed amount of shares to zero.
* Can only be called by addresses with the DISTRIBUTOR_ROLE and when the contract is not paused.
*/
function resetIndexedUserAssets(address user, bool resetLastIndexedPeriodBalance)
external
onlyRole(DISTRIBUTOR_ROLE)
whenNotPaused
{
userAssets[user].indexedAmountShares = 0;
if (resetLastIndexedPeriodBalance) {
userAssets[user].lastIndexedPeriodBalance = 0;
} else {
(, userAssets[user].lastIndexedPeriodBalance) =
getIndexedUserAmount(user, balanceOf(user), globalPool.currentPeriod);
}
userAssets[user].lastUpdatedPeriod = globalPool.currentPeriod;
}
/**
* @dev Increases the current period and updates the shares per token.
* @param sharesPerToken The new number of shares per token
* @notice Can only be called by addresses with the GOV_ROLE and when the contract is not paused.
*/
function increaseIndexedAssetPeriod(uint256 sharesPerToken) public onlyRole(DISTRIBUTOR_ROLE) whenNotPaused {
globalPool.previousPoolAmounts.push(
PoolAmount({period: globalPool.currentPeriod, amount: totalSupply(), sharesPerToken: sharesPerToken})
);
globalPool.currentPeriod++;
globalPool.sharesPerToken = sharesPerToken;
emit IncreasedAssetPeriod(globalPool.currentPeriod, sharesPerToken);
}
/**
* @dev Sets the shares per token for the last period to 0. Only called by the Pool when the
* auction fails.
* @notice Can only be called by addresses with the DISTRIBUTOR_ROLE and when the contract is not
* paused.
*/
function zeroLastSharesPerToken() external onlyRole(DISTRIBUTOR_ROLE) {
globalPool.previousPoolAmounts[globalPool.currentPeriod - 1].sharesPerToken = 0;
}
/**
* @dev Sets the auction start block. Only called by the Pool.
* @param _auctionStartBlock The block number at which the auction started
*/
function setAuctionStartBlock(uint256 _auctionStartBlock) external onlyPool {
auctionStartBlock = _auctionStartBlock;
}
/**
* @dev Sets the pool for the bond token. Only called by the pool factory, and only once during
* Pool creation.
* @param _pool The address of the pool
*/
function setPool(address _pool) external {
require(msg.sender == address(poolFactory), CallerIsNotPoolFactory());
pool = Pool(_pool);
}
/**
* @dev Sets the shares per token.
* @param _sharesPerToken The new shares per token value.
*/
function setSharesPerToken(uint256 _sharesPerToken) external onlyPool {
globalPool.sharesPerToken = _sharesPerToken;
}
function setAuctionStartTransfersPause(uint256 _auctionStartTransfersPause) external onlyRole(GOV_ROLE) {
auctionStartTransfersPause = _auctionStartTransfersPause;
}
/**
* @dev Adds or removes an address from the to whitelist.
* @param account The address to update
* @param isWhitelisted Whether the address should be whitelisted
* @notice Can only be called by addresses with the GOV_ROLE.
*/
function setToWhitelist(address account, bool isWhitelisted) external onlyRole(GOV_ROLE) {
toWhitelist[account] = isWhitelisted;
}
/**
* @dev Adds or removes an address from the from whitelist.
* @param account The address to update
* @param isWhitelisted Whether the address should be whitelisted
* @notice Can only be called by addresses with the GOV_ROLE.
*/
function setFromWhitelist(address account, bool isWhitelisted) external onlyRole(GOV_ROLE) {
fromWhitelist[account] = isWhitelisted;
}
/**
* @dev Pauses all contract functions except for upgrades.
* Requirements:
* - the caller must have the `SECURITY_COUNCIL_ROLE` from the pool factory.
*/
function pause() external onlySecurityCouncil {
_pause();
}
/**
* @dev Unpauses all contract functions.
* Requirements:
* - the caller must have the `SECURITY_COUNCIL_ROLE`.
*/
function unpause() external onlySecurityCouncil {
_unpause();
}
modifier onlySecurityCouncil() {
if (!poolFactory.hasRole(poolFactory.SECURITY_COUNCIL_ROLE(), msg.sender)) revert CallerIsNotSecurityCouncil();
_;
}
modifier onlyPool() {
if (msg.sender != address(pool)) revert CallerIsNotPool();
_;
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract.
* Called by
* {upgradeTo} and {upgradeToAndCall}.
* @param newImplementation Address of the new implementation contract
* @notice Can only be called by addresses with the GOV_ROLE.
*/
function _authorizeUpgrade(address newImplementation) internal override onlyRole(GOV_ROLE) {}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
library Decimals {
/**
* @dev Converts a token amount to its base unit representation.
* @param amount The token amount.
* @param decimals The number of decimals the token uses.
* @return The base unit representation of the token amount.
*/
function toBaseUnit(uint256 amount, uint8 decimals) internal pure returns (uint256) {
return amount / (10 ** decimals);
}
/**
* @dev Converts a base unit representation to a token amount.
* @param baseUnitAmount The base unit representation of the token amount.
* @param decimals The number of decimals the token uses.
* @return The token amount.
*/
function fromBaseUnit(uint256 baseUnitAmount, uint8 decimals) internal pure returns (uint256) {
return baseUnitAmount * (10 ** decimals);
}
/**
* @dev Normalizes a token amount to a common decimal base.
* @param amount The token amount.
* @param fromDecimals The number of decimals the token uses.
* @param toDecimals The target number of decimals.
* @return The normalized token amount.
*/
function normalizeAmount(uint256 amount, uint8 fromDecimals, uint8 toDecimals) internal pure returns (uint256) {
if (fromDecimals > toDecimals) return amount / (10 ** (fromDecimals - toDecimals));
else if (fromDecimals < toDecimals) return amount * (10 ** (toDecimals - fromDecimals));
else return amount;
}
/**
* @dev Normalizes a token amount to a specified decimal base.
* @param token The ERC20 token.
* @param amount The token amount to normalize.
* @param toDecimals The target number of decimals.
* @return The normalized token amount.
*/
function normalizeTokenAmount(uint256 amount, address token, uint8 toDecimals) internal view returns (uint256) {
uint8 decimals = IERC20Metadata(token).decimals();
return normalizeAmount(amount, decimals, toDecimals);
}
/**
* @dev Adds two token amounts with different decimals.
* @param amount1 The first token amount.
* @param decimals1 The number of decimals for the first token.
* @param amount2 The second token amount.
* @param decimals2 The number of decimals for the second token.
* @param resultDecimals The number of decimals for the result.
* @return The sum of the two token amounts normalized to the result decimals.
*/
function addAmounts(uint256 amount1, uint8 decimals1, uint256 amount2, uint8 decimals2, uint8 resultDecimals)
internal
pure
returns (uint256)
{
uint256 normalizedAmount1 = normalizeAmount(amount1, decimals1, resultDecimals);
uint256 normalizedAmount2 = normalizeAmount(amount2, decimals2, resultDecimals);
return normalizedAmount1 + normalizedAmount2;
}
/**
* @dev Subtracts two token amounts with different decimals.
* @param amount1 The first token amount.
* @param decimals1 The number of decimals for the first token.
* @param amount2 The second token amount.
* @param decimals2 The number of decimals for the second token.
* @param resultDecimals The number of decimals for the result.
* @return The difference of the two token amounts normalized to the result decimals.
*/
function subtractAmounts(uint256 amount1, uint8 decimals1, uint256 amount2, uint8 decimals2, uint8 resultDecimals)
internal
pure
returns (uint256)
{
uint256 normalizedAmount1 = normalizeAmount(amount1, decimals1, resultDecimals);
uint256 normalizedAmount2 = normalizeAmount(amount2, decimals2, resultDecimals);
return normalizedAmount1 - normalizedAmount2;
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {Pool} from "./Pool.sol";
import {BondToken} from "./BondToken.sol";
import {Distributor} from "./Distributor.sol";
import {DistributorAdapter} from "./DistributorAdapter.sol";
import {LeverageToken} from "./LeverageToken.sol";
import {Create3} from "@create3/contracts/Create3.sol";
import {Deployer} from "./utils/Deployer.sol";
import {ERC20Extensions} from "./lib/ERC20Extensions.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {BeaconProxy} from "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
/**
* @title PoolFactory
* @dev This contract is responsible for creating and managing pools.
* It inherits from various OpenZeppelin upgradeable contracts for enhanced functionality and
* security.
*/
contract PoolFactory is Initializable, AccessControlUpgradeable, UUPSUpgradeable, PausableUpgradeable {
using SafeERC20 for IERC20;
using ERC20Extensions for IERC20;
bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE");
bytes32 public constant POOL_ROLE = keccak256("POOL_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant SECURITY_COUNCIL_ROLE = keccak256("SECURITY_COUNCIL_ROLE");
struct PoolParams {
uint256 fee;
address reserveToken;
address couponToken;
uint256 distributionPeriod;
uint256 sharesPerToken;
address feeBeneficiary;
}
/// @dev Array to store addresses of created pools
address[] public pools;
/// @dev Address of the governance contract
address public governance;
/// @dev Address of the OracleFeeds contract
address public oracleFeeds;
/// @dev Instance of the Deployer contract
Deployer public deployer;
/// @dev Address of the UpgradeableBeacon for Pool
address public poolBeacon;
/// @dev Address of the UpgradeableBeacon for BondToken
address public bondBeacon;
/// @dev Address of the UpgradeableBeacon for LeverageToken
address public leverageBeacon;
/// @dev Address of the UpgradeableBeacon for Distributor
address public distributorBeacon;
/// @dev Address of the UpgradeableBeacon for DistributorAdapter
address public distributorIntegrationAdapterBeacon;
/// @dev Address of the DistributorCouponBridgeAdapter
address public crossChainController;
/// @dev Mapping to store distributor addresses for each pool
mapping(address => address) public distributors;
/// @dev Mapping to store integrating protocol distributor adapters for each pool
mapping(address => address) public distributorIntegrationAdapters;
/// @dev Error thrown when bond amount is zero
error ZeroDebtAmount();
/// @dev Error thrown when reserve amount is zero
error ZeroReserveAmount();
/// @dev Error thrown when leverage amount is zero
error ZeroLeverageAmount();
/// @dev Error thrown when distributor adapter beacon is already set
error AlreadySet();
/**
* @dev Emitted when a new pool is created
* @param pool Address of the newly created pool
* @param reserveAmount Amount of reserve tokens
* @param bondAmount Amount of bond tokens
* @param leverageAmount Amount of leverage tokens
*/
event PoolCreated(address pool, uint256 reserveAmount, uint256 bondAmount, uint256 leverageAmount);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @dev Initializes the contract with the governance address and sets up roles.
* This function is called once during deployment or upgrading to initialize state variables.
* @param _governance Address of the governance account that will have the GOV_ROLE.
* @param _deployer Address of the Deployer contract.
* @param _oracleFeeds Address of the OracleFeeds contract.
* @param _poolImplementation Address of the Pool implementation contract.
* @param _bondImplementation Address of the BondToken implementation contract.
* @param _leverageImplementation Address of the LeverageToken implementation contract.
* @param _distributorImplementation Address of the Distributor implementation contract.
*/
function initialize(
address _governance,
address _deployer,
address _oracleFeeds,
address _poolImplementation,
address _bondImplementation,
address _leverageImplementation,
address _distributorImplementation
) public initializer {
__UUPSUpgradeable_init();
__Pausable_init();
deployer = Deployer(_deployer);
governance = _governance;
oracleFeeds = _oracleFeeds;
_grantRole(GOV_ROLE, _governance);
// Stores beacon implementation addresses
poolBeacon = _poolImplementation;
bondBeacon = _bondImplementation;
leverageBeacon = _leverageImplementation;
distributorBeacon = _distributorImplementation;
// Temporary privilege for deployment configs. REVOKE IN PROD
_grantRole(GOV_ROLE, msg.sender);
}
/**
* @dev Creates a new pool with the given parameters
* @param params Struct containing pool parameters
* @param reserveAmount Amount of reserve tokens to seed the pool
* @param bondAmount Amount of bond tokens to mint
* @param leverageAmount Amount of leverage tokens to mint
* @return Address of the newly created pool
*/
function createPool(
PoolParams calldata params,
uint256 reserveAmount,
uint256 bondAmount,
uint256 leverageAmount,
string memory bondName,
string memory bondSymbol,
string memory leverageName,
string memory leverageSymbol,
bool pauseOnCreation
) external whenNotPaused onlyRole(POOL_ROLE) returns (address) {
if (reserveAmount == 0) revert ZeroReserveAmount();
if (bondAmount == 0) revert ZeroDebtAmount();
if (leverageAmount == 0) revert ZeroLeverageAmount();
// Deploy Bond token
BondToken bondToken = BondToken(
deployer.deployBondToken(
bondBeacon, bondName, bondSymbol, address(this), address(this), address(this), params.sharesPerToken
)
);
// Deploy Leverage token
LeverageToken lToken = LeverageToken(
deployer.deployLeverageToken(
leverageBeacon, leverageName, leverageSymbol, address(this), address(this), address(this)
)
);
// Deploy pool contract as a BeaconProxy
bytes memory initData = abi.encodeCall(
Pool.initialize,
(
address(this),
params.fee,
params.reserveToken,
address(bondToken),
address(lToken),
params.couponToken,
params.sharesPerToken,
params.distributionPeriod,
params.feeBeneficiary,
oracleFeeds,
pauseOnCreation
)
);
address pool = Create3.create3(
keccak256(abi.encodePacked(params.reserveToken, params.couponToken, bondToken.symbol(), lToken.symbol())),
abi.encodePacked(type(BeaconProxy).creationCode, abi.encode(poolBeacon, initData))
);
BondToken(bondToken).setPool(pool);
// Deploy distributors
Distributor distributor = Distributor(deployer.deployDistributor(distributorBeacon, pool, address(this)));
distributors[pool] = address(distributor);
distributorIntegrationAdapters[pool] =
deployer.deployDistributorIntegrationAdapter(distributorIntegrationAdapterBeacon, pool);
// Deploy bridge distributors
bondToken.grantRole(MINTER_ROLE, pool);
lToken.grantRole(MINTER_ROLE, pool);
bondToken.grantRole(bondToken.DISTRIBUTOR_ROLE(), pool);
bondToken.grantRole(bondToken.DISTRIBUTOR_ROLE(), address(distributor));
// set token governance
bondToken.grantRole(GOV_ROLE, governance);
lToken.grantRole(GOV_ROLE, governance);
// renounce governance from factory
bondToken.revokeRole(GOV_ROLE, address(this));
lToken.revokeRole(GOV_ROLE, address(this));
pools.push(pool);
emit PoolCreated(pool, reserveAmount, bondAmount, leverageAmount);
// Send seed reserves to pool
IERC20(params.reserveToken).safeTransferFrom(msg.sender, pool, reserveAmount);
// Mint seed amounts
bondToken.mint(msg.sender, bondAmount);
lToken.mint(msg.sender, leverageAmount);
// Revoke minter role from factory
bondToken.revokeRole(MINTER_ROLE, address(this));
lToken.revokeRole(MINTER_ROLE, address(this));
return pool;
}
/**
* @dev Returns the number of pools created.
* @return The length of the pools array.
*/
function poolsLength() external view returns (uint256) {
return pools.length;
}
/**
* @dev Sets the deployer address.
* @param _deployer The address of the deployer.
*/
function setDeployer(address _deployer) external onlyRole(GOV_ROLE) {
deployer = Deployer(_deployer);
}
/**
* @dev Sets the governance address.
* @param _governance The address of the governance.
*/
function setGovernance(address _governance) external onlyRole(GOV_ROLE) {
address oldGovernance = governance;
governance = _governance;
grantRole(GOV_ROLE, _governance);
revokeRole(GOV_ROLE, oldGovernance);
}
/**
* @dev Sets the distributor adapter beacon address. We need this as we can't use a reinitializer as this has been
* disabled in the constructor with _disableInitializers(). Enforced to only be callable once
*/
function setDistributorIntegrationAdapterBeacon(address _distributorIntegrationAdapterBeacon)
external
onlyRole(GOV_ROLE)
{
if (distributorIntegrationAdapterBeacon != address(0)) revert AlreadySet();
distributorIntegrationAdapterBeacon = _distributorIntegrationAdapterBeacon;
}
/**
* @dev Sets the distributor bridge adapter address. Same restriction as setDistributorIntegrationAdapterBeacon
*/
function setCrossChainController(address _crossChainController) external onlyRole(GOV_ROLE) {
if (crossChainController != address(0)) revert AlreadySet();
crossChainController = _crossChainController;
}
/**
* @dev Grants `role` to `account`.
* If `account` had not been already granted `role`, emits a {RoleGranted} event.
* @param role The role to grant
* @param account The account to grant the role to
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(GOV_ROLE) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
* If `account` had been granted `role`, emits a {RoleRevoked} event.
* @param role The role to revoke
* @param account The account to revoke the role from
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(GOV_ROLE) {
_revokeRole(role, account);
}
/**
* @dev Pauses contract. Reverts any interaction except upgrade.
*/
function pause() external onlyRole(SECURITY_COUNCIL_ROLE) {
_pause();
}
/**
* @dev Unpauses contract.
*/
function unpause() external onlyRole(SECURITY_COUNCIL_ROLE) {
_unpause();
}
/**
* @dev Authorizes an upgrade to a new implementation.
* Can only be called by the owner of the contract.
* @param newImplementation Address of the new implementation
*/
function _authorizeUpgrade(address newImplementation) internal override onlyRole(GOV_ROLE) {}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {Auction} from "./Auction.sol";
import {BondToken} from "./BondToken.sol";
import {Decimals} from "./lib/Decimals.sol";
import {OracleFeeds} from "./OracleFeeds.sol";
import {Distributor} from "./Distributor.sol";
import {DistributorAdapter} from "./DistributorAdapter.sol";
import {PoolFactory} from "./PoolFactory.sol";
import {Deployer} from "./utils/Deployer.sol";
import {Validator} from "./utils/Validator.sol";
import {OracleReader} from "./OracleReader.sol";
import {LeverageToken} from "./LeverageToken.sol";
import {CrossChainController} from "./cross-chain/CrossChainController.sol";
import {ERC20Extensions} from "./lib/ERC20Extensions.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
/**
* @title Pool
* @dev This contract manages a pool of assets, allowing for the creatio and redemption of bond and
* leverage tokens.
* It also handles distribution periods and interacts with an oracle for price information.
*/
contract Pool is Initializable, PausableUpgradeable, ReentrancyGuardUpgradeable, OracleReader, Validator {
using Decimals for uint256;
using SafeERC20 for IERC20;
using ERC20Extensions for IERC20;
// Constants
uint256 private constant POINT_EIGHT = 800_000; // 1000000 precision | 800000=0.8
uint256 private constant POINT_TWO = 200_000;
uint256 private constant COLLATERAL_THRESHOLD = 1_250_000;
uint256 private constant PRECISION = 1_000_000;
uint256 private constant BOND_TARGET_PRICE = 100;
uint8 private constant COMMON_DECIMALS = 18;
uint256 private constant SECONDS_PER_YEAR = 365 days;
uint256 private constant MIN_POOL_SALE_LIMIT = 90; // 90%
// Protocol
PoolFactory public poolFactory;
uint256 private fee;
address public feeBeneficiary;
uint256 private lastFeeClaimTime;
uint256 private poolSaleLimit;
string public name;
// Tokens
address public reserveToken;
BondToken public bondToken;
LeverageToken public lToken;
// Coupon
address public couponToken;
// Distribution
uint256 private sharesPerToken;
uint256 private distributionPeriod; // in seconds
uint256 private auctionPeriod; // in seconds
uint256 private lastDistribution; // timestamp in seconds
mapping(uint256 => address) public auctions;
/**
* @dev Enum representing the types of tokens that can be created or redeemed.
*/
enum TokenType {
BOND, // bond
LEVERAGE
}
/**
* @dev Struct containing information about the pool's current state.
*/
struct PoolInfo {
uint256 fee;
uint256 reserve; //underlying token amount
uint256 bondSupply;
uint256 levSupply;
uint256 sharesPerToken;
uint256 currentPeriod;
uint256 lastDistribution;
uint256 distributionPeriod;
uint256 auctionPeriod;
address feeBeneficiary;
}
// Custom errors
error MinAmount();
error ZeroAmount();
error FeeTooHigh();
error AccessDenied();
error NotBeneficiary();
error ZeroDebtSupply();
error AuctionIsOngoing();
error ZeroLeverageSupply();
error CallerIsNotAuction();
error DistributionPeriod();
error AuctionPeriodPassed();
error AuctionAlreadyStarted();
error PoolSaleLimitTooLow();
error DistributionPeriodNotPassed();
// Events
event AuctionStarted(address auction, uint256 period, uint256 couponAmountToDistribute);
event SharesPerTokenChanged(uint256 oldSharesPerToken, uint256 sharesPerToken);
event Distributed(uint256 period, uint256 amount, address distributor, address distributorAdapter);
event AuctionPeriodChanged(uint256 oldPeriod, uint256 newPeriod);
event DistributionRollOver(uint256 period, uint256 shares);
event DistributionPeriodChanged(uint256 oldPeriod, uint256 newPeriod);
event TokensCreated(
address caller, address indexed onBehalfOf, TokenType tokenType, uint256 depositedAmount, uint256 mintedAmount
);
event TokensRedeemed(
address caller, address indexed onBehalfOf, TokenType tokenType, uint256 depositedAmount, uint256 redeemedAmount
);
event FeeClaimed(address beneficiary, uint256 amount);
event NoFeesToClaim();
event FeeChanged(uint256 oldFee, uint256 newFee);
event PoolSaleLimitChanged(uint256 oldThreshold, uint256 newThreshold);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @dev Initializes the contract with the given parameters.
* @param _poolFactory Address of the pool factory contract.
* @param _fee Fee percentage for the pool.
* @param _reserveToken Address of the reserve token.
* @param _dToken Address of the bond token.
* @param _lToken Address of the leverage token.
* @param _couponToken Address of the coupon token.
* @param _sharesPerToken Initial shares per bond per distribution period.
* @param _distributionPeriod Initial distribution period in seconds.
* @param _oracleFeeds Address of the OracleFeeds contract.
*/
function initialize(
address _poolFactory,
uint256 _fee,
address _reserveToken,
address _dToken,
address _lToken,
address _couponToken,
uint256 _sharesPerToken,
uint256 _distributionPeriod,
address _feeBeneficiary,
address _oracleFeeds,
bool _pauseOnCreation
) public initializer {
__OracleReader_init(_oracleFeeds);
__ReentrancyGuard_init();
__Pausable_init();
poolFactory = PoolFactory(_poolFactory);
// Fee cannot exceed 10%
require(_fee <= 100_000, FeeTooHigh());
fee = _fee;
reserveToken = _reserveToken;
bondToken = BondToken(_dToken);
lToken = LeverageToken(_lToken);
couponToken = _couponToken;
sharesPerToken = _sharesPerToken;
distributionPeriod = _distributionPeriod;
lastDistribution = block.timestamp;
feeBeneficiary = _feeBeneficiary;
lastFeeClaimTime = block.timestamp;
poolSaleLimit = MIN_POOL_SALE_LIMIT;
if (_pauseOnCreation) _pause();
}
/**
* @dev Sets the pool sale limit. Cannot be set below 90%.
* @param _poolSaleLimit The new pool sale limit value.
*/
function setPoolSaleLimit(uint256 _poolSaleLimit) external onlyRole(poolFactory.GOV_ROLE()) {
if (_poolSaleLimit < MIN_POOL_SALE_LIMIT) revert PoolSaleLimitTooLow();
uint256 oldThreshold = poolSaleLimit;
poolSaleLimit = _poolSaleLimit;
emit PoolSaleLimitChanged(oldThreshold, _poolSaleLimit);
}
/**
* @dev Creates new tokens by depositing reserve tokens.
* @param tokenType The type of token to create (BOND or LEVERAGE).
* @param depositAmount The amount of reserve tokens to deposit.
* @param minAmount The minimum amount of new tokens to receive.
* @return amount of new tokens created.
*/
function create(TokenType tokenType, uint256 depositAmount, uint256 minAmount)
external
nonReentrant
whenNotPaused
returns (uint256)
{
return _create(tokenType, depositAmount, minAmount, address(0));
}
/**
* @dev Creates new tokens by depositing reserve tokens, with additional parameters for deadline
* and onBehalfOf for router support.
* @param tokenType The type of token to create (BOND or LEVERAGE).
* @param depositAmount The amount of reserve tokens to deposit.
* @param minAmount The minimum amount of new tokens to receive.
* @param deadline The deadline timestamp in seconds for the transaction to be executed.
* @param onBehalfOf The address to receive the new tokens.
* @return The amount of new tokens created.
*/
function create(TokenType tokenType, uint256 depositAmount, uint256 minAmount, uint256 deadline, address onBehalfOf)
external
nonReentrant
whenNotPaused
checkDeadline(deadline)
returns (uint256)
{
return _create(tokenType, depositAmount, minAmount, onBehalfOf);
}
/**
* @dev Creates new tokens by depositing reserve tokens, with additional parameters for deadline
* and onBehalfOf for router support.
* @param tokenType The type of token to create (BOND or LEVERAGE).
* @param depositAmount The amount of reserve tokens to deposit.
* @param minAmount The minimum amount of new tokens to receive.
* @param onBehalfOf The address to receive the new tokens.
* @return The amount of new tokens created.
*/
function _create(TokenType tokenType, uint256 depositAmount, uint256 minAmount, address onBehalfOf)
private
returns (uint256)
{
_claimFees();
// Get amount to mint
uint256 amount = simulateCreate(tokenType, depositAmount);
// Check slippage
if (amount < minAmount) revert MinAmount();
// Mint amount should be higher than zero
if (amount == 0) revert ZeroAmount();
address recipient = onBehalfOf == address(0) ? msg.sender : onBehalfOf;
// Take reserveToken from user
IERC20(reserveToken).safeTransferFrom(msg.sender, address(this), depositAmount);
// Mint tokens
if (tokenType == TokenType.BOND) bondToken.mint(recipient, amount);
else lToken.mint(recipient, amount);
emit TokensCreated(msg.sender, recipient, tokenType, depositAmount, amount);
return amount;
}
/**
* @dev Simulates the creation of new tokens without actually minting them.
* @param tokenType The type of token to simulate creating (BOND or LEVERAGE).
* @param depositAmount The amount of reserve tokens to simulate depositing.
* @return amount of new tokens that would be created.
*/
function simulateCreate(TokenType tokenType, uint256 depositAmount) public view returns (uint256) {
require(depositAmount > 0, ZeroAmount());
uint256 bondSupply = bondToken.totalSupply().normalizeTokenAmount(address(bondToken), COMMON_DECIMALS);
uint256 levSupply = lToken.totalSupply().normalizeTokenAmount(address(lToken), COMMON_DECIMALS);
uint256 poolReserves =
IERC20(reserveToken).balanceOf(address(this)).normalizeTokenAmount(reserveToken, COMMON_DECIMALS);
poolReserves =
poolReserves - (poolReserves * fee * (block.timestamp - lastFeeClaimTime)) / (PRECISION * SECONDS_PER_YEAR);
depositAmount = depositAmount.normalizeTokenAmount(reserveToken, COMMON_DECIMALS);
uint8 assetDecimals = 0;
if (tokenType == TokenType.LEVERAGE) assetDecimals = lToken.decimals();
else assetDecimals = bondToken.decimals();
return getCreateAmount(
tokenType,
depositAmount,
bondSupply,
levSupply,
poolReserves,
getOraclePrice(reserveToken, USD),
getOracleDecimals(reserveToken, USD)
).normalizeAmount(COMMON_DECIMALS, assetDecimals);
}
/**
* @dev Calculates the amount of new tokens to create based on the current pool state and oracle
* price.
* @param tokenType The type of token to create (BOND or LEVERAGE).
* @param depositAmount The amount of reserve tokens to deposit.
* @param bondSupply The current supply of bond tokens.
* @param levSupply The current supply of leverage tokens.
* @param poolReserves The current amount of reserve tokens in the pool.
* @param ethPrice The current ETH price from the oracle.
* @param oracleDecimals The number of decimals used by the oracle.
* @return amount of new tokens to create.
*/
function getCreateAmount(
TokenType tokenType,
uint256 depositAmount,
uint256 bondSupply,
uint256 levSupply,
uint256 poolReserves,
uint256 ethPrice,
uint8 oracleDecimals
) public pure returns (uint256) {
if (bondSupply == 0) revert ZeroDebtSupply();
uint256 assetSupply = bondSupply;
uint256 multiplier = POINT_EIGHT;
if (tokenType == TokenType.LEVERAGE) {
multiplier = POINT_TWO;
assetSupply = levSupply;
}
uint256 tvl = (ethPrice * poolReserves).toBaseUnit(oracleDecimals);
uint256 collateralLevel = (tvl * PRECISION) / (bondSupply * BOND_TARGET_PRICE);
uint256 creationRate = BOND_TARGET_PRICE * PRECISION;
if (collateralLevel <= COLLATERAL_THRESHOLD) {
if (tokenType == TokenType.LEVERAGE && assetSupply == 0) revert ZeroLeverageSupply();
creationRate = (tvl * multiplier) / assetSupply;
} else if (tokenType == TokenType.LEVERAGE) {
if (assetSupply == 0) revert ZeroLeverageSupply();
uint256 adjustedValue = tvl - (BOND_TARGET_PRICE * bondSupply);
creationRate = (adjustedValue * PRECISION) / assetSupply;
}
return ((depositAmount * ethPrice * PRECISION) / creationRate).toBaseUnit(oracleDecimals);
}
/**
* @dev Redeems tokens for reserve tokens.
* @param tokenType The type of derivative token to redeem (BOND or LEVERAGE).
* @param depositAmount The amount of derivative tokens to redeem.
* @param minAmount The minimum amount of reserve tokens to receive.
* @return amount of reserve tokens received.
*/
function redeem(TokenType tokenType, uint256 depositAmount, uint256 minAmount)
public
nonReentrant
whenNotPaused
returns (uint256)
{
return _redeem(tokenType, depositAmount, minAmount, address(0));
}
/**
* @dev Redeems tokens for reserve tokens, with additional parameters.
* @param tokenType The type of derivative token to redeem (BOND or LEVERAGE).
* @param depositAmount The amount of derivative tokens to redeem.
* @param minAmount The minimum amount of reserve tokens to receive.
* @param deadline The deadline timestamp in seconds for the transaction to be executed.
* @param onBehalfOf The address to receive the reserve tokens.
* @return amount of reserve tokens received.
*/
function redeem(TokenType tokenType, uint256 depositAmount, uint256 minAmount, uint256 deadline, address onBehalfOf)
external
nonReentrant
whenNotPaused
checkDeadline(deadline)
returns (uint256)
{
return _redeem(tokenType, depositAmount, minAmount, onBehalfOf);
}
/**
* @dev Redeems tokens for reserve tokens, with additional parameters.
* @param tokenType The type of derivative token to redeem (BOND or LEVERAGE).
* @param depositAmount The amount of derivative tokens to redeem.
* @param minAmount The minimum amount of reserve tokens to receive.
* @param onBehalfOf The address to receive the reserve tokens.
* @return amount of reserve tokens received.
*/
function _redeem(TokenType tokenType, uint256 depositAmount, uint256 minAmount, address onBehalfOf)
private
returns (uint256)
{
_claimFees();
// Get amount to mint
uint256 reserveAmount = simulateRedeem(tokenType, depositAmount);
// Check whether reserve contains enough funds
if (reserveAmount < minAmount) revert MinAmount();
// Reserve amount should be higher than zero
if (reserveAmount == 0) revert ZeroAmount();
// Burn derivative tokens
if (tokenType == TokenType.BOND) bondToken.burn(msg.sender, depositAmount);
else lToken.burn(msg.sender, depositAmount);
address recipient = onBehalfOf == address(0) ? msg.sender : onBehalfOf;
IERC20(reserveToken).safeTransfer(recipient, reserveAmount);
emit TokensRedeemed(msg.sender, recipient, tokenType, depositAmount, reserveAmount);
return reserveAmount;
}
/**
* @dev Simulates the redemption of tokens without actually burning them.
* @param tokenType The type of derivative token to simulate redeeming (BOND or LEVERAGE).
* @param depositAmount The amount of derivative tokens to simulate redeeming.
* @return amount of reserve tokens that would be received.
*/
function simulateRedeem(TokenType tokenType, uint256 depositAmount) public view returns (uint256) {
require(depositAmount > 0, ZeroAmount());
uint256 bondSupply = bondToken.totalSupply().normalizeTokenAmount(address(bondToken), COMMON_DECIMALS);
uint256 levSupply = lToken.totalSupply().normalizeTokenAmount(address(lToken), COMMON_DECIMALS);
uint256 poolReserves =
IERC20(reserveToken).balanceOf(address(this)).normalizeTokenAmount(reserveToken, COMMON_DECIMALS);
// Calculate and subtract fees from poolReserves
poolReserves =
poolReserves - (poolReserves * fee * (block.timestamp - lastFeeClaimTime)) / (PRECISION * SECONDS_PER_YEAR);
address derivTokenToRedeem = tokenType == TokenType.LEVERAGE ? address(lToken) : address(bondToken);
depositAmount = depositAmount.normalizeTokenAmount(derivTokenToRedeem, COMMON_DECIMALS);
uint8 oracleDecimals = getOracleDecimals(reserveToken, USD);
uint8 sharesDecimals = bondToken.SHARES_DECIMALS();
uint256 marketRate;
address feed = OracleFeeds(oracleFeeds).priceFeeds(derivTokenToRedeem, USD);
if (feed != address(0)) {
marketRate = getOraclePrice(derivTokenToRedeem, USD).normalizeAmount(
getOracleDecimals(derivTokenToRedeem, USD),
sharesDecimals // this is the decimals of the reserve token chainlink feed
);
}
return getRedeemAmount(
tokenType,
depositAmount,
bondSupply,
levSupply,
poolReserves,
getOraclePrice(reserveToken, USD),
oracleDecimals,
marketRate
).normalizeAmount(COMMON_DECIMALS, IERC20(reserveToken).safeDecimals());
}
/**
* @dev Calculates the amount of reserve tokens to be redeemed for a given amount of bond or
* leverage tokens.
* @param tokenType The type of derivative token being redeemed (BOND or LEVERAGE).
* @param depositAmount The amount of derivative tokens being redeemed.
* @param bondSupply The total supply of bond tokens.
* @param levSupply The total supply of leverage tokens.
* @param poolReserves The total amount of reserve tokens in the pool.
* @param ethPrice The current ETH price from the oracle.
* @param oracleDecimals The number of decimals used by the oracle.
* @param marketRate The current market rate of the bond token.
* @return amount of reserve tokens to be redeemed.
*/
function getRedeemAmount(
TokenType tokenType,
uint256 depositAmount,
uint256 bondSupply,
uint256 levSupply,
uint256 poolReserves,
uint256 ethPrice,
uint8 oracleDecimals,
uint256 marketRate
) public pure returns (uint256) {
if (bondSupply == 0) revert ZeroDebtSupply();
uint256 tvl = (ethPrice * poolReserves).toBaseUnit(oracleDecimals);
uint256 assetSupply = bondSupply;
uint256 multiplier = POINT_EIGHT;
// Calculate the collateral level based on the token type
uint256 collateralLevel = (tvl * PRECISION) / (bondSupply * BOND_TARGET_PRICE);
if (tokenType == TokenType.LEVERAGE) {
multiplier = POINT_TWO;
assetSupply = levSupply;
if (assetSupply == 0) revert ZeroLeverageSupply();
}
// Calculate the redeem rate based on the collateral level and token type
uint256 redeemRate;
if (collateralLevel <= COLLATERAL_THRESHOLD) {
redeemRate = ((tvl * multiplier) / assetSupply);
} else if (tokenType == TokenType.LEVERAGE) {
redeemRate = ((tvl - (bondSupply * BOND_TARGET_PRICE)) * PRECISION / assetSupply);
} else {
redeemRate = BOND_TARGET_PRICE * PRECISION;
}
if (marketRate != 0 && marketRate < redeemRate) redeemRate = marketRate;
// Calculate and return the final redeem amount
return ((depositAmount * redeemRate).fromBaseUnit(oracleDecimals) / ethPrice) / PRECISION;
}
/**
* @dev Starts an auction for the current period.
*/
function startAuction() external whenNotPaused {
// Check if distribution period has passed
require(lastDistribution + distributionPeriod < block.timestamp, DistributionPeriodNotPassed());
// Check if auction period hasn't passed
require(lastDistribution + distributionPeriod + auctionPeriod >= block.timestamp, AuctionPeriodPassed());
// Check if auction for current period has already started
(uint256 currentPeriod,) = bondToken.globalPool();
require(auctions[currentPeriod] == address(0), AuctionAlreadyStarted());
uint8 bondDecimals = bondToken.decimals();
uint8 sharesDecimals = bondToken.SHARES_DECIMALS();
uint8 maxDecimals = bondDecimals > sharesDecimals ? bondDecimals : sharesDecimals;
uint256 normalizedTotalSupply = bondToken.totalSupply().normalizeAmount(bondDecimals, maxDecimals);
uint256 normalizedShares = sharesPerToken.normalizeAmount(sharesDecimals, maxDecimals);
// Calculate the coupon amount to distribute
uint256 couponAmountToDistribute =
(normalizedTotalSupply * normalizedShares).toBaseUnit(maxDecimals * 2 - IERC20(couponToken).safeDecimals());
// Round UP the coupon amount relative to slot size
uint256 maxBids = 1000;
couponAmountToDistribute = ((couponAmountToDistribute + maxBids - 1) / maxBids) * maxBids;
address auction = Deployer(poolFactory.deployer()).deployAuction(
address(this),
address(couponToken),
address(reserveToken),
couponAmountToDistribute,
block.timestamp + auctionPeriod,
maxBids,
address(this),
poolSaleLimit
);
auctions[currentPeriod] = auction;
// Increase the bond token period
bondToken.increaseIndexedAssetPeriod(sharesPerToken);
// If cross-chain is enabled, increase the shares per token for all remotes
address crossChainController = poolFactory.crossChainController();
if (crossChainController != address(0)) {
CrossChainController(crossChainController).increaseIndexedAssetPeriodForRemotes(sharesPerToken);
}
// Update last distribution time
lastDistribution += distributionPeriod;
bondToken.setAuctionStartBlock(block.number);
emit AuctionStarted(auction, currentPeriod, couponAmountToDistribute);
}
/**
* @dev Transfers reserve tokens to the current auction.
* @param amount The amount of reserve tokens to transfer.
*/
function transferReserveToAuction(uint256 amount) external virtual {
require(msg.sender == lastAuction(), CallerIsNotAuction());
IERC20(reserveToken).safeTransfer(msg.sender, amount);
}
/**
* @dev Sets the shares per token for the last period to 0. Only called when an auction fails.
*/
function zeroLastSharesPerToken() external {
require(msg.sender == lastAuction(), CallerIsNotAuction());
bondToken.zeroLastSharesPerToken();
// If cross-chain is enabled, zero the shares per token for all remotes
address crossChainController = poolFactory.crossChainController();
if (crossChainController != address(0)) {
CrossChainController(crossChainController).zeroLastSharesPerTokenForRemotes();
}
}
/**
* @dev Distributes coupon tokens to bond token holders.
* Can only be called after the distribution period has passed.
*/
function distribute() external whenNotPaused {
(uint256 currentPeriod,) = bondToken.globalPool();
require(currentPeriod > 0, AccessDenied());
// Period is increased when auction starts, we want to distribute for the previous period
uint256 previousPeriod = currentPeriod - 1;
uint256 couponAmountToDistribute = Auction(auctions[previousPeriod]).totalBuyCouponAmount();
if (
Auction(auctions[previousPeriod]).state() == Auction.State.FAILED_POOL_SALE_LIMIT
|| Auction(auctions[previousPeriod]).state() == Auction.State.FAILED_UNDERSOLD
) {
emit DistributionRollOver(previousPeriod, couponAmountToDistribute);
return;
}
if (Auction(auctions[previousPeriod]).state() != Auction.State.SUCCEEDED) revert AuctionIsOngoing();
// Get Distributor
address distributor = poolFactory.distributors(address(this));
address distributorIntegrationAdapter = poolFactory.distributorIntegrationAdapters(address(this));
CrossChainController crossChainController = CrossChainController(poolFactory.crossChainController());
uint256 distributorIntegrationAdapterAmount;
if (distributorIntegrationAdapter != address(0)) {
distributorIntegrationAdapterAmount = DistributorAdapter(distributorIntegrationAdapter).getDistributionAmount();
}
uint256 remoteDistributionAmount;
if (address(crossChainController) != address(0)) {
remoteDistributionAmount = crossChainController.getRemoteDistributionAmountForPool(address(this));
if (remoteDistributionAmount > 0) {
IERC20(couponToken).safeTransfer(address(crossChainController), remoteDistributionAmount);
crossChainController.sendUsdcToRemoteDistributors(address(this));
}
}
// Transfer coupon tokens to the distributor
IERC20(couponToken).safeTransfer(
distributor, couponAmountToDistribute - distributorIntegrationAdapterAmount - remoteDistributionAmount
);
IERC20(couponToken).safeTransfer(distributorIntegrationAdapter, distributorIntegrationAdapterAmount);
// Update distributor with the amount to distribute
Distributor(distributor).allocate(
couponAmountToDistribute - distributorIntegrationAdapterAmount - remoteDistributionAmount
);
emit Distributed(previousPeriod, couponAmountToDistribute, distributor, distributorIntegrationAdapter);
}
/**
* @dev Returns the current pool information.
* @return info A struct containing various pool parameters and balances in the following order:
* {fee, distributionPeriod, reserve, bondSupply, levSupply, sharesPerToken, currentPeriod,
* lastDistribution, auctionPeriod, feeBeneficiary}
*/
function getPoolInfo() external view returns (PoolInfo memory info) {
(uint256 currentPeriod, uint256 _sharesPerToken) = bondToken.globalPool();
info = PoolInfo({
fee: fee,
distributionPeriod: distributionPeriod,
reserve: IERC20(reserveToken).balanceOf(address(this)),
bondSupply: bondToken.totalSupply(),
levSupply: lToken.totalSupply(),
sharesPerToken: _sharesPerToken,
currentPeriod: currentPeriod,
lastDistribution: lastDistribution,
auctionPeriod: auctionPeriod,
feeBeneficiary: feeBeneficiary
});
}
/**
* @dev Sets the distribution period.
* @param _distributionPeriod The new distribution period.
*/
function setDistributionPeriod(uint256 _distributionPeriod) external NotInAuction onlyRole(poolFactory.GOV_ROLE()) {
uint256 oldPeriod = distributionPeriod;
distributionPeriod = _distributionPeriod;
emit DistributionPeriodChanged(oldPeriod, _distributionPeriod);
}
/**
* @dev Sets the auction period.
* @param _auctionPeriod The new auction period.
*/
function setAuctionPeriod(uint256 _auctionPeriod) external NotInAuction onlyRole(poolFactory.GOV_ROLE()) {
uint256 oldPeriod = auctionPeriod;
auctionPeriod = _auctionPeriod;
emit AuctionPeriodChanged(oldPeriod, _auctionPeriod);
}
/**
* @dev Sets the shares per token.
* @param _sharesPerToken The new shares per token value.
*/
function setSharesPerToken(uint256 _sharesPerToken) external NotInAuction onlyRole(poolFactory.GOV_ROLE()) {
uint256 oldSharesPerToken = sharesPerToken;
sharesPerToken = _sharesPerToken;
bondToken.setSharesPerToken(_sharesPerToken);
emit SharesPerTokenChanged(oldSharesPerToken, sharesPerToken);
}
/**
* @dev Sets the fee for the pool.
* @param _fee The new fee value.
*/
function setFee(uint256 _fee) external onlyRole(poolFactory.GOV_ROLE()) {
// Fee cannot exceed 10%
require(_fee <= 100_000, FeeTooHigh());
// Force a fee claim to prevent governance from setting a higher fee
// and collecting increased fees on old deposits
if (getFeeAmount() > 0) _claimFees();
else lastFeeClaimTime = block.timestamp; // Still checkpoint the fee claim time for cases where
// the fee is set to 0
uint256 oldFee = fee;
fee = _fee;
emit FeeChanged(oldFee, _fee);
}
/**
* @dev Sets the fee beneficiary for the pool.
* @param _feeBeneficiary The address of the new fee beneficiary.
*/
function setFeeBeneficiary(address _feeBeneficiary) external onlyRole(poolFactory.GOV_ROLE()) {
feeBeneficiary = _feeBeneficiary;
}
/**
* @dev Sets the name of the pool.
* @param _name The new name of the pool.
*/
function setName(string memory _name) external onlyRole(poolFactory.GOV_ROLE()) {
name = _name;
}
/**
* @dev Allows the fee beneficiary to claim the accumulated protocol fees.
*/
function claimFees() public nonReentrant {
_claimFees();
}
/**
* @dev Returns the amount of fees to be claimed.
* @return The amount of fees to be claimed.
*/
function getFeeAmount() internal view returns (uint256) {
return (IERC20(reserveToken).balanceOf(address(this)) * fee * (block.timestamp - lastFeeClaimTime))
/ (PRECISION * SECONDS_PER_YEAR);
}
function _claimFees() internal {
uint256 feeAmount = getFeeAmount();
if (feeAmount == 0) {
emit NoFeesToClaim();
return;
}
lastFeeClaimTime = block.timestamp;
IERC20(reserveToken).safeTransfer(feeBeneficiary, feeAmount);
emit FeeClaimed(feeBeneficiary, feeAmount);
}
function lastAuction() internal view returns (address) {
(uint256 currentPeriod,) = bondToken.globalPool();
return auctions[currentPeriod - 1];
}
/**
* @dev Pauses the contract. Reverts any interaction except upgrade.
*/
function pause() external onlyRole(poolFactory.SECURITY_COUNCIL_ROLE()) {
_pause();
}
/**
* @dev Unpauses the contract.
*/
function unpause() external onlyRole(poolFactory.SECURITY_COUNCIL_ROLE()) {
_unpause();
}
/**
* @dev Transfers all reserve assets to a specified address.
* @param to The address to transfer all reserve assets to
* @notice Can only be called by addresses with the GOV_ROLE. This is an emergency function.
*/
function transferAllReserveAssets(address to) external onlyRole(poolFactory.GOV_ROLE()) {
require(to != address(0), "Invalid address");
uint256 balance = IERC20(reserveToken).balanceOf(address(this));
if (balance > 0) {
IERC20(reserveToken).safeTransfer(to, balance);
}
}
/**
* @dev Modifier to check if the caller has the specified role.
* @param role The role to check for.
*/
modifier onlyRole(bytes32 role) {
if (!poolFactory.hasRole(role, msg.sender)) revert AccessDenied();
_;
}
/**
* @dev Modifier to prevent a function from being called during an ongoing auction.
*/
modifier NotInAuction() {
(uint256 currentPeriod,) = bondToken.globalPool();
require(auctions[currentPeriod] == address(0), AuctionIsOngoing());
_;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {Pool} from "./Pool.sol";
import {PoolFactory} from "./PoolFactory.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract Auction is Initializable, UUPSUpgradeable, PausableUpgradeable {
using SafeERC20 for IERC20;
// Pool contract
address public pool;
// Auction beneficiary
address public beneficiary;
// Auction buy and sell tokens
address public buyCouponToken;
address public sellReserveToken;
// Auction end time and total buy amount
uint256 public endTime;
uint256 public totalBuyCouponAmount;
uint256 public poolSaleLimit;
// Pending refunds
mapping(address => uint256) public pendingRefunds; // user => amount
enum State {
BIDDING,
SUCCEEDED,
FAILED_UNDERSOLD,
FAILED_POOL_SALE_LIMIT
}
State public state;
struct Bid {
address bidder;
uint256 buyReserveAmount;
uint256 sellCouponAmount;
uint256 nextBidIndex;
uint256 prevBidIndex;
bool claimed;
}
mapping(uint256 => Bid) public bids; // Mapping to store all bids by their index
uint256 public bidCount;
uint256 public lastBidIndex;
uint256 public highestBidIndex; // The index of the highest bid in the sorted list
uint256 public maxBids;
uint256 public lowestBidIndex; // New variable to track the lowest bid
uint256 public currentCouponAmount; // Aggregated buy amount (coupon) for the auction
uint256 public totalSellReserveAmount; // Aggregated sell amount (reserve) for the auction
event AuctionEnded(State state, uint256 totalSellReserveAmount, uint256 totalBuyCouponAmount);
event FailedAuctionBidRefundClaimed(uint256 indexed bidIndex, address indexed bidder, uint256 sellCouponAmount);
event LosingBidRefundClaimed(address indexed bidder, uint256 sellCouponAmount);
event BidClaimed(uint256 indexed bidIndex, address indexed bidder, uint256 sellCouponAmount);
event BidPlaced(uint256 indexed bidIndex, address indexed bidder, uint256 buyReserveAmount, uint256 sellCouponAmount);
event BidRemoved(
uint256 indexed bidIndex, address indexed bidder, uint256 buyReserveAmount, uint256 sellCouponAmount
);
event BidReduced(
uint256 indexed bidIndex, address indexed bidder, uint256 buyReserveAmount, uint256 sellCouponAmount
);
event BidRefundAllocated(address indexed bidder, uint256 couponAmount);
error AccessDenied();
error AuctionFailed();
error NothingToClaim();
error AlreadyClaimed();
error AuctionHasEnded();
error BidAmountTooLow();
error BidAmountTooHigh();
error InvalidSellAmount();
error AuctionStillOngoing();
error AuctionAlreadyEnded();
error AuctionSucceededOrOngoing();
uint256 public constant MAX_BID_AMOUNT = 1e50;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @dev Initializes the Auction contract.
* @param _buyCouponToken The address of the buy token (coupon).
* @param _sellReserveToken The address of the sell token (reserve).
* @param _totalBuyCouponAmount The total amount of buy tokens (coupon) for the auction.
* @param _endTime The end time of the auction.
* @param _maxBids The maximum number of bids allowed in the auction.
* @param _beneficiary The address of the auction beneficiary.
* @param _poolSaleLimit The percentage threshold auctions should respect when selling reserves
* (e.g. 95 = 95%).
*/
function initialize(
address _pool,
address _buyCouponToken,
address _sellReserveToken,
uint256 _totalBuyCouponAmount,
uint256 _endTime,
uint256 _maxBids,
address _beneficiary,
uint256 _poolSaleLimit
) public initializer {
__UUPSUpgradeable_init();
buyCouponToken = _buyCouponToken; // coupon
sellReserveToken = _sellReserveToken; // reserve
totalBuyCouponAmount = _totalBuyCouponAmount; // coupon amount
endTime = _endTime;
maxBids = _maxBids;
pool = _pool;
poolSaleLimit = _poolSaleLimit;
if (_beneficiary == address(0)) beneficiary = msg.sender;
else beneficiary = _beneficiary;
}
/**
* @dev Places a bid on a portion of the pool.
* @param buyReserveAmount The amount of buy tokens (reserve) to bid.
* @param sellCouponAmount The amount of sell tokens (coupon) to bid.
* @return The index of the bid.
*/
function bid(uint256 buyReserveAmount, uint256 sellCouponAmount)
external
auctionActive
whenNotPaused
returns (uint256)
{
if (sellCouponAmount == 0 || sellCouponAmount > totalBuyCouponAmount) revert InvalidSellAmount();
if (sellCouponAmount % slotSize() != 0) revert InvalidSellAmount();
if (buyReserveAmount == 0) revert BidAmountTooLow();
if (buyReserveAmount > MAX_BID_AMOUNT) revert BidAmountTooHigh();
// Transfer buy tokens to contract
IERC20(buyCouponToken).safeTransferFrom(msg.sender, address(this), sellCouponAmount);
Bid memory newBid = Bid({
bidder: msg.sender,
buyReserveAmount: buyReserveAmount,
sellCouponAmount: sellCouponAmount,
nextBidIndex: 0, // Default to 0, which indicates the end of the list
prevBidIndex: 0, // Default to 0, which indicates the start of the list
claimed: false
});
lastBidIndex++; // Avoids 0 index
uint256 newBidIndex = lastBidIndex;
bids[newBidIndex] = newBid;
bidCount++;
// Insert the new bid into the sorted linked list
insertSortedBid(newBidIndex);
currentCouponAmount += sellCouponAmount;
totalSellReserveAmount += buyReserveAmount;
if (bidCount > maxBids) {
if (lowestBidIndex == newBidIndex) revert BidAmountTooLow();
_removeBid(lowestBidIndex);
}
// Remove and refund out of range bids
removeExcessBids();
// Check if the new bid is still on the map after removeBids
if (bids[newBidIndex].bidder == address(0)) revert BidAmountTooLow();
emit BidPlaced(newBidIndex, msg.sender, buyReserveAmount, sellCouponAmount);
return newBidIndex;
}
/**
* @dev Inserts the bid into the linked list based on the price (buyAmount/sellAmount) in
* descending order, then by sellAmount.
* @param newBidIndex The index of the bid to insert.
*/
function insertSortedBid(uint256 newBidIndex) internal {
Bid storage newBid = bids[newBidIndex];
uint256 newSellCouponAmount = newBid.sellCouponAmount;
uint256 newBuyReserveAmount = newBid.buyReserveAmount;
uint256 leftSide;
uint256 rightSide;
if (highestBidIndex == 0) {
// First bid being inserted
highestBidIndex = newBidIndex;
lowestBidIndex = newBidIndex;
} else {
uint256 currentBidIndex = highestBidIndex;
uint256 previousBidIndex = 0;
// Traverse the linked list to find the correct spot for the new bid
while (currentBidIndex != 0) {
// Cache the current bid's data into local variables
Bid storage currentBid = bids[currentBidIndex];
uint256 currentSellCouponAmount = currentBid.sellCouponAmount;
uint256 currentBuyReserveAmount = currentBid.buyReserveAmount;
uint256 currentNextBidIndex = currentBid.nextBidIndex;
// Compare prices without division by cross-multiplying (it's more gas efficient)
leftSide = newSellCouponAmount * currentBuyReserveAmount;
rightSide = currentSellCouponAmount * newBuyReserveAmount;
if (leftSide > rightSide || (leftSide == rightSide && newSellCouponAmount > currentSellCouponAmount)) break;
previousBidIndex = currentBidIndex;
currentBidIndex = currentNextBidIndex;
}
if (previousBidIndex == 0) {
// New bid is the highest bid
newBid.nextBidIndex = highestBidIndex;
bids[highestBidIndex].prevBidIndex = newBidIndex;
highestBidIndex = newBidIndex;
} else {
// Insert bid in the middle or at the end
newBid.nextBidIndex = currentBidIndex;
newBid.prevBidIndex = previousBidIndex;
bids[previousBidIndex].nextBidIndex = newBidIndex;
if (currentBidIndex != 0) bids[currentBidIndex].prevBidIndex = newBidIndex;
}
// If the new bid is inserted at the end, update the lowest bid index
if (currentBidIndex == 0) lowestBidIndex = newBidIndex;
}
// Cache the lowest bid's data into local variables
Bid storage lowestBid = bids[lowestBidIndex];
uint256 lowestSellCouponAmount = lowestBid.sellCouponAmount;
uint256 lowestBuyReserveAmount = lowestBid.buyReserveAmount;
// Compare prices without division by cross-multiplying (it's more gas efficient)
leftSide = newSellCouponAmount * lowestBuyReserveAmount;
rightSide = lowestSellCouponAmount * newBuyReserveAmount;
if (leftSide < rightSide || (leftSide == rightSide && newSellCouponAmount < lowestSellCouponAmount)) {
lowestBidIndex = newBidIndex;
}
}
/**
* @dev Removes excess bids from the auction.
*/
function removeExcessBids() internal {
if (currentCouponAmount <= totalBuyCouponAmount) return;
uint256 amountToRemove = currentCouponAmount - totalBuyCouponAmount;
uint256 currentIndex = lowestBidIndex;
while (currentIndex != 0 && amountToRemove != 0) {
// Cache the current bid's data into local variables
Bid storage currentBid = bids[currentIndex];
uint256 sellCouponAmount = currentBid.sellCouponAmount;
uint256 prevIndex = currentBid.prevBidIndex;
if (amountToRemove >= sellCouponAmount) {
// Subtract the sellAmount from amountToRemove
amountToRemove -= sellCouponAmount;
// Remove the bid
_removeBid(currentIndex);
// Move to the previous bid (higher price)
currentIndex = prevIndex;
} else {
// Calculate the proportion of sellAmount being removed
uint256 proportion = (amountToRemove * 1e18) / sellCouponAmount;
// Reduce the current bid's amounts
currentBid.sellCouponAmount = sellCouponAmount - amountToRemove;
currentCouponAmount -= amountToRemove;
uint256 reserveReduction = ((currentBid.buyReserveAmount * proportion) / 1e18);
currentBid.buyReserveAmount = currentBid.buyReserveAmount - reserveReduction;
totalSellReserveAmount -= reserveReduction;
// Refund the proportional sellAmount
pendingRefunds[currentBid.bidder] += amountToRemove;
amountToRemove = 0;
emit BidRefundAllocated(currentBid.bidder, amountToRemove);
emit BidReduced(currentIndex, currentBid.bidder, currentBid.buyReserveAmount, currentBid.sellCouponAmount);
}
}
}
/**
* @dev Removes a bid from the linked list.
* @param bidIndex The index of the bid to remove.
*/
function _removeBid(uint256 bidIndex) internal {
Bid storage bidToRemove = bids[bidIndex];
uint256 nextIndex = bidToRemove.nextBidIndex;
uint256 prevIndex = bidToRemove.prevBidIndex;
// Update linked list pointers
if (prevIndex == 0) {
// Removing the highest bid
highestBidIndex = nextIndex;
} else {
bids[prevIndex].nextBidIndex = nextIndex;
}
if (nextIndex == 0) {
// Removing the lowest bid
lowestBidIndex = prevIndex;
} else {
bids[nextIndex].prevBidIndex = prevIndex;
}
address bidder = bidToRemove.bidder;
uint256 buyReserveAmount = bidToRemove.buyReserveAmount;
uint256 sellCouponAmount = bidToRemove.sellCouponAmount;
currentCouponAmount -= sellCouponAmount;
totalSellReserveAmount -= buyReserveAmount;
// Refund the buy tokens for the removed bid
pendingRefunds[bidder] += sellCouponAmount;
emit BidRefundAllocated(bidder, sellCouponAmount);
emit BidRemoved(bidIndex, bidder, buyReserveAmount, sellCouponAmount);
delete bids[bidIndex];
bidCount--;
}
/**
* @dev Ends the auction and transfers the reserve to the auction.
*/
function endAuction() external auctionExpired whenNotPaused {
if (state != State.BIDDING) revert AuctionAlreadyEnded();
if (currentCouponAmount < totalBuyCouponAmount) {
state = State.FAILED_UNDERSOLD;
Pool(pool).zeroLastSharesPerToken();
} else if (totalSellReserveAmount >= (IERC20(sellReserveToken).balanceOf(pool) * poolSaleLimit) / 100) {
state = State.FAILED_POOL_SALE_LIMIT;
Pool(pool).zeroLastSharesPerToken();
} else {
state = State.SUCCEEDED;
Pool(pool).transferReserveToAuction(totalSellReserveAmount);
IERC20(buyCouponToken).safeTransfer(beneficiary, totalBuyCouponAmount);
}
emit AuctionEnded(state, totalSellReserveAmount, totalBuyCouponAmount);
}
/**
* @dev Claims the tokens for a winning bid.
* @param bidIndex The index of the bid to claim.
*/
function claimBid(uint256 bidIndex) external auctionExpired auctionSucceeded whenNotPaused {
Bid storage bidInfo = bids[bidIndex];
if (bidInfo.bidder != msg.sender) revert NothingToClaim();
if (bidInfo.claimed) revert AlreadyClaimed();
bidInfo.claimed = true;
IERC20(sellReserveToken).safeTransfer(bidInfo.bidder, bidInfo.buyReserveAmount);
emit BidClaimed(bidIndex, bidInfo.bidder, bidInfo.buyReserveAmount);
}
function claimRefund(uint256 bidIndex) external auctionExpired auctionFailed whenNotPaused {
Bid storage bidInfo = bids[bidIndex];
if (bidInfo.bidder != msg.sender) revert NothingToClaim();
if (bidInfo.claimed) revert AlreadyClaimed();
bidInfo.claimed = true;
IERC20(buyCouponToken).safeTransfer(bidInfo.bidder, bidInfo.sellCouponAmount);
emit FailedAuctionBidRefundClaimed(bidIndex, bidInfo.bidder, bidInfo.sellCouponAmount);
}
function claimRefund() external whenNotPaused {
uint256 amountToClaim = pendingRefunds[msg.sender];
if (amountToClaim == 0) revert NothingToClaim();
pendingRefunds[msg.sender] = 0;
IERC20(buyCouponToken).safeTransfer(msg.sender, amountToClaim);
emit LosingBidRefundClaimed(msg.sender, amountToClaim);
}
/**
* @dev Returns the size of a bid slot.
* @return uint256 The size of a bid slot.
*/
function slotSize() public view returns (uint256) {
return totalBuyCouponAmount / maxBids;
}
/**
* @dev Modifier to check if the auction is still active.
*/
modifier auctionActive() {
if (block.timestamp >= endTime) revert AuctionHasEnded();
_;
}
/**
* @dev Modifier to check if the auction has expired.
*/
modifier auctionExpired() {
if (block.timestamp < endTime) revert AuctionStillOngoing();
_;
}
/**
* @dev Modifier to check if the auction succeeded.
*/
modifier auctionSucceeded() {
if (state != State.SUCCEEDED) revert AuctionFailed();
_;
}
modifier auctionFailed() {
if (state == State.SUCCEEDED || state == State.BIDDING) revert AuctionSucceededOrOngoing();
_;
}
/**
* @dev Modifier to check if the caller has the specified role.
* @param role The role to check for.
*/
modifier onlyRole(bytes32 role) {
if (!PoolFactory(Pool(pool).poolFactory()).hasRole(role, msg.sender)) revert AccessDenied();
_;
}
function pause() external onlyRole(PoolFactory(Pool(pool).poolFactory()).SECURITY_COUNCIL_ROLE()) {
_pause();
}
function unpause() external onlyRole(PoolFactory(Pool(pool).poolFactory()).SECURITY_COUNCIL_ROLE()) {
_unpause();
}
/**
* @dev Authorizes an upgrade to a new implementation.
* Can only be called by the owner of the contract.
* @param newImplementation Address of the new implementation
*/
function _authorizeUpgrade(address newImplementation)
internal
override
onlyRole(PoolFactory(Pool(pool).poolFactory()).GOV_ROLE())
{}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @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 Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 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 in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._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 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._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() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @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 {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* 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. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC1967-compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
return $._paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../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}.
*
* 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.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @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 {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
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 returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` 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 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
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 `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` 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.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` 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.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
AccessControlStorage storage $ = _getAccessControlStorage();
return $._roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
AccessControlStorage storage $ = _getAccessControlStorage();
bytes32 previousAdminRole = getRoleAdmin(role);
$._roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.20;
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {ERC20Upgradeable} from "../ERC20Upgradeable.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {EIP712Upgradeable} from "../../../utils/cryptography/EIP712Upgradeable.sol";
import {NoncesUpgradeable} from "../../../utils/NoncesUpgradeable.sol";
import {Initializable} from "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation 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.
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20Permit, EIP712Upgradeable, NoncesUpgradeable {
bytes32 private constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Permit deadline has expired.
*/
error ERC2612ExpiredSignature(uint256 deadline);
/**
* @dev Mismatched signature.
*/
error ERC2612InvalidSigner(address signer, address owner);
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal onlyInitializing {
__EIP712_init_unchained(name, "1");
}
function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {}
/**
* @inheritdoc IERC20Permit
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
if (block.timestamp > deadline) {
revert ERC2612ExpiredSignature(deadline);
}
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
if (signer != owner) {
revert ERC2612InvalidSigner(signer, owner);
}
_approve(owner, spender, value);
}
/**
* @inheritdoc IERC20Permit
*/
function nonces(address owner) public view virtual override(IERC20Permit, NoncesUpgradeable) returns (uint256) {
return super.nonces(owner);
}
/**
* @inheritdoc IERC20Permit
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
return _domainSeparatorV4();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
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: UNLICENSED
pragma solidity ^0.8.26;
import {Auction} from "./Auction.sol";
import {Pool} from "./Pool.sol";
import {BondToken} from "./BondToken.sol";
import {Decimals} from "./lib/Decimals.sol";
import {PoolFactory} from "../src/PoolFactory.sol";
import {ERC20Extensions} from "./lib/ERC20Extensions.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
/**
* @title Distributor
* @dev This contract manages the distribution of coupon shares to users based on their bond token
* balances.
*/
contract Distributor is Initializable, PausableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
using ERC20Extensions for IERC20;
using Decimals for uint256;
/// @dev Pool factory address
PoolFactory public poolFactory;
/// @dev Pool address
Pool public pool;
/// @dev Coupon token total amount to be distributed
uint256 public couponAmountToDistribute;
/// @dev Error thrown when there are not enough shares in the contract's balance
error NotEnoughSharesBalance();
/// @dev Error thrown when an unsupported pool is accessed
error UnsupportedPool();
/// @dev Error thrown when there are not enough shares allocated to distribute
error NotEnoughSharesToDistribute();
/// @dev Error thrown when there are not enough coupon tokens in the contract's balance
error NotEnoughCouponBalance();
/// @dev Error thrown when attempting to register an already registered pool
error PoolAlreadyRegistered();
/// @dev Error thrown when the pool has an invalid address
error InvalidPoolAddress();
/// @dev error thrown when the caller is not the pool
error CallerIsNotPool();
/// @dev error thrown when the caller does not have the required role
error AccessDenied();
/// @dev error thrown when user has no shares to claim
error NothingToClaim();
/// @dev Event emitted when a user claims their shares
event ClaimedShares(address user, uint256 period, uint256 shares);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @dev Initializes the contract with the pool address and pool factory address.
* This function is called once during deployment or upgrading to initialize state variables.
* @param _pool Address of the pool.
* @param _poolFactory Address of the pool factory.
*/
function initialize(address _pool, address _poolFactory) public initializer {
__ReentrancyGuard_init();
__Pausable_init();
pool = Pool(_pool);
poolFactory = PoolFactory(_poolFactory);
}
/**
* @dev Allows a user to claim their shares from a specific pool.
* Calculates the number of shares based on the user's bond token balance and the shares per
* token.
* Transfers the calculated shares to the user's address.
*/
function claim() external nonReentrant whenNotPaused {
BondToken bondToken = Pool(pool).bondToken();
address couponToken = Pool(pool).couponToken();
if (address(bondToken) == address(0) || couponToken == address(0)) revert UnsupportedPool();
(uint256 currentPeriod,) = bondToken.globalPool();
uint256 balance = bondToken.balanceOf(msg.sender);
(uint256 shares, uint256 lastIndexedPeriodBalance) =
bondToken.getIndexedUserAmount(msg.sender, balance, currentPeriod);
shares = shares.normalizeAmount(bondToken.decimals(), IERC20(couponToken).safeDecimals());
bool isLastAuctionFinalized = !(Auction(pool.auctions(currentPeriod - 1)).state() == Auction.State.BIDDING);
if (isLastAuctionFinalized) {
BondToken.PoolAmount[] memory poolAmount = bondToken.getPreviousPoolAmounts();
shares += (lastIndexedPeriodBalance * poolAmount[currentPeriod - 1].sharesPerToken).normalizeAmount(
IERC20(bondToken).safeDecimals() + bondToken.SHARES_DECIMALS(), IERC20(couponToken).safeDecimals()
);
}
if (shares == 0) revert NothingToClaim();
if (IERC20(couponToken).balanceOf(address(this)) < shares) revert NotEnoughSharesBalance();
// check if pool has enough *allocated* shares to distribute
if (couponAmountToDistribute < shares) revert NotEnoughSharesToDistribute();
// check if the distributor has enough shares tokens as the amount to distribute
if (IERC20(couponToken).balanceOf(address(this)) < couponAmountToDistribute) revert NotEnoughSharesToDistribute();
couponAmountToDistribute -= shares;
bondToken.resetIndexedUserAssets(msg.sender, isLastAuctionFinalized);
IERC20(couponToken).safeTransfer(msg.sender, shares);
emit ClaimedShares(msg.sender, currentPeriod, shares);
}
/**
* @dev Allocates shares to a pool.
* @param _amountToDistribute Amount of shares to allocate.
*/
function allocate(uint256 _amountToDistribute) external whenNotPaused {
require(address(pool) == msg.sender, CallerIsNotPool());
address couponToken = pool.couponToken();
couponAmountToDistribute += _amountToDistribute;
if (IERC20(couponToken).balanceOf(address(this)) < couponAmountToDistribute) revert NotEnoughCouponBalance();
}
/**
* @dev Pauses the contract. Reverts any interaction except upgrade.
*/
function pause() external onlyRole(poolFactory.SECURITY_COUNCIL_ROLE()) {
_pause();
}
/**
* @dev Unpauses the contract.
*/
function unpause() external onlyRole(poolFactory.SECURITY_COUNCIL_ROLE()) {
_unpause();
}
/**
* @dev Modifier to check if the caller has the specified role.
* @param role The role to check for.
*/
modifier onlyRole(bytes32 role) {
if (!poolFactory.hasRole(role, msg.sender)) revert AccessDenied();
_;
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {Pool} from "./Pool.sol";
import {Auction} from "./Auction.sol";
import {BondToken} from "./BondToken.sol";
import {Decimals} from "./lib/Decimals.sol";
import {PoolFactory} from "./PoolFactory.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
contract DistributorAdapter is Initializable, PausableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
using Decimals for uint256;
struct MerkleRootData {
bytes32 merkleRoot;
string ipfsHash;
}
// State variables
PoolFactory public poolFactory;
Pool public pool;
mapping(uint256 => MerkleRootData[]) public submittedRoots;
mapping(uint256 => MerkleRootData) public selectedRoots;
mapping(address => mapping(uint256 => bool)) public hasClaimed; // user => period => claimed
address[] public integratingContracts;
// Events
event MerkleRootSubmitted(address indexed submitter, uint256 indexed period, bytes32 merkleRoot, string ipfsHash);
event MerkleRootSelected(uint256 indexed period, bytes32 merkleRoot, string ipfsHash);
event IntegratingContractAdded(address indexed contractAddress, uint256 indexed period);
event IntegratingContractRemoved(address indexed contractAddress, uint256 indexed period);
event Claimed(address indexed user, uint256 indexed period, uint256 amount);
// Errors
error InvalidMerkleProof();
error AlreadyClaimed();
error AccessDenied();
error InvalidPeriod();
error NotEnoughBalance();
error CallerIsNotPool();
error AddressNotFound();
error NotInBiddingPhase();
error InvalidRootIndex();
error RootAlreadySelected();
error RootNotActive();
error AuctionNotFinalized();
error NoCouponsYet();
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(address _pool, address _poolFactory) public initializer {
__ReentrancyGuard_init();
__Pausable_init();
pool = Pool(_pool);
poolFactory = PoolFactory(_poolFactory);
}
/**
* @dev Submit a merkle root for the latest completed period, where bond holders are incentivized to do so during the
* bidding phase of the corresponding auction.
* @param _merkleRoot The merkle root
* @param _ipfsHash The ipfs hash containing full merkle tree
*/
function submitMerkleRoot(bytes32 _merkleRoot, string calldata _ipfsHash) external whenNotPaused {
// Posting lists only makes sense during bidding phase, so we enforce this
uint256 currentPeriod = _currentPeriod();
if (currentPeriod == 0) revert NoCouponsYet();
uint256 lastPeriod = currentPeriod - 1;
if (Auction(pool.auctions(lastPeriod)).state() != Auction.State.BIDDING) revert NotInBiddingPhase();
submittedRoots[lastPeriod].push(MerkleRootData({merkleRoot: _merkleRoot, ipfsHash: _ipfsHash}));
emit MerkleRootSubmitted(msg.sender, lastPeriod, _merkleRoot, _ipfsHash);
}
function selectMerkleRoot(uint256 rootIndex) external onlyGov whenNotPaused {
uint256 lastPeriod = _currentPeriod() - 1;
if (rootIndex >= submittedRoots[lastPeriod].length) revert InvalidRootIndex();
MerkleRootData memory selectedRoot = submittedRoots[lastPeriod][rootIndex];
selectedRoots[lastPeriod] = selectedRoot;
emit MerkleRootSelected(lastPeriod, selectedRoot.merkleRoot, selectedRoot.ipfsHash);
}
function addIntegratingContract(address _address) external onlyGov {
integratingContracts.push(_address);
emit IntegratingContractAdded(_address, _currentPeriod());
}
function removeIntegratingContract(address _address) external onlyGov {
for (uint256 i = 0; i < integratingContracts.length; i++) {
if (integratingContracts[i] == _address) {
integratingContracts[i] = integratingContracts[integratingContracts.length - 1];
integratingContracts.pop();
emit IntegratingContractRemoved(_address, _currentPeriod());
return;
}
}
revert AddressNotFound();
}
function claim(uint256 period, uint256 amount, bytes32[] calldata merkleProof)
external
nonReentrant
whenNotPaused
lastAuctionFinalized(period)
{
if (hasClaimed[msg.sender][period]) revert AlreadyClaimed();
// Double hash as per OpenZeppelin guidelines
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(msg.sender, amount))));
if (!MerkleProof.verify(merkleProof, selectedRoots[period].merkleRoot, leaf)) revert InvalidMerkleProof();
if (IERC20(pool.couponToken()).balanceOf(address(this)) < amount) revert NotEnoughBalance();
hasClaimed[msg.sender][period] = true;
IERC20(pool.couponToken()).safeTransfer(msg.sender, amount);
emit Claimed(msg.sender, amount, period);
}
function getDistributionAmount() external view returns (uint256 totalAmount) {
BondToken bondToken = pool.bondToken();
uint256 lastPeriod = _currentPeriod() - 1;
for (uint256 i = 0; i < integratingContracts.length; i++) {
address addr = integratingContracts[i];
(, uint256 lastIndexedPeriodBalance) =
bondToken.getIndexedUserAmount(addr, bondToken.balanceOf(addr), _currentPeriod());
if (lastIndexedPeriodBalance > 0) {
BondToken.PoolAmount[] memory poolAmount = bondToken.getPreviousPoolAmounts();
totalAmount += (lastIndexedPeriodBalance * poolAmount[lastPeriod].sharesPerToken).normalizeAmount(
bondToken.decimals() + bondToken.SHARES_DECIMALS(), bondToken.SHARES_DECIMALS()
);
}
}
}
function _currentPeriod() internal view returns (uint256 currentPeriod) {
(currentPeriod,) = pool.bondToken().globalPool();
}
function pause() external {
if (!poolFactory.hasRole(poolFactory.SECURITY_COUNCIL_ROLE(), msg.sender)) revert AccessDenied();
_pause();
}
function unpause() external {
if (!poolFactory.hasRole(poolFactory.SECURITY_COUNCIL_ROLE(), msg.sender)) revert AccessDenied();
_unpause();
}
modifier onlyGov() {
if (!poolFactory.hasRole(poolFactory.GOV_ROLE(), msg.sender)) revert AccessDenied();
_;
}
modifier lastAuctionFinalized(uint256 period) {
uint256 currentPeriod = _currentPeriod();
if (currentPeriod == 0) revert NoCouponsYet();
uint256 lastPeriod = currentPeriod - 1;
// If the period is the last period, we need to check if the auction is in bidding phase. Prior auctions are
// guaranteed to be finalized
if (period == lastPeriod && Auction(pool.auctions(lastPeriod)).state() == Auction.State.BIDDING) {
revert AuctionNotFinalized();
}
_;
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {PoolFactory} from "./PoolFactory.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import {ERC20PermitUpgradeable} from
"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
/**
* @title LeverageToken
* @dev This contract implements a leverage token with upgradeable capabilities, access control, and
* pausability.
*/
contract LeverageToken is
Initializable,
ERC20Upgradeable,
AccessControlUpgradeable,
ERC20PermitUpgradeable,
UUPSUpgradeable,
PausableUpgradeable
{
/// @dev Role identifier for accounts with minting privileges
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
/// @dev Role identifier for accounts with governance privileges
bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE");
/// @dev The pool factory
PoolFactory public poolFactory;
/// @dev Mapping of addresses that can receive tokens even when paused
mapping(address => bool) public toWhitelist;
/// @dev Mapping of addresses that can send tokens even when paused
mapping(address => bool) public fromWhitelist;
/// @dev Error thrown when the caller is not the security council
error CallerIsNotSecurityCouncil();
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
/**
* @dev Initializes the contract with a name, symbol, minter, and governance address.
* @param name The name of the token
* @param symbol The symbol of the token
* @param minter The address that will have minting privileges
* @param governance The address that will have governance privileges
*/
function initialize(
string memory name,
string memory symbol,
address minter,
address governance,
address _poolFactory
) public initializer {
__ERC20_init(name, symbol);
__ERC20Permit_init(name);
__UUPSUpgradeable_init();
__Pausable_init();
poolFactory = PoolFactory(_poolFactory);
_grantRole(MINTER_ROLE, minter);
_grantRole(GOV_ROLE, governance);
_setRoleAdmin(GOV_ROLE, GOV_ROLE);
_setRoleAdmin(MINTER_ROLE, MINTER_ROLE);
}
/**
* @dev Mints new tokens to the specified address.
* @param to The address that will receive the minted tokens
* @param amount The amount of tokens to mint
* @notice Can only be called by addresses with the MINTER_ROLE.
*/
function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) {
_mint(to, amount);
}
/**
* @dev Burns tokens from the specified account.
* @param account The account from which tokens will be burned
* @param amount The amount of tokens to burn
* @notice Can only be called by addresses with the MINTER_ROLE.
*/
function burn(address account, uint256 amount) public onlyRole(MINTER_ROLE) {
_burn(account, amount);
}
/**
* @dev Internal function to update user assets after a transfer.
* @param from The address tokens are transferred from
* @param to The address tokens are transferred to
* @param amount The amount of tokens transferred
* @notice This function is called during token transfer and is paused when the contract is
* paused, unless the from or to address is whitelisted.
*/
function _update(address from, address to, uint256 amount) internal virtual override {
// Check if transfer is allowed when paused
if (paused()) {
bool isWhitelistedTransfer = fromWhitelist[from] || toWhitelist[to];
if (!isWhitelistedTransfer) {
revert EnforcedPause();
}
}
super._update(from, to, amount);
}
/**
* @dev Adds or removes an address from the to whitelist.
* @param account The address to update
* @param isWhitelisted Whether the address should be whitelisted
* @notice Can only be called by addresses with the GOV_ROLE.
*/
function setToWhitelist(address account, bool isWhitelisted) external onlyRole(GOV_ROLE) {
toWhitelist[account] = isWhitelisted;
}
/**
* @dev Adds or removes an address from the from whitelist.
* @param account The address to update
* @param isWhitelisted Whether the address should be whitelisted
* @notice Can only be called by addresses with the GOV_ROLE.
*/
function setFromWhitelist(address account, bool isWhitelisted) external onlyRole(GOV_ROLE) {
fromWhitelist[account] = isWhitelisted;
}
/**
* @dev Pauses all token transfers, mints, burns, and indexing updates.
* @notice Can only be called by addresses with the SECURITY_COUNCIL_ROLE. Does not prevent
* contract upgrades.
*/
function pause() external onlySecurityCouncil {
_pause();
}
/**
* @dev Unpauses all token transfers, mints, burns, and indexing updates.
* @notice Can only be called by addresses with the SECURITY_COUNCIL_ROLE.
*/
function unpause() external onlySecurityCouncil {
_unpause();
}
modifier onlySecurityCouncil() {
if (!poolFactory.hasRole(poolFactory.SECURITY_COUNCIL_ROLE(), msg.sender)) revert CallerIsNotSecurityCouncil();
_;
}
/**
* @dev Internal function to authorize an upgrade to a new implementation.
* @param newImplementation The address of the new implementation
* @notice Can only be called by the owner of the contract.
*/
function _authorizeUpgrade(address newImplementation) internal override onlyRole(GOV_ROLE) {}
}//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; /** @title A library for deploying contracts EIP-3171 style. @author Agustin Aguilar <[email protected]> */ library Create3 { error ErrorCreatingProxy(); error ErrorCreatingContract(); error TargetAlreadyExists(); /** @notice The bytecode for a contract that proxies the creation of another contract @dev If this code is deployed using CREATE2 it can be used to decouple `creationCode` from the child contract address 0x67363d3d37363d34f03d5260086018f3: 0x00 0x67 0x67XXXXXXXXXXXXXXXX PUSH8 bytecode 0x363d3d37363d34f0 0x01 0x3d 0x3d RETURNDATASIZE 0 0x363d3d37363d34f0 0x02 0x52 0x52 MSTORE 0x03 0x60 0x6008 PUSH1 08 8 0x04 0x60 0x6018 PUSH1 18 24 8 0x05 0xf3 0xf3 RETURN 0x363d3d37363d34f0: 0x00 0x36 0x36 CALLDATASIZE cds 0x01 0x3d 0x3d RETURNDATASIZE 0 cds 0x02 0x3d 0x3d RETURNDATASIZE 0 0 cds 0x03 0x37 0x37 CALLDATACOPY 0x04 0x36 0x36 CALLDATASIZE cds 0x05 0x3d 0x3d RETURNDATASIZE 0 cds 0x06 0x34 0x34 CALLVALUE val 0 cds 0x07 0xf0 0xf0 CREATE addr */ bytes internal constant PROXY_CHILD_BYTECODE = hex"67_36_3d_3d_37_36_3d_34_f0_3d_52_60_08_60_18_f3"; // KECCAK256_PROXY_CHILD_BYTECODE = keccak256(PROXY_CHILD_BYTECODE); bytes32 internal constant KECCAK256_PROXY_CHILD_BYTECODE = 0x21c35dbe1b344a2488cf3321d6ce542f8e9f305544ff09e4993a62319a497c1f; /** @notice Returns the size of the code on a given address @param _addr Address that may or may not contain code @return size of the code on the given `_addr` */ function codeSize(address _addr) internal view returns (uint256 size) { assembly { size := extcodesize(_addr) } } /** @notice Creates a new contract with given `_creationCode` and `_salt` @param _salt Salt of the contract creation, resulting address will be derivated from this value only @param _creationCode Creation code (constructor) of the contract to be deployed, this value doesn't affect the resulting address @return addr of the deployed contract, reverts on error */ function create3(bytes32 _salt, bytes memory _creationCode) internal returns (address addr) { return create3(_salt, _creationCode, 0); } /** @notice Creates a new contract with given `_creationCode` and `_salt` @param _salt Salt of the contract creation, resulting address will be derivated from this value only @param _creationCode Creation code (constructor) of the contract to be deployed, this value doesn't affect the resulting address @param _value In WEI of ETH to be forwarded to child contract @return addr of the deployed contract, reverts on error */ function create3(bytes32 _salt, bytes memory _creationCode, uint256 _value) internal returns (address addr) { // Creation code bytes memory creationCode = PROXY_CHILD_BYTECODE; // Get target final address addr = addressOf(_salt); if (codeSize(addr) != 0) revert TargetAlreadyExists(); // Create CREATE2 proxy address proxy; assembly { proxy := create2(0, add(creationCode, 32), mload(creationCode), _salt)} if (proxy == address(0)) revert ErrorCreatingProxy(); // Call proxy with final init code (bool success,) = proxy.call{ value: _value }(_creationCode); if (!success || codeSize(addr) == 0) revert ErrorCreatingContract(); } /** @notice Computes the resulting address of a contract deployed using address(this) and the given `_salt` @param _salt Salt of the contract creation, resulting address will be derivated from this value only @return addr of the deployed contract, reverts on error @dev The address creation formula is: keccak256(rlp([keccak256(0xff ++ address(this) ++ _salt ++ keccak256(childBytecode))[12:], 0x01])) */ function addressOf(bytes32 _salt) internal view returns (address) { address proxy = address( uint160( uint256( keccak256( abi.encodePacked( hex'ff', address(this), _salt, KECCAK256_PROXY_CHILD_BYTECODE ) ) ) ) ); return address( uint160( uint256( keccak256( abi.encodePacked( hex"d6_94", proxy, hex"01" ) ) ) ) ); } }
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {Utils} from "../lib/Utils.sol";
import {Auction} from "../Auction.sol";
import {BondToken} from "../BondToken.sol";
import {Distributor} from "../Distributor.sol";
import {LeverageToken} from "../LeverageToken.sol";
import {PoolFactory} from "../PoolFactory.sol";
import {Create3} from "@create3/contracts/Create3.sol";
import {BeaconProxy} from "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";
/**
* @title Deployer
* @dev Contract for deploying BondToken and LeverageToken instances
*/
contract Deployer {
bytes32 public bondSalt;
bytes32 public leverageSalt;
bytes32 public distributorSalt;
PoolFactory public poolFactory;
error CallerIsNotPoolFactory();
error CallerIsNotSecurityCouncil();
error PoolFactoryAlreadySet();
constructor() {
// Initial salt values (can be anything)
bondSalt = "BOND_SALT";
leverageSalt = "LEVERAGE_SALT";
distributorSalt = "DISTRIBUTOR_SALT";
}
/**
* @dev Deploys a new BondToken contract
* @param bondBeacon The address of the beacon for the BondToken
* @param minter The address with minting privileges
* @param governance The address with governance privileges
* @param sharesPerToken The initial number of shares per token
* @return address of the deployed BondToken contract
*/
function deployBondToken(
address bondBeacon,
string memory name,
string memory symbol,
address minter,
address governance,
address,
uint256 sharesPerToken
) external onlyPoolFactory returns (address) {
bytes memory initData =
abi.encodeCall(BondToken.initialize, (name, symbol, minter, governance, address(poolFactory), sharesPerToken));
address addr =
Create3.create3(bondSalt, abi.encodePacked(type(BeaconProxy).creationCode, abi.encode(bondBeacon, initData)));
bondSalt = bytes32(uint256(uint256(bondSalt) + 1)); // Increment salt for next deployment
return addr;
}
/**
* @dev Deploys a new LeverageToken contract
* @param minter The address with minting privileges
* @param governance The address with governance privileges
* @return address of the deployed LeverageToken contract
*/
function deployLeverageToken(
address leverageBeacon,
string memory name,
string memory symbol,
address minter,
address governance,
address
) external onlyPoolFactory returns (address) {
bytes memory initData =
abi.encodeCall(LeverageToken.initialize, (name, symbol, minter, governance, address(poolFactory)));
address addr = Create3.create3(
leverageSalt, abi.encodePacked(type(BeaconProxy).creationCode, abi.encode(leverageBeacon, initData))
);
leverageSalt = bytes32(uint256(uint256(leverageSalt) + 1)); // Increment salt for next deployment
return addr;
}
function deployDistributor(address distributorBeacon, address pool, address)
external
onlyPoolFactory
returns (address)
{
bytes memory initData = abi.encodeCall(Distributor.initialize, (pool, address(poolFactory)));
address addr = Create3.create3(
distributorSalt, abi.encodePacked(type(BeaconProxy).creationCode, abi.encode(distributorBeacon, initData))
);
distributorSalt = bytes32(uint256(uint256(distributorSalt) + 1)); // Increment salt for next deployment
return addr;
}
/**
* @dev Deploys a new DistributorIntegrationAdapter contract
* @param distributorIntegrationAdapterBeacon The address of the beacon for the DistributorIntegrationAdapter
* @param pool The address of the pool
* @return address of the deployed DistributorIntegrationAdapter contract
*/
function deployDistributorIntegrationAdapter(address distributorIntegrationAdapterBeacon, address pool)
external
returns (address)
{
return address(
new BeaconProxy(
address(distributorIntegrationAdapterBeacon),
abi.encodeCall(Distributor.initialize, (pool, address(poolFactory)))
)
);
}
/**
* @dev Deploys a new Auction contract
* @param pool The address of the pool
* @param couponToken The address of the coupon token
* @param reserveToken The address of the reserve token
* @param couponAmountToDistribute The amount of coupon tokens to distribute
* @param endTime The end time of the auction
* @param maxBids The maximum number of bids
* @param beneficiary The address of the beneficiary
* @param poolSaleLimit The sale limit of the pool
* @return address of the deployed Auction contract
*/
function deployAuction(
address pool,
address couponToken,
address reserveToken,
uint256 couponAmountToDistribute,
uint256 endTime,
uint256 maxBids,
address beneficiary,
uint256 poolSaleLimit
) external returns (address) {
return Utils.deploy(
address(new Auction()),
abi.encodeWithSelector(
Auction.initialize.selector,
pool,
couponToken,
reserveToken,
couponAmountToDistribute,
endTime,
maxBids,
beneficiary,
poolSaleLimit
)
);
}
/**
* @dev Sets the pool factory. We leave the function open but ensure it can only be called once
* (which would be done during deployment)
* @param _poolFactory The address of the pool factory
*/
function setPoolFactory(address _poolFactory) external {
if (address(poolFactory) != address(0)) revert PoolFactoryAlreadySet();
poolFactory = PoolFactory(_poolFactory);
}
function setSalts(bytes32 _bondSalt, bytes32 _leverageSalt, bytes32 _distributorSalt) external onlySecurityCouncil {
bondSalt = _bondSalt;
leverageSalt = _leverageSalt;
distributorSalt = _distributorSalt;
}
function computeBondTokenAddress() external view returns (address) {
return Create3.addressOf(bondSalt);
}
function computeLeverageTokenAddress() external view returns (address) {
return Create3.addressOf(leverageSalt);
}
function computeDistributorAddress() external view returns (address) {
return Create3.addressOf(distributorSalt);
}
function computeAddress(bytes32 salt) external view returns (address) {
return Create3.addressOf(salt);
}
modifier onlyPoolFactory() {
if (msg.sender != address(poolFactory)) revert CallerIsNotPoolFactory();
_;
}
modifier onlySecurityCouncil() {
if (!poolFactory.hasRole(poolFactory.SECURITY_COUNCIL_ROLE(), msg.sender)) revert CallerIsNotSecurityCouncil();
_;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Interface that includes the decimals method
interface ExtendedIERC20 is IERC20 {
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
}
// Library to extend the functionality of IERC20
library ERC20Extensions {
function safeDecimals(IERC20 token) internal view returns (uint8) {
// Try casting the token to the extended interface with decimals()
try ExtendedIERC20(address(token)).decimals() returns (uint8 tokenDecimals) {
return tokenDecimals;
} catch {
// Return a default value if decimals() is not implemented
return 18;
}
}
function safeSymbol(IERC20 token) internal view returns (string memory) {
// Try casting the token to the extended interface with symbol()
try ExtendedIERC20(address(token)).symbol() returns (string memory tokenSymbol) {
return tokenSymbol;
} catch {
// Return a default value if symbol() is not implemented
return "";
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/BeaconProxy.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "./IBeacon.sol";
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
/**
* @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.
*
* The beacon address can only be set once during construction, and cannot be changed afterwards. It is stored in an
* immutable variable to avoid unnecessary storage reads, and also in the beacon storage slot specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] so that it can be accessed externally.
*
* CAUTION: Since the beacon address can never be changed, you must ensure that you either control the beacon, or trust
* the beacon to not upgrade the implementation maliciously.
*
* IMPORTANT: Do not use the implementation logic to modify the beacon storage slot. Doing so would leave the proxy in
* an inconsistent state where the beacon storage slot does not match the beacon address.
*/
contract BeaconProxy is Proxy {
// An immutable address for the beacon to avoid unnecessary SLOADs before each delegate call.
address private immutable _beacon;
/**
* @dev Initializes the proxy with `beacon`.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
* will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity
* constructor.
*
* Requirements:
*
* - `beacon` must be a contract with the interface {IBeacon}.
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address beacon, bytes memory data) payable {
ERC1967Utils.upgradeBeaconToAndCall(beacon, data);
_beacon = beacon;
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation() internal view virtual override returns (address) {
return IBeacon(_getBeacon()).implementation();
}
/**
* @dev Returns the beacon.
*/
function _getBeacon() internal view virtual returns (address) {
return _beacon;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../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;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @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);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// 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 cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import "@openzeppelin/contracts/access/AccessControl.sol";
contract OracleFeeds is AccessControl {
bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE");
// Mapping of token pairs to their price feed addresses
mapping(address => mapping(address => address)) public priceFeeds;
mapping(address => uint256) public feedHeartbeats;
constructor() {
_grantRole(GOV_ROLE, msg.sender);
}
/**
* @dev Sets the price feed for a given token pair
* @param tokenA Address of the first token
* @param tokenB Address of the second token
* @param priceFeed Address of the price feed oracle
*
* Note: address(0) is a special address that represents USD (IRL asset)
*/
function setPriceFeed(address tokenA, address tokenB, address priceFeed, uint256 heartbeat)
external
onlyRole(GOV_ROLE)
{
priceFeeds[tokenA][tokenB] = priceFeed;
if (heartbeat == 0) heartbeat = 1 days;
feedHeartbeats[priceFeed] = heartbeat;
}
/**
* @dev Grants `role` to `account`.
* If `account` had not been already granted `role`, emits a {RoleGranted} event.
* @param role The role to grant
* @param account The account to grant the role to
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(GOV_ROLE) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
* If `account` had been granted `role`, emits a {RoleRevoked} event.
* @param role The role to revoke
* @param account The account to revoke the role from
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(GOV_ROLE) {
_revokeRole(role, account);
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;
import "./BlockTimestamp.sol";
/**
* @title Validator
* @dev Abstract contract that provides a modifier to check transaction deadlines.
*/
abstract contract Validator is BlockTimestamp {
/**
* @dev Custom error to be thrown when a transaction is submitted after its deadline.
*/
error TransactionTooOld();
/**
* @dev Modifier to check if the current block timestamp is before or equal to the given deadline.
* @param deadline The timestamp by which the transaction must be executed.
* @notice This modifier will revert the transaction if the current block timestamp is after the
* deadline.
*/
modifier checkDeadline(uint256 deadline) {
if (_blockTimestamp() > deadline) revert TransactionTooOld();
_;
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {OracleFeeds} from "./OracleFeeds.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
/**
* @title OracleReader
* @dev Contract for reading price data from Chainlink oracles
*/
contract OracleReader {
address public oracleFeeds;
uint256[49] private __gap;
// @note: address(0) is a special address that represents USD (IRL asset)
address public constant USD = address(0);
// @note: special address that represents ETH (Chainlink asset)
address public constant ETH = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/**
* @dev Error thrown when no valid price is found
*/
error NoPriceFound();
/**
* @dev Error thrown when no valid feed is found
*/
error NoFeedFound();
/**
* @dev Error thrown when the price is stale
*/
error StalePrice();
/**
* @dev Error thrown when oracle feeds are aready initialized
*/
error AlreadyInitialized();
/**
* @dev Initializes the contract with the OracleFeeds address
* @param _oracleFeeds Address of the OracleFeeds contract
*/
function __OracleReader_init(address _oracleFeeds) internal {
require(oracleFeeds == address(0), AlreadyInitialized());
oracleFeeds = _oracleFeeds;
}
/**
* @dev Retrieves the latest price from the oracle
* @return price from the oracle
* @dev Reverts if the price data is older than chainlink's heartbeat
*/
function getOraclePrice(address quote, address base) public view returns (uint256) {
bool isInverted = false;
address feed = OracleFeeds(oracleFeeds).priceFeeds(quote, base);
if (feed == address(0)) {
feed = OracleFeeds(oracleFeeds).priceFeeds(base, quote);
if (feed == address(0)) revert NoFeedFound();
// Invert the price
isInverted = true;
}
(, int256 answer,, uint256 updatedTimestamp,) = AggregatorV3Interface(feed).latestRoundData();
if (updatedTimestamp + OracleFeeds(oracleFeeds).feedHeartbeats(feed) < block.timestamp) revert StalePrice();
uint256 decimals = uint256(AggregatorV3Interface(feed).decimals());
return isInverted ? (10 ** decimals * 10 ** decimals) / uint256(answer) : uint256(answer);
}
/**
* @dev Retrieves the number of decimals used in the oracle's price data
* @return decimals Number of decimals used in the price data
*/
function getOracleDecimals(address quote, address base) public view returns (uint8 decimals) {
address feed = OracleFeeds(oracleFeeds).priceFeeds(quote, base);
if (feed == address(0)) {
feed = OracleFeeds(oracleFeeds).priceFeeds(base, quote);
if (feed == address(0)) revert NoFeedFound();
}
return AggregatorV3Interface(feed).decimals();
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Pool} from "../Pool.sol";
import {PoolFactory} from "../PoolFactory.sol";
import {BondToken} from "../BondToken.sol";
import {Decimals} from "../lib/Decimals.sol";
import {BondBaseOftAdapter} from "./BondBaseOftAdapter.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {EnforcedOptionParam} from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OAppOptionsType3.sol";
import {IRouterClient} from "@chainlink/contracts/src/v0.8/ccip/interfaces/IRouterClient.sol";
import {Client} from "@chainlink/contracts/src/v0.8/ccip/libraries/Client.sol";
contract CrossChainController is Initializable, UUPSUpgradeable, PausableUpgradeable {
using Decimals for uint256;
uint256 private constant CCIP_DESTINATION_GAS_LIMIT = 150_000;
struct PoolCrossChainConfig {
address bondOftAdapter;
uint256[] supportedChainIds;
mapping(uint256 => address) remoteDistributors;
}
PoolFactory public poolFactory;
IERC20 private usdc;
IRouterClient private ccipRouter;
/// @dev Mapping to store pool cross chain configs
mapping(address => PoolCrossChainConfig) public poolCrossChainConfigs;
mapping(uint256 => uint32) public chainIdToLzEid;
mapping(uint256 => uint64) public chainIdToCcipChainSelector;
error OnlyGovernance();
error AddOftAdapterFirst();
error OnlyPool();
error OnlyPoolOrGovernance();
error NotEnoughBridgingFees(uint256 available, uint256 required);
event CrossChainSupportAdded(
address indexed pool, address bondOftAdapter, uint256 chainId, uint32 lzEid, address remoteDistributor
);
event CrossChainSupportExtended(address indexed pool, uint256 chainId, uint32 lzEid, address remoteDistributor);
event CrossChainSupportRemoved(address indexed pool, uint256 chainId);
event AllCrossChainSupportRemoved(address indexed pool);
event UsdcSentToRemoteDistributor(bytes32 messageId, uint256 chainId, address remoteDistributor, uint256 usdcAmount);
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(address _poolFactory, address _usdc, address _ccipRouter) external initializer {
poolFactory = PoolFactory(_poolFactory);
usdc = IERC20(_usdc);
ccipRouter = IRouterClient(_ccipRouter);
}
function increaseIndexedAssetPeriodForRemotes(uint256 sharesPerToken) external {
address pool = msg.sender;
if (!_isValidPool(pool)) revert OnlyPool();
PoolCrossChainConfig storage config = poolCrossChainConfigs[pool];
if (config.bondOftAdapter == address(0)) return; // Not configured for cross-chain
// For each supported chain, send the message
uint256[] memory supportedChains = config.supportedChainIds;
for (uint256 i = 0; i < supportedChains.length; i++) {
uint256 chainId = supportedChains[i];
BondBaseOftAdapter(payable(config.bondOftAdapter)).increasePeriodForRemote(
sharesPerToken, chainIdToLzEid[chainId], config.remoteDistributors[chainId]
);
}
}
function zeroLastSharesPerTokenForRemotes() external {
address pool = msg.sender;
if (!_isValidPool(pool)) revert OnlyPool();
PoolCrossChainConfig storage config = poolCrossChainConfigs[pool];
if (config.bondOftAdapter == address(0)) return; // Not configured for cross-chain
// For each supported chain, send the message
uint256[] memory supportedChains = config.supportedChainIds;
for (uint256 i = 0; i < supportedChains.length; i++) {
uint256 chainId = supportedChains[i];
BondBaseOftAdapter(payable(config.bondOftAdapter)).zeroLastSharesForRemotes(
chainIdToLzEid[chainId], config.remoteDistributors[chainId]
);
}
}
/**
* @dev Pool will send USDC first, and then call this function with a low level call. This means that if it fails,
* usdc is temporarily stuck here. We allow this to be called by governance for retry
*/
function sendUsdcToRemoteDistributors(address pool) external {
if (!_isValidPool(msg.sender) && !poolFactory.hasRole(poolFactory.GOV_ROLE(), _msgSender())) {
revert OnlyPoolOrGovernance();
}
PoolCrossChainConfig storage config = poolCrossChainConfigs[pool];
if (config.bondOftAdapter == address(0)) return; // Not configured for cross-chain
// For each supported chain, send USDC via CCIP
uint256[] memory supportedChains = config.supportedChainIds;
for (uint256 i = 0; i < supportedChains.length; i++) {
uint256 chainId = supportedChains[i];
uint64 destinationChainSelector = chainIdToCcipChainSelector[chainId];
address remoteDistributor = config.remoteDistributors[chainId];
// Calculate USDC amount for this chain
uint256 usdcAmount = _getUsdcAmountForChain(pool, chainId);
if (usdcAmount == 0) continue; // Skip if no USDC to send
Client.EVM2AnyMessage memory message = _buildCCIPMessage(remoteDistributor, usdcAmount);
uint256 fees = ccipRouter.getFee(destinationChainSelector, message);
if (fees > address(this).balance) revert NotEnoughBridgingFees(address(this).balance, fees);
// Approve and send
usdc.approve(address(ccipRouter), usdcAmount);
bytes32 messageId = ccipRouter.ccipSend(destinationChainSelector, message);
emit UsdcSentToRemoteDistributor(messageId, chainId, remoteDistributor, usdcAmount);
}
}
function addCrossChainSupport(
address _pool,
address _bondOftAdapter,
uint256 _supportedChainId,
uint32 _supportedLzEid,
uint64 _supportedCcipChainSelector,
address _remoteDistributor
) external onlyGovernance {
PoolCrossChainConfig storage config = poolCrossChainConfigs[_pool];
config.bondOftAdapter = _bondOftAdapter;
config.supportedChainIds.push(_supportedChainId);
config.remoteDistributors[_supportedChainId] = _remoteDistributor;
// Map chain IDs to third party mappings for chains
chainIdToLzEid[_supportedChainId] = _supportedLzEid;
chainIdToCcipChainSelector[_supportedChainId] = _supportedCcipChainSelector;
emit CrossChainSupportAdded(_pool, _bondOftAdapter, _supportedChainId, _supportedLzEid, _remoteDistributor);
}
function extendCrossChainSupport(
address _pool,
uint256 _supportedChainId,
uint32 _supportedLzEid,
uint64 _supportedCcipChainSelector,
address _remoteDistributor
) external onlyGovernance {
PoolCrossChainConfig storage config = poolCrossChainConfigs[_pool];
if (config.bondOftAdapter == address(0)) revert AddOftAdapterFirst();
// Add the chain ID and remote distributor
config.supportedChainIds.push(_supportedChainId);
config.remoteDistributors[_supportedChainId] = _remoteDistributor;
// Map chain IDs to third party mappings for chains
chainIdToLzEid[_supportedChainId] = _supportedLzEid;
chainIdToCcipChainSelector[_supportedChainId] = _supportedCcipChainSelector;
emit CrossChainSupportExtended(_pool, _supportedChainId, _supportedLzEid, _remoteDistributor);
}
function removeCrossChainSupport(address _pool, uint256 _supportedChainId) external onlyGovernance {
PoolCrossChainConfig storage config = poolCrossChainConfigs[_pool];
// Remove the chain ID from the array
uint256[] storage chainIds = config.supportedChainIds;
for (uint256 i = 0; i < chainIds.length; i++) {
if (chainIds[i] == _supportedChainId) {
chainIds[i] = chainIds[chainIds.length - 1];
chainIds.pop();
break;
}
}
// Clear the remote distributor mapping for this chain
delete config.remoteDistributors[_supportedChainId];
// Clear the chain ID mappings
delete chainIdToLzEid[_supportedChainId];
delete chainIdToCcipChainSelector[_supportedChainId];
emit CrossChainSupportRemoved(_pool, _supportedChainId);
}
function removeAllCrossChainSupport(address _pool) external onlyGovernance {
PoolCrossChainConfig storage config = poolCrossChainConfigs[_pool];
// Clear chain ID mappings and remote distributors
for (uint256 i = 0; i < config.supportedChainIds.length; i++) {
uint256 chainId = config.supportedChainIds[i];
delete config.remoteDistributors[chainId];
delete chainIdToLzEid[chainId];
delete chainIdToCcipChainSelector[chainId];
}
// Clear the array and addresses
delete config.supportedChainIds;
delete config.bondOftAdapter;
emit AllCrossChainSupportRemoved(_pool);
}
function getSupportedChains(address _pool) external view returns (uint256[] memory) {
return poolCrossChainConfigs[_pool].supportedChainIds;
}
function getRemoteDistributionAmountForPool(address _pool) external view returns (uint256) {
uint256[] memory supportedChains = poolCrossChainConfigs[_pool].supportedChainIds;
uint256 totalAmount = 0;
for (uint256 i = 0; i < supportedChains.length; i++) {
totalAmount += _getUsdcAmountForChain(_pool, supportedChains[i]);
}
return totalAmount;
}
function _getUsdcAmountForChain(address _pool, uint256 _chainId) internal view returns (uint256) {
// Get remote balance from the BondBaseOftAdapter
PoolCrossChainConfig storage config = poolCrossChainConfigs[_pool];
uint32 lzEid = chainIdToLzEid[_chainId];
BondToken bondToken = Pool(_pool).bondToken();
BondToken.PoolAmount[] memory previousPoolAmounts = bondToken.getPreviousPoolAmounts();
uint256 sharesPerToken = previousPoolAmounts[previousPoolAmounts.length - 1].sharesPerToken;
// Get snapshot balance
uint256 snapshotBalance = BondBaseOftAdapter(payable(config.bondOftAdapter)).snapshotBalance(lzEid);
uint256 amount = (sharesPerToken * snapshotBalance).normalizeAmount(
bondToken.decimals() + bondToken.SHARES_DECIMALS(), bondToken.SHARES_DECIMALS()
);
// Return the snapshot amount
return amount;
}
function _buildCCIPMessage(address _receiver, uint256 _usdcAmount)
private
view
returns (Client.EVM2AnyMessage memory)
{
Client.EVMTokenAmount[] memory tokenAmounts;
if (_usdcAmount == 0) {
tokenAmounts = new Client.EVMTokenAmount[](0);
} else {
tokenAmounts = new Client.EVMTokenAmount[](1);
tokenAmounts[0] = Client.EVMTokenAmount({token: address(usdc), amount: _usdcAmount});
}
return Client.EVM2AnyMessage({
receiver: abi.encode(_receiver),
data: bytes(""),
tokenAmounts: tokenAmounts,
extraArgs: Client._argsToBytes(Client.EVMExtraArgsV1({gasLimit: CCIP_DESTINATION_GAS_LIMIT})),
feeToken: address(0)
});
}
function _isValidPool(address _pool) internal view returns (bool) {
uint256 numberOfPools = poolFactory.poolsLength();
for (uint256 i = 0; i < numberOfPools; i++) {
if (poolFactory.pools(i) == _pool) return true;
}
return false;
}
modifier onlyGovernance() {
if (!poolFactory.hasRole(poolFactory.GOV_ROLE(), _msgSender())) revert OnlyGovernance();
_;
}
function _authorizeUpgrade(address newImplementation) internal override onlyGovernance {}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../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;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._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 {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// 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) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @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 v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @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);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @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 {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
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 {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-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 the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
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 {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.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);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @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.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
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].
*
* CAUTION: See Security Considerations above.
*/
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 v5.0.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError, bytes32) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:storage-location erc7201:openzeppelin.storage.EIP712
struct EIP712Storage {
/// @custom:oz-renamed-from _HASHED_NAME
bytes32 _hashedName;
/// @custom:oz-renamed-from _HASHED_VERSION
bytes32 _hashedVersion;
string _name;
string _version;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;
function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
assembly {
$.slot := EIP712StorageLocation
}
}
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
EIP712Storage storage $ = _getEIP712Storage();
$._name = name;
$._version = version;
// Reset prior values in storage if upgrading
$._hashedName = 0;
$._hashedVersion = 0;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
EIP712Storage storage $ = _getEIP712Storage();
// If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
// and the EIP712 domain is not reliable, as it will be missing name and version.
require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized");
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Name() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._name;
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Version() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._version;
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
*/
function _EIP712NameHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory name = _EIP712Name();
if (bytes(name).length > 0) {
return keccak256(bytes(name));
} else {
// If the name is empty, the contract may have been upgraded without initializing the new storage.
// We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
bytes32 hashedName = $._hashedName;
if (hashedName != 0) {
return hashedName;
} else {
return keccak256("");
}
}
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
*/
function _EIP712VersionHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory version = _EIP712Version();
if (bytes(version).length > 0) {
return keccak256(bytes(version));
} else {
// If the version is empty, the contract may have been upgraded without initializing the new storage.
// We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
bytes32 hashedVersion = $._hashedVersion;
if (hashedVersion != 0) {
return hashedVersion;
} else {
return keccak256("");
}
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides tracking nonces for addresses. Nonces will only increment.
*/
abstract contract NoncesUpgradeable is Initializable {
/**
* @dev The nonce used for an `account` is not the expected current nonce.
*/
error InvalidAccountNonce(address account, uint256 currentNonce);
/// @custom:storage-location erc7201:openzeppelin.storage.Nonces
struct NoncesStorage {
mapping(address account => uint256) _nonces;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Nonces")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant NoncesStorageLocation = 0x5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00;
function _getNoncesStorage() private pure returns (NoncesStorage storage $) {
assembly {
$.slot := NoncesStorageLocation
}
}
function __Nonces_init() internal onlyInitializing {
}
function __Nonces_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns the next unused nonce for an address.
*/
function nonces(address owner) public view virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
return $._nonces[owner];
}
/**
* @dev Consumes a nonce.
*
* Returns the current value and increments nonce.
*/
function _useNonce(address owner) internal virtual returns (uint256) {
NoncesStorage storage $ = _getNoncesStorage();
// For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
// decremented or reset. This guarantees that the nonce never overflows.
unchecked {
// It is important to do x++ and not ++x here.
return $._nonces[owner]++;
}
}
/**
* @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
*/
function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
uint256 current = _useNonce(owner);
if (nonce != current) {
revert InvalidAccountNonce(owner, current);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.20;
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*/
library MerkleProof {
/**
*@dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Calldata version of {verify}
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Calldata version of {processProof}
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = _hashPair(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Calldata version of {multiProofVerify}
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
if (leavesLen + proofLen != totalHashes + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Calldata version of {processMultiProof}.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofLen = proof.length;
uint256 totalHashes = proofFlags.length;
// Check proof validity.
if (leavesLen + proofLen != totalHashes + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](totalHashes);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < totalHashes; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = _hashPair(a, b);
}
if (totalHashes > 0) {
if (proofPos != proofLen) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[totalHashes - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Sorts the pair (a, b) and hashes the result.
*/
function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
/**
* @title Utils
* @dev Library containing utility functions for contract deployment
*/
library Utils {
/**
* @dev Deploys a new upgradeable proxy contract
* @param implementation The address of the implementation contract
* @param initialize The initialization data for the proxy contract
* @return address The address of the newly deployed proxy contract
*/
function deploy(address implementation, bytes memory initialize) internal returns (address) {
ERC1967Proxy proxy = new ERC1967Proxy(implementation, initialize);
return address(proxy);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @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.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
* function and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @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 or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* 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.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @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`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) 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 FailedInnerCall();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.26;
/**
* @title BlockTimestamp
* @dev Abstract contract providing a function to get the current block timestamp.
*/
abstract contract BlockTimestamp {
/**
* @notice Returns the current block timestamp
* @return uint256 The current block timestamp
*/
function _blockTimestamp() internal view virtual returns (uint256) {
return block.timestamp;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(
uint80 _roundId
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {BondToken} from "../BondToken.sol";
import {PoolFactory} from "../PoolFactory.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {OFTAdapterUpgradeable} from "@layerzerolabs/oft-evm-upgradeable/contracts/oft/OFTAdapterUpgradeable.sol";
import {EnforcedOptionParam} from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OAppOptionsType3.sol";
import {IOAppCore} from "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppCore.sol";
import {SendParam} from "@layerzerolabs/oft-evm/contracts/interfaces/IOFT.sol";
import {OptionsBuilder} from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol";
import {MessagingReceipt, MessagingFee} from "@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol";
contract BondBaseOftAdapter is
Initializable,
UUPSUpgradeable,
OwnableUpgradeable,
PausableUpgradeable,
OFTAdapterUpgradeable
{
using OptionsBuilder for bytes;
uint128 public constant GAS_COST_LZ_RECEIVE = 100_000;
uint128 public constant GAS_COST_LZ_COMPOSE = 200_000;
mapping(uint32 => uint256) public remoteBalance;
mapping(uint32 => uint256) public snapshotBalance;
error OnlyCrossChainController();
error OnlyPoolFactory();
error OnlySecurityCouncil();
event IncreasePeriodForRemote(uint32 indexed supportedLzEid, MessagingReceipt receipt);
event ZeroLastSharesForRemote(uint32 indexed supportedLzEid, MessagingReceipt receipt);
constructor(address _token, address _lzEndpoint) OFTAdapterUpgradeable(_token, _lzEndpoint) {
_disableInitializers();
}
function initialize(address _owner) external initializer {
__OFTAdapter_init(_owner);
__Ownable_init(_owner);
}
function increasePeriodForRemote(uint256 sharesPerToken, uint32 _dstEid, address _remoteDistributor)
external
onlyCrossChainController
{
// snapshot the remote balance
snapshotBalance[_dstEid] = remoteBalance[_dstEid];
// send lz message to increase period on remote
bytes memory _message = abi.encodeWithSelector(BondToken.increaseIndexedAssetPeriod.selector, sharesPerToken);
MessagingReceipt memory receipt = _sendLzMessage(_dstEid, _remoteDistributor, _message);
emit IncreasePeriodForRemote(_dstEid, receipt);
}
function zeroLastSharesForRemotes(uint32 _dstEid, address _remoteDistributor) external onlyCrossChainController {
bytes memory _message = abi.encodeWithSelector(BondToken.zeroLastSharesPerToken.selector);
MessagingReceipt memory receipt = _sendLzMessage(_dstEid, _remoteDistributor, _message);
emit ZeroLastSharesForRemote(_dstEid, receipt);
}
function _sendLzMessage(uint32 _dstEid, address _remoteDistributor, bytes memory _message)
internal
returns (MessagingReceipt memory receipt)
{
bytes memory _extraOptions = OptionsBuilder.newOptions().addExecutorLzReceiveOption(GAS_COST_LZ_RECEIVE, 0)
.addExecutorLzComposeOption(0, GAS_COST_LZ_COMPOSE, 0);
// Send a message with dummy 0 value for tokens
SendParam memory sendParam =
SendParam(_dstEid, _addressToBytes32(_remoteDistributor), 0, 0, _extraOptions, _message, "");
MessagingFee memory fee = _quote(_dstEid, _message, _extraOptions, false);
// The gas cost sent in msg.values 10% higher than quoted. This is to account for additional payload length when
// OFTCore appends msg.sender in _buildMsgAndOptions(). This is gated to having sendParam as calldata and not
// memory, making using logic more convoluted than necessary. Instead, we simply pass an additional 10% factor,
// where the extra is refunded back to the OFTAdapter. Actual extra cost is less than 1% of estimated
(receipt,) =
OFTAdapterUpgradeable(address(this)).send{value: fee.nativeFee * 110 / 100}(sendParam, fee, address(this));
return receipt;
}
function _debit(address _from, uint256 _amountLD, uint256 _minAmountLD, uint32 _dstEid)
internal
override
returns (uint256 amountSentLD, uint256 amountReceivedLD)
{
(amountSentLD,) = _debitView(_amountLD, _minAmountLD, _dstEid);
remoteBalance[_dstEid] += amountSentLD;
(amountSentLD, amountReceivedLD) = super._debit(_from, _amountLD, _minAmountLD, _dstEid);
}
function _credit(address _to, uint256 _amountLD, uint32 _srcEid) internal override returns (uint256 amountReceivedLD) {
remoteBalance[_srcEid] -= _amountLD;
amountReceivedLD = super._credit(_to, _amountLD, _srcEid);
}
function _payNative(uint256 _nativeFee) internal view override returns (uint256) {
if (msg.value < _nativeFee) revert NotEnoughNative(msg.value);
return msg.value;
}
function _addressToBytes32(address _addr) private pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
modifier onlyCrossChainController() {
address crossChainController = address(BondToken(address(innerToken)).poolFactory().crossChainController());
if (msg.sender != crossChainController) revert OnlyCrossChainController();
_;
}
modifier onlyPoolFactory() {
if (msg.sender != address(BondToken(address(innerToken)).poolFactory())) revert OnlyPoolFactory();
_;
}
modifier onlySecurityCouncil() {
PoolFactory poolFactory = BondToken(address(innerToken)).poolFactory();
if (!poolFactory.hasRole(poolFactory.SECURITY_COUNCIL_ROLE(), msg.sender)) revert OnlySecurityCouncil();
_;
}
function pause() external onlySecurityCouncil {
_pause();
}
function unpause() external onlySecurityCouncil {
_unpause();
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
receive() external payable {}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IOAppOptionsType3, EnforcedOptionParam } from "../interfaces/IOAppOptionsType3.sol";
/**
* @title OAppOptionsType3
* @dev Abstract contract implementing the IOAppOptionsType3 interface with type 3 options.
*/
abstract contract OAppOptionsType3 is IOAppOptionsType3, Ownable {
uint16 internal constant OPTION_TYPE_3 = 3;
// @dev The "msgType" should be defined in the child contract.
mapping(uint32 eid => mapping(uint16 msgType => bytes enforcedOption)) public enforcedOptions;
/**
* @dev Sets the enforced options for specific endpoint and message type combinations.
* @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.
* @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.
* eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay
* if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().
*/
function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) public virtual onlyOwner {
_setEnforcedOptions(_enforcedOptions);
}
/**
* @dev Sets the enforced options for specific endpoint and message type combinations.
* @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
*
* @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.
* @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.
* eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay
* if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().
*/
function _setEnforcedOptions(EnforcedOptionParam[] memory _enforcedOptions) internal virtual {
for (uint256 i = 0; i < _enforcedOptions.length; i++) {
// @dev Enforced options are only available for optionType 3, as type 1 and 2 dont support combining.
_assertOptionsType3(_enforcedOptions[i].options);
enforcedOptions[_enforcedOptions[i].eid][_enforcedOptions[i].msgType] = _enforcedOptions[i].options;
}
emit EnforcedOptionSet(_enforcedOptions);
}
/**
* @notice Combines options for a given endpoint and message type.
* @param _eid The endpoint ID.
* @param _msgType The OAPP message type.
* @param _extraOptions Additional options passed by the caller.
* @return options The combination of caller specified options AND enforced options.
*
* @dev If there is an enforced lzReceive option:
* - {gasLimit: 200k, msg.value: 1 ether} AND a caller supplies a lzReceive option: {gasLimit: 100k, msg.value: 0.5 ether}
* - The resulting options will be {gasLimit: 300k, msg.value: 1.5 ether} when the message is executed on the remote lzReceive() function.
* @dev This presence of duplicated options is handled off-chain in the verifier/executor.
*/
function combineOptions(
uint32 _eid,
uint16 _msgType,
bytes calldata _extraOptions
) public view virtual returns (bytes memory) {
bytes memory enforced = enforcedOptions[_eid][_msgType];
// No enforced options, pass whatever the caller supplied, even if it's empty or legacy type 1/2 options.
if (enforced.length == 0) return _extraOptions;
// No caller options, return enforced
if (_extraOptions.length == 0) return enforced;
// @dev If caller provided _extraOptions, must be type 3 as its the ONLY type that can be combined.
if (_extraOptions.length >= 2) {
_assertOptionsType3(_extraOptions);
// @dev Remove the first 2 bytes containing the type from the _extraOptions and combine with enforced.
return bytes.concat(enforced, _extraOptions[2:]);
}
// No valid set of options was found.
revert InvalidOptions(_extraOptions);
}
/**
* @dev Internal function to assert that options are of type 3.
* @param _options The options to be checked.
*/
function _assertOptionsType3(bytes memory _options) internal pure virtual {
uint16 optionsType;
assembly {
optionsType := mload(add(_options, 2))
}
if (optionsType != OPTION_TYPE_3) revert InvalidOptions(_options);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {Client} from "../libraries/Client.sol";
interface IRouterClient {
error UnsupportedDestinationChain(uint64 destChainSelector);
error InsufficientFeeTokenAmount();
error InvalidMsgValue();
/// @notice Checks if the given chain ID is supported for sending/receiving.
/// @param destChainSelector The chain to check.
/// @return supported is true if it is supported, false if not.
function isChainSupported(
uint64 destChainSelector
) external view returns (bool supported);
/// @param destinationChainSelector The destination chainSelector.
/// @param message The cross-chain CCIP message including data and/or tokens.
/// @return fee returns execution fee for the message.
/// delivery to destination chain, denominated in the feeToken specified in the message.
/// @dev Reverts with appropriate reason upon invalid message.
function getFee(
uint64 destinationChainSelector,
Client.EVM2AnyMessage memory message
) external view returns (uint256 fee);
/// @notice Request a message to be sent to the destination chain.
/// @param destinationChainSelector The destination chain ID.
/// @param message The cross-chain CCIP message including data and/or tokens.
/// @return messageId The message ID.
/// @dev Note if msg.value is larger than the required fee (from getFee) we accept.
/// the overpayment with no refund.
/// @dev Reverts with appropriate reason upon invalid message.
function ccipSend(
uint64 destinationChainSelector,
Client.EVM2AnyMessage calldata message
) external payable returns (bytes32);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// End consumer library.
library Client {
/// @dev RMN depends on this struct, if changing, please notify the RMN maintainers.
struct EVMTokenAmount {
address token; // token address on the local chain.
uint256 amount; // Amount of tokens.
}
struct Any2EVMMessage {
bytes32 messageId; // MessageId corresponding to ccipSend on source.
uint64 sourceChainSelector; // Source chain selector.
bytes sender; // abi.decode(sender) if coming from an EVM chain.
bytes data; // payload sent in original message.
EVMTokenAmount[] destTokenAmounts; // Tokens and their amounts in their destination chain representation.
}
// If extraArgs is empty bytes, the default is 200k gas limit.
struct EVM2AnyMessage {
bytes receiver; // abi.encode(receiver address) for dest EVM chains.
bytes data; // Data payload.
EVMTokenAmount[] tokenAmounts; // Token transfers.
address feeToken; // Address of feeToken. address(0) means you will send msg.value.
bytes extraArgs; // Populate this with _argsToBytes(EVMExtraArgsV2).
}
// Tag to indicate only a gas limit. Only usable for EVM as destination chain.
bytes4 public constant EVM_EXTRA_ARGS_V1_TAG = 0x97a657c9;
struct EVMExtraArgsV1 {
uint256 gasLimit;
}
function _argsToBytes(
EVMExtraArgsV1 memory extraArgs
) internal pure returns (bytes memory bts) {
return abi.encodeWithSelector(EVM_EXTRA_ARGS_V1_TAG, extraArgs);
}
// Tag to indicate a gas limit (or dest chain equivalent processing units) and Out Of Order Execution. This tag is
// available for multiple chain families. If there is no chain family specific tag, this is the default available
// for a chain.
// Note: not available for Solana VM based chains.
bytes4 public constant GENERIC_EXTRA_ARGS_V2_TAG = 0x181dcf10;
/// @param gasLimit: gas limit for the callback on the destination chain.
/// @param allowOutOfOrderExecution: if true, it indicates that the message can be executed in any order relative to
/// other messages from the same sender. This value's default varies by chain. On some chains, a particular value is
/// enforced, meaning if the expected value is not set, the message request will revert.
/// @dev Fully compatible with the previously existing EVMExtraArgsV2.
struct GenericExtraArgsV2 {
uint256 gasLimit;
bool allowOutOfOrderExecution;
}
// Extra args tag for chains that use the Solana VM.
bytes4 public constant SVM_EXTRA_ARGS_V1_TAG = 0x1f3b3aba;
struct SVMExtraArgsV1 {
uint32 computeUnits;
uint64 accountIsWritableBitmap;
bool allowOutOfOrderExecution;
bytes32 tokenReceiver;
bytes32[] accounts;
}
/// @dev The maximum number of accounts that can be passed in SVMExtraArgs.
uint256 public constant SVM_EXTRA_ARGS_MAX_ACCOUNTS = 64;
function _argsToBytes(
GenericExtraArgsV2 memory extraArgs
) internal pure returns (bytes memory bts) {
return abi.encodeWithSelector(GENERIC_EXTRA_ARGS_V2_TAG, extraArgs);
}
function _svmArgsToBytes(
SVMExtraArgsV1 memory extraArgs
) internal pure returns (bytes memory bts) {
return abi.encodeWithSelector(SVM_EXTRA_ARGS_V1_TAG, extraArgs);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @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:
* ```solidity
* 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(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes 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
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @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
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an EIP-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.20;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.20;
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address implementation, bytes memory _data) payable {
ERC1967Utils.upgradeToAndCall(implementation, _data);
}
/**
* @dev Returns the current implementation address.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _implementation() internal view virtual override returns (address) {
return ERC1967Utils.getImplementation();
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./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);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../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.
*
* The initial owner is set to the address provided by the deployer. 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 {
/// @custom:storage-location erc7201:openzeppelin.storage.Ownable
struct OwnableStorage {
address _owner;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;
function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
assembly {
$.slot := OwnableStorageLocation
}
}
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
function __Ownable_init(address initialOwner) internal onlyInitializing {
__Ownable_init_unchained(initialOwner);
}
function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @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) {
OwnableStorage storage $ = _getOwnableStorage();
return $._owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @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 {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
OwnableStorage storage $ = _getOwnableStorage();
address oldOwner = $._owner;
$._owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IERC20Metadata, IERC20 } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IOFT, OFTCoreUpgradeable } from "./OFTCoreUpgradeable.sol";
/**
* @title OFTAdapter Contract
* @dev OFTAdapter is a contract that adapts an ERC-20 token to the OFT functionality.
*
* @dev For existing ERC20 tokens, this can be used to convert the token to crosschain compatibility.
* @dev WARNING: ONLY 1 of these should exist for a given global mesh,
* unless you make a NON-default implementation of OFT and needs to be done very carefully.
* @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out.
* IF the 'innerToken' applies something like a transfer fee, the default will NOT work...
* a pre/post balance check will need to be done to calculate the amountSentLD/amountReceivedLD.
*/
abstract contract OFTAdapterUpgradeable is OFTCoreUpgradeable {
using SafeERC20 for IERC20;
IERC20 internal immutable innerToken;
/**
* @dev Constructor for the OFTAdapter contract.
* @param _token The address of the ERC-20 token to be adapted.
* @param _lzEndpoint The LayerZero endpoint address.
* @dev _token must implement the IERC20 interface, and include a decimals() function.
*/
constructor(
address _token,
address _lzEndpoint
) OFTCoreUpgradeable(IERC20Metadata(_token).decimals(), _lzEndpoint) {
innerToken = IERC20(_token);
}
/**
* @dev Initializes the OFTAdapter with the provided delegate.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*
* @dev The delegate typically should be set as the owner of the contract.
* @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to
* accommodate the different version of Ownable.
*/
function __OFTAdapter_init(address _delegate) internal onlyInitializing {
__OFTCore_init(_delegate);
}
function __OFTAdapter_init_unchained() internal onlyInitializing {}
/**
* @dev Retrieves the address of the underlying ERC20 implementation.
* @return The address of the adapted ERC-20 token.
*
* @dev In the case of OFTAdapter, address(this) and erc20 are NOT the same contract.
*/
function token() public view returns (address) {
return address(innerToken);
}
/**
* @notice Indicates whether the OFT contract requires approval of the 'token()' to send.
* @return requiresApproval Needs approval of the underlying token implementation.
*
* @dev In the case of default OFTAdapter, approval is required.
* @dev In non-default OFTAdapter contracts with something like mint and burn privileges, it would NOT need approval.
*/
function approvalRequired() external pure virtual returns (bool) {
return true;
}
/**
* @dev Burns tokens from the sender's specified balance, ie. pull method.
* @param _from The address to debit from.
* @param _amountLD The amount of tokens to send in local decimals.
* @param _minAmountLD The minimum amount to send in local decimals.
* @param _dstEid The destination chain ID.
* @return amountSentLD The amount sent in local decimals.
* @return amountReceivedLD The amount received in local decimals on the remote.
*
* @dev msg.sender will need to approve this _amountLD of tokens to be locked inside of the contract.
* @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out.
* IF the 'innerToken' applies something like a transfer fee, the default will NOT work...
* a pre/post balance check will need to be done to calculate the amountReceivedLD.
*/
function _debit(
address _from,
uint256 _amountLD,
uint256 _minAmountLD,
uint32 _dstEid
) internal virtual override returns (uint256 amountSentLD, uint256 amountReceivedLD) {
(amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);
// @dev Lock tokens by moving them into this contract from the caller.
innerToken.safeTransferFrom(_from, address(this), amountSentLD);
}
/**
* @dev Credits tokens to the specified address.
* @param _to The address to credit the tokens to.
* @param _amountLD The amount of tokens to credit in local decimals.
* @dev _srcEid The source chain ID.
* @return amountReceivedLD The amount of tokens ACTUALLY received in local decimals.
*
* @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out.
* IF the 'innerToken' applies something like a transfer fee, the default will NOT work...
* a pre/post balance check will need to be done to calculate the amountReceivedLD.
*/
function _credit(
address _to,
uint256 _amountLD,
uint32 /*_srcEid*/
) internal virtual override returns (uint256 amountReceivedLD) {
// @dev Unlock the tokens and transfer to the recipient.
innerToken.safeTransfer(_to, _amountLD);
// @dev In the case of NON-default OFTAdapter, the amountLD MIGHT not be == amountReceivedLD.
return _amountLD;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { ILayerZeroEndpointV2 } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
/**
* @title IOAppCore
*/
interface IOAppCore {
// Custom error messages
error OnlyPeer(uint32 eid, bytes32 sender);
error NoPeer(uint32 eid);
error InvalidEndpointCall();
error InvalidDelegate();
// Event emitted when a peer (OApp) is set for a corresponding endpoint
event PeerSet(uint32 eid, bytes32 peer);
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*/
function oAppVersion() external view returns (uint64 senderVersion, uint64 receiverVersion);
/**
* @notice Retrieves the LayerZero endpoint associated with the OApp.
* @return iEndpoint The LayerZero endpoint as an interface.
*/
function endpoint() external view returns (ILayerZeroEndpointV2 iEndpoint);
/**
* @notice Retrieves the peer (OApp) associated with a corresponding endpoint.
* @param _eid The endpoint ID.
* @return peer The peer address (OApp instance) associated with the corresponding endpoint.
*/
function peers(uint32 _eid) external view returns (bytes32 peer);
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*/
function setPeer(uint32 _eid, bytes32 _peer) external;
/**
* @notice Sets the delegate address for the OApp Core.
* @param _delegate The address of the delegate to be set.
*/
function setDelegate(address _delegate) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { MessagingReceipt, MessagingFee } from "@layerzerolabs/oapp-evm/contracts/oapp/OAppSender.sol";
/**
* @dev Struct representing token parameters for the OFT send() operation.
*/
struct SendParam {
uint32 dstEid; // Destination endpoint ID.
bytes32 to; // Recipient address.
uint256 amountLD; // Amount to send in local decimals.
uint256 minAmountLD; // Minimum amount to send in local decimals.
bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.
bytes composeMsg; // The composed message for the send() operation.
bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations.
}
/**
* @dev Struct representing OFT limit information.
* @dev These amounts can change dynamically and are up the specific oft implementation.
*/
struct OFTLimit {
uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient.
uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient.
}
/**
* @dev Struct representing OFT receipt information.
*/
struct OFTReceipt {
uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals.
// @dev In non-default implementations, the amountReceivedLD COULD differ from this value.
uint256 amountReceivedLD; // Amount of tokens to be received on the remote side.
}
/**
* @dev Struct representing OFT fee details.
* @dev Future proof mechanism to provide a standardized way to communicate fees to things like a UI.
*/
struct OFTFeeDetail {
int256 feeAmountLD; // Amount of the fee in local decimals.
string description; // Description of the fee.
}
/**
* @title IOFT
* @dev Interface for the OftChain (OFT) token.
* @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well.
* @dev This specific interface ID is '0x02e49c2c'.
*/
interface IOFT {
// Custom error messages
error InvalidLocalDecimals();
error SlippageExceeded(uint256 amountLD, uint256 minAmountLD);
// Events
event OFTSent(
bytes32 indexed guid, // GUID of the OFT message.
uint32 dstEid, // Destination Endpoint ID.
address indexed fromAddress, // Address of the sender on the src chain.
uint256 amountSentLD, // Amount of tokens sent in local decimals.
uint256 amountReceivedLD // Amount of tokens received in local decimals.
);
event OFTReceived(
bytes32 indexed guid, // GUID of the OFT message.
uint32 srcEid, // Source Endpoint ID.
address indexed toAddress, // Address of the recipient on the dst chain.
uint256 amountReceivedLD // Amount of tokens received in local decimals.
);
/**
* @notice Retrieves interfaceID and the version of the OFT.
* @return interfaceId The interface ID.
* @return version The version.
*
* @dev interfaceId: This specific interface ID is '0x02e49c2c'.
* @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.
* @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.
* ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)
*/
function oftVersion() external view returns (bytes4 interfaceId, uint64 version);
/**
* @notice Retrieves the address of the token associated with the OFT.
* @return token The address of the ERC20 token implementation.
*/
function token() external view returns (address);
/**
* @notice Indicates whether the OFT contract requires approval of the 'token()' to send.
* @return requiresApproval Needs approval of the underlying token implementation.
*
* @dev Allows things like wallet implementers to determine integration requirements,
* without understanding the underlying token implementation.
*/
function approvalRequired() external view returns (bool);
/**
* @notice Retrieves the shared decimals of the OFT.
* @return sharedDecimals The shared decimals of the OFT.
*/
function sharedDecimals() external view returns (uint8);
/**
* @notice Provides the fee breakdown and settings data for an OFT. Unused in the default implementation.
* @param _sendParam The parameters for the send operation.
* @return limit The OFT limit information.
* @return oftFeeDetails The details of OFT fees.
* @return receipt The OFT receipt information.
*/
function quoteOFT(
SendParam calldata _sendParam
) external view returns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory);
/**
* @notice Provides a quote for the send() operation.
* @param _sendParam The parameters for the send() operation.
* @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
* @return fee The calculated LayerZero messaging fee from the send() operation.
*
* @dev MessagingFee: LayerZero msg fee
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
*/
function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory);
/**
* @notice Executes the send() operation.
* @param _sendParam The parameters for the send operation.
* @param _fee The fee information supplied by the caller.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess funds from fees etc. on the src.
* @return receipt The LayerZero messaging receipt from the send() operation.
* @return oftReceipt The OFT receipt information.
*
* @dev MessagingReceipt: LayerZero msg receipt
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function send(
SendParam calldata _sendParam,
MessagingFee calldata _fee,
address _refundAddress
) external payable returns (MessagingReceipt memory, OFTReceipt memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { BytesLib } from "solidity-bytes-utils/contracts/BytesLib.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { ExecutorOptions } from "@layerzerolabs/lz-evm-messagelib-v2/contracts/libs/ExecutorOptions.sol";
import { DVNOptions } from "@layerzerolabs/lz-evm-messagelib-v2/contracts/uln/libs/DVNOptions.sol";
/**
* @title OptionsBuilder
* @dev Library for building and encoding various message options.
*/
library OptionsBuilder {
using SafeCast for uint256;
using BytesLib for bytes;
// Constants for options types
uint16 internal constant TYPE_1 = 1; // legacy options type 1
uint16 internal constant TYPE_2 = 2; // legacy options type 2
uint16 internal constant TYPE_3 = 3;
// Custom error message
error InvalidSize(uint256 max, uint256 actual);
error InvalidOptionType(uint16 optionType);
// Modifier to ensure only options of type 3 are used
modifier onlyType3(bytes memory _options) {
if (_options.toUint16(0) != TYPE_3) revert InvalidOptionType(_options.toUint16(0));
_;
}
/**
* @dev Creates a new options container with type 3.
* @return options The newly created options container.
*/
function newOptions() internal pure returns (bytes memory) {
return abi.encodePacked(TYPE_3);
}
/**
* @dev Adds an executor LZ receive option to the existing options.
* @param _options The existing options container.
* @param _gas The gasLimit used on the lzReceive() function in the OApp.
* @param _value The msg.value passed to the lzReceive() function in the OApp.
* @return options The updated options container.
*
* @dev When multiples of this option are added, they are summed by the executor
* eg. if (_gas: 200k, and _value: 1 ether) AND (_gas: 100k, _value: 0.5 ether) are sent in an option to the LayerZeroEndpoint,
* that becomes (300k, 1.5 ether) when the message is executed on the remote lzReceive() function.
*/
function addExecutorLzReceiveOption(
bytes memory _options,
uint128 _gas,
uint128 _value
) internal pure onlyType3(_options) returns (bytes memory) {
bytes memory option = ExecutorOptions.encodeLzReceiveOption(_gas, _value);
return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZRECEIVE, option);
}
/**
* @dev Adds an executor native drop option to the existing options.
* @param _options The existing options container.
* @param _amount The amount for the native value that is airdropped to the 'receiver'.
* @param _receiver The receiver address for the native drop option.
* @return options The updated options container.
*
* @dev When multiples of this option are added, they are summed by the executor on the remote chain.
*/
function addExecutorNativeDropOption(
bytes memory _options,
uint128 _amount,
bytes32 _receiver
) internal pure onlyType3(_options) returns (bytes memory) {
bytes memory option = ExecutorOptions.encodeNativeDropOption(_amount, _receiver);
return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_NATIVE_DROP, option);
}
// /**
// * @dev Adds an executor native drop option to the existing options.
// * @param _options The existing options container.
// * @param _amount The amount for the native value that is airdropped to the 'receiver'.
// * @param _receiver The receiver address for the native drop option.
// * @return options The updated options container.
// *
// * @dev When multiples of this option are added, they are summed by the executor on the remote chain.
// */
function addExecutorLzReadOption(
bytes memory _options,
uint128 _gas,
uint32 _size,
uint128 _value
) internal pure onlyType3(_options) returns (bytes memory) {
bytes memory option = ExecutorOptions.encodeLzReadOption(_gas, _size, _value);
return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZREAD, option);
}
/**
* @dev Adds an executor LZ compose option to the existing options.
* @param _options The existing options container.
* @param _index The index for the lzCompose() function call.
* @param _gas The gasLimit for the lzCompose() function call.
* @param _value The msg.value for the lzCompose() function call.
* @return options The updated options container.
*
* @dev When multiples of this option are added, they are summed PER index by the executor on the remote chain.
* @dev If the OApp sends N lzCompose calls on the remote, you must provide N incremented indexes starting with 0.
* ie. When your remote OApp composes (N = 3) messages, you must set this option for index 0,1,2
*/
function addExecutorLzComposeOption(
bytes memory _options,
uint16 _index,
uint128 _gas,
uint128 _value
) internal pure onlyType3(_options) returns (bytes memory) {
bytes memory option = ExecutorOptions.encodeLzComposeOption(_index, _gas, _value);
return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZCOMPOSE, option);
}
/**
* @dev Adds an executor ordered execution option to the existing options.
* @param _options The existing options container.
* @return options The updated options container.
*/
function addExecutorOrderedExecutionOption(
bytes memory _options
) internal pure onlyType3(_options) returns (bytes memory) {
return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_ORDERED_EXECUTION, bytes(""));
}
/**
* @dev Adds a DVN pre-crime option to the existing options.
* @param _options The existing options container.
* @param _dvnIdx The DVN index for the pre-crime option.
* @return options The updated options container.
*/
function addDVNPreCrimeOption(
bytes memory _options,
uint8 _dvnIdx
) internal pure onlyType3(_options) returns (bytes memory) {
return addDVNOption(_options, _dvnIdx, DVNOptions.OPTION_TYPE_PRECRIME, bytes(""));
}
/**
* @dev Adds an executor option to the existing options.
* @param _options The existing options container.
* @param _optionType The type of the executor option.
* @param _option The encoded data for the executor option.
* @return options The updated options container.
*/
function addExecutorOption(
bytes memory _options,
uint8 _optionType,
bytes memory _option
) internal pure onlyType3(_options) returns (bytes memory) {
return
abi.encodePacked(
_options,
ExecutorOptions.WORKER_ID,
_option.length.toUint16() + 1, // +1 for optionType
_optionType,
_option
);
}
/**
* @dev Adds a DVN option to the existing options.
* @param _options The existing options container.
* @param _dvnIdx The DVN index for the DVN option.
* @param _optionType The type of the DVN option.
* @param _option The encoded data for the DVN option.
* @return options The updated options container.
*/
function addDVNOption(
bytes memory _options,
uint8 _dvnIdx,
uint8 _optionType,
bytes memory _option
) internal pure onlyType3(_options) returns (bytes memory) {
return
abi.encodePacked(
_options,
DVNOptions.WORKER_ID,
_option.length.toUint16() + 2, // +2 for optionType and dvnIdx
_dvnIdx,
_optionType,
_option
);
}
/**
* @dev Encodes legacy options of type 1.
* @param _executionGas The gasLimit value passed to lzReceive().
* @return legacyOptions The encoded legacy options.
*/
function encodeLegacyOptionsType1(uint256 _executionGas) internal pure returns (bytes memory) {
if (_executionGas > type(uint128).max) revert InvalidSize(type(uint128).max, _executionGas);
return abi.encodePacked(TYPE_1, _executionGas);
}
/**
* @dev Encodes legacy options of type 2.
* @param _executionGas The gasLimit value passed to lzReceive().
* @param _nativeForDst The amount of native air dropped to the receiver.
* @param _receiver The _nativeForDst receiver address.
* @return legacyOptions The encoded legacy options of type 2.
*/
function encodeLegacyOptionsType2(
uint256 _executionGas,
uint256 _nativeForDst,
bytes memory _receiver // @dev Use bytes instead of bytes32 in legacy type 2 for _receiver.
) internal pure returns (bytes memory) {
if (_executionGas > type(uint128).max) revert InvalidSize(type(uint128).max, _executionGas);
if (_nativeForDst > type(uint128).max) revert InvalidSize(type(uint128).max, _nativeForDst);
if (_receiver.length > 32) revert InvalidSize(32, _receiver.length);
return abi.encodePacked(TYPE_2, _executionGas, _nativeForDst, _receiver);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
// @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers
// solhint-disable-next-line no-unused-import
import { OAppSender, MessagingFee, MessagingReceipt } from "./OAppSender.sol";
// @dev Import the 'Origin' so it's exposed to OApp implementers
// solhint-disable-next-line no-unused-import
import { OAppReceiver, Origin } from "./OAppReceiver.sol";
import { OAppCore } from "./OAppCore.sol";
/**
* @title OApp
* @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality.
*/
abstract contract OApp is OAppSender, OAppReceiver {
/**
* @dev Constructor to initialize the OApp with the provided endpoint and owner.
* @param _endpoint The address of the LOCAL LayerZero endpoint.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*/
constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {}
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol implementation.
* @return receiverVersion The version of the OAppReceiver.sol implementation.
*/
function oAppVersion()
public
pure
virtual
override(OAppSender, OAppReceiver)
returns (uint64 senderVersion, uint64 receiverVersion)
{
return (SENDER_VERSION, RECEIVER_VERSION);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../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.
*
* The initial owner is set to the address provided by the deployer. 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;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @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 {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @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 {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_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
pragma solidity ^0.8.20;
/**
* @dev Struct representing enforced option parameters.
*/
struct EnforcedOptionParam {
uint32 eid; // Endpoint ID
uint16 msgType; // Message Type
bytes options; // Additional options
}
/**
* @title IOAppOptionsType3
* @dev Interface for the OApp with Type 3 Options, allowing the setting and combining of enforced options.
*/
interface IOAppOptionsType3 {
// Custom error message for invalid options
error InvalidOptions(bytes options);
// Event emitted when enforced options are set
event EnforcedOptionSet(EnforcedOptionParam[] _enforcedOptions);
/**
* @notice Sets enforced options for specific endpoint and message type combinations.
* @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
*/
function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) external;
/**
* @notice Combines options for a given endpoint and message type.
* @param _eid The endpoint ID.
* @param _msgType The OApp message type.
* @param _extraOptions Additional options passed by the caller.
* @return options The combination of caller specified options AND enforced options.
*/
function combineOptions(
uint32 _eid,
uint16 _msgType,
bytes calldata _extraOptions
) external view returns (bytes memory options);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { OAppUpgradeable, Origin } from "@layerzerolabs/oapp-evm-upgradeable/contracts/oapp/OAppUpgradeable.sol";
import { OAppOptionsType3Upgradeable } from "@layerzerolabs/oapp-evm-upgradeable/contracts/oapp/libs/OAppOptionsType3Upgradeable.sol";
import { IOAppMsgInspector } from "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppMsgInspector.sol";
import { OAppPreCrimeSimulatorUpgradeable } from "@layerzerolabs/oapp-evm-upgradeable/contracts/precrime/OAppPreCrimeSimulatorUpgradeable.sol";
import { IOFT, SendParam, OFTLimit, OFTReceipt, OFTFeeDetail, MessagingReceipt, MessagingFee } from "@layerzerolabs/oft-evm/contracts/interfaces/IOFT.sol";
import { OFTMsgCodec } from "@layerzerolabs/oft-evm/contracts/libs/OFTMsgCodec.sol";
import { OFTComposeMsgCodec } from "@layerzerolabs/oft-evm/contracts/libs/OFTComposeMsgCodec.sol";
/**
* @title OFTCore
* @dev Abstract contract for the OftChain (OFT) token.
*/
abstract contract OFTCoreUpgradeable is
IOFT,
OAppUpgradeable,
OAppPreCrimeSimulatorUpgradeable,
OAppOptionsType3Upgradeable
{
using OFTMsgCodec for bytes;
using OFTMsgCodec for bytes32;
struct OFTCoreStorage {
// Address of an optional contract to inspect both 'message' and 'options'
address msgInspector;
}
// keccak256(abi.encode(uint256(keccak256("layerzerov2.storage.oftcore")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OFT_CORE_STORAGE_LOCATION =
0x41db8a78b0206aba5c54bcbfc2bda0d84082a84eb88e680379a57b9e9f653c00;
// @notice Provides a conversion rate when swapping between denominations of SD and LD
// - shareDecimals == SD == shared Decimals
// - localDecimals == LD == local decimals
// @dev Considers that tokens have different decimal amounts on various chains.
// @dev eg.
// For a token
// - locally with 4 decimals --> 1.2345 => uint(12345)
// - remotely with 2 decimals --> 1.23 => uint(123)
// - The conversion rate would be 10 ** (4 - 2) = 100
// @dev If you want to send 1.2345 -> (uint 12345), you CANNOT represent that value on the remote,
// you can only display 1.23 -> uint(123).
// @dev To preserve the dust that would otherwise be lost on that conversion,
// we need to unify a denomination that can be represented on ALL chains inside of the OFT mesh
uint256 public immutable decimalConversionRate;
// @notice Msg types that are used to identify the various OFT operations.
// @dev This can be extended in child contracts for non-default oft operations
// @dev These values are used in things like combineOptions() in OAppOptionsType3.sol.
uint16 public constant SEND = 1;
uint16 public constant SEND_AND_CALL = 2;
event MsgInspectorSet(address inspector);
function _getOFTCoreStorage() internal pure returns (OFTCoreStorage storage $) {
assembly {
$.slot := OFT_CORE_STORAGE_LOCATION
}
}
/**
* @dev Constructor.
* @param _localDecimals The decimals of the token on the local chain (this chain).
* @param _endpoint The address of the LayerZero endpoint.
*/
constructor(uint8 _localDecimals, address _endpoint) OAppUpgradeable(_endpoint) {
if (_localDecimals < sharedDecimals()) revert InvalidLocalDecimals();
decimalConversionRate = 10 ** (_localDecimals - sharedDecimals());
}
/**
* @notice Retrieves interfaceID and the version of the OFT.
* @return interfaceId The interface ID.
* @return version The version.
*
* @dev interfaceId: This specific interface ID is '0x02e49c2c'.
* @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.
* @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.
* ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)
*/
function oftVersion() external pure virtual returns (bytes4 interfaceId, uint64 version) {
return (type(IOFT).interfaceId, 1);
}
/**
* @dev Initializes the OFTCore contract.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*
* @dev The delegate typically should be set as the owner of the contract.
* @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to
* accommodate the different version of Ownable.
*/
function __OFTCore_init(address _delegate) internal onlyInitializing {
__OApp_init(_delegate);
__OAppPreCrimeSimulator_init();
__OAppOptionsType3_init();
}
function __OFTCore_init_unchained() internal onlyInitializing {}
function msgInspector() public view returns (address) {
OFTCoreStorage storage $ = _getOFTCoreStorage();
return $.msgInspector;
}
/**
* @dev Retrieves the shared decimals of the OFT.
* @return The shared decimals of the OFT.
*
* @dev Sets an implicit cap on the amount of tokens, over uint64.max() will need some sort of outbound cap / totalSupply cap
* Lowest common decimal denominator between chains.
* Defaults to 6 decimal places to provide up to 18,446,744,073,709.551615 units (max uint64).
* For tokens exceeding this totalSupply(), they will need to override the sharedDecimals function with something smaller.
* ie. 4 sharedDecimals would be 1,844,674,407,370,955.1615
*/
function sharedDecimals() public pure virtual returns (uint8) {
return 6;
}
/**
* @dev Sets the message inspector address for the OFT.
* @param _msgInspector The address of the message inspector.
*
* @dev This is an optional contract that can be used to inspect both 'message' and 'options'.
* @dev Set it to address(0) to disable it, or set it to a contract address to enable it.
*/
function setMsgInspector(address _msgInspector) public virtual onlyOwner {
OFTCoreStorage storage $ = _getOFTCoreStorage();
$.msgInspector = _msgInspector;
emit MsgInspectorSet(_msgInspector);
}
/**
* @notice Provides a quote for OFT-related operations.
* @param _sendParam The parameters for the send operation.
* @return oftLimit The OFT limit information.
* @return oftFeeDetails The details of OFT fees.
* @return oftReceipt The OFT receipt information.
*/
function quoteOFT(
SendParam calldata _sendParam
)
external
view
virtual
returns (OFTLimit memory oftLimit, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory oftReceipt)
{
uint256 minAmountLD = 0; // Unused in the default implementation.
uint256 maxAmountLD = type(uint64).max; // Unused in the default implementation.
oftLimit = OFTLimit(minAmountLD, maxAmountLD);
// Unused in the default implementation; reserved for future complex fee details.
oftFeeDetails = new OFTFeeDetail[](0);
// @dev This is the same as the send() operation, but without the actual send.
// - amountSentLD is the amount in local decimals that would be sent from the sender.
// - amountReceivedLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance.
// @dev The amountSentLD MIGHT not equal the amount the user actually receives. HOWEVER, the default does.
(uint256 amountSentLD, uint256 amountReceivedLD) = _debitView(
_sendParam.amountLD,
_sendParam.minAmountLD,
_sendParam.dstEid
);
oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);
}
/**
* @notice Provides a quote for the send() operation.
* @param _sendParam The parameters for the send() operation.
* @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
* @return msgFee The calculated LayerZero messaging fee from the send() operation.
*
* @dev MessagingFee: LayerZero msg fee
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
*/
function quoteSend(
SendParam calldata _sendParam,
bool _payInLzToken
) external view virtual returns (MessagingFee memory msgFee) {
// @dev mock the amount to receive, this is the same operation used in the send().
// The quote is as similar as possible to the actual send() operation.
(, uint256 amountReceivedLD) = _debitView(_sendParam.amountLD, _sendParam.minAmountLD, _sendParam.dstEid);
// @dev Builds the options and OFT message to quote in the endpoint.
(bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);
// @dev Calculates the LayerZero fee for the send() operation.
return _quote(_sendParam.dstEid, message, options, _payInLzToken);
}
/**
* @dev Executes the send operation.
* @param _sendParam The parameters for the send operation.
* @param _fee The calculated fee for the send() operation.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess funds.
* @return msgReceipt The receipt for the send operation.
* @return oftReceipt The OFT receipt information.
*
* @dev MessagingReceipt: LayerZero msg receipt
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function send(
SendParam calldata _sendParam,
MessagingFee calldata _fee,
address _refundAddress
) external payable virtual returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) {
// @dev Applies the token transfers regarding this send() operation.
// - amountSentLD is the amount in local decimals that was ACTUALLY sent/debited from the sender.
// - amountReceivedLD is the amount in local decimals that will be received/credited to the recipient on the remote OFT instance.
(uint256 amountSentLD, uint256 amountReceivedLD) = _debit(
msg.sender,
_sendParam.amountLD,
_sendParam.minAmountLD,
_sendParam.dstEid
);
// @dev Builds the options and OFT message to quote in the endpoint.
(bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);
// @dev Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt.
msgReceipt = _lzSend(_sendParam.dstEid, message, options, _fee, _refundAddress);
// @dev Formulate the OFT receipt.
oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);
emit OFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, amountSentLD, amountReceivedLD);
}
/**
* @dev Internal function to build the message and options.
* @param _sendParam The parameters for the send() operation.
* @param _amountLD The amount in local decimals.
* @return message The encoded message.
* @return options The encoded options.
*/
function _buildMsgAndOptions(
SendParam calldata _sendParam,
uint256 _amountLD
) internal view virtual returns (bytes memory message, bytes memory options) {
bool hasCompose;
// @dev This generated message has the msg.sender encoded into the payload so the remote knows who the caller is.
(message, hasCompose) = OFTMsgCodec.encode(
_sendParam.to,
_toSD(_amountLD),
// @dev Must be include a non empty bytes if you want to compose, EVEN if you dont need it on the remote.
// EVEN if you dont require an arbitrary payload to be sent... eg. '0x01'
_sendParam.composeMsg
);
// @dev Change the msg type depending if its composed or not.
uint16 msgType = hasCompose ? SEND_AND_CALL : SEND;
// @dev Combine the callers _extraOptions with the enforced options via the OAppOptionsType3.
options = combineOptions(_sendParam.dstEid, msgType, _sendParam.extraOptions);
OFTCoreStorage storage $ = _getOFTCoreStorage();
// @dev Optionally inspect the message and options depending if the OApp owner has set a msg inspector.
// @dev If it fails inspection, needs to revert in the implementation. ie. does not rely on return boolean
address inspector = $.msgInspector; // caches the msgInspector to avoid potential double storage read
if (inspector != address(0)) IOAppMsgInspector(inspector).inspect(message, options);
}
/**
* @dev Internal function to handle the receive on the LayerZero endpoint.
* @param _origin The origin information.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address from the src chain.
* - nonce: The nonce of the LayerZero message.
* @param _guid The unique identifier for the received LayerZero message.
* @param _message The encoded message.
* @dev _executor The address of the executor.
* @dev _extraData Additional data.
*/
function _lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address /*_executor*/, // @dev unused in the default implementation.
bytes calldata /*_extraData*/ // @dev unused in the default implementation.
) internal virtual override {
// @dev The src sending chain doesnt know the address length on this chain (potentially non-evm)
// Thus everything is bytes32() encoded in flight.
address toAddress = _message.sendTo().bytes32ToAddress();
// @dev Credit the amountLD to the recipient and return the ACTUAL amount the recipient received in local decimals
uint256 amountReceivedLD = _credit(toAddress, _toLD(_message.amountSD()), _origin.srcEid);
if (_message.isComposed()) {
// @dev Proprietary composeMsg format for the OFT.
bytes memory composeMsg = OFTComposeMsgCodec.encode(
_origin.nonce,
_origin.srcEid,
amountReceivedLD,
_message.composeMsg()
);
// @dev Stores the lzCompose payload that will be executed in a separate tx.
// Standardizes functionality for executing arbitrary contract invocation on some non-evm chains.
// @dev The off-chain executor will listen and process the msg based on the src-chain-callers compose options passed.
// @dev The index is used when a OApp needs to compose multiple msgs on lzReceive.
// For default OFT implementation there is only 1 compose msg per lzReceive, thus its always 0.
endpoint.sendCompose(toAddress, _guid, 0 /* the index of the composed message*/, composeMsg);
}
emit OFTReceived(_guid, _origin.srcEid, toAddress, amountReceivedLD);
}
/**
* @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.
* @param _origin The origin information.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address from the src chain.
* - nonce: The nonce of the LayerZero message.
* @param _guid The unique identifier for the received LayerZero message.
* @param _message The LayerZero message.
* @param _executor The address of the off-chain executor.
* @param _extraData Arbitrary data passed by the msg executor.
*
* @dev Enables the preCrime simulator to mock sending lzReceive() messages,
* routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.
*/
function _lzReceiveSimulate(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) internal virtual override {
_lzReceive(_origin, _guid, _message, _executor, _extraData);
}
/**
* @dev Check if the peer is considered 'trusted' by the OApp.
* @param _eid The endpoint ID to check.
* @param _peer The peer to check.
* @return Whether the peer passed is considered 'trusted' by the OApp.
*
* @dev Enables OAppPreCrimeSimulator to check whether a potential Inbound Packet is from a trusted source.
*/
function isPeer(uint32 _eid, bytes32 _peer) public view virtual override returns (bool) {
return peers(_eid) == _peer;
}
/**
* @dev Internal function to remove dust from the given local decimal amount.
* @param _amountLD The amount in local decimals.
* @return amountLD The amount after removing dust.
*
* @dev Prevents the loss of dust when moving amounts between chains with different decimals.
* @dev eg. uint(123) with a conversion rate of 100 becomes uint(100).
*/
function _removeDust(uint256 _amountLD) internal view virtual returns (uint256 amountLD) {
return (_amountLD / decimalConversionRate) * decimalConversionRate;
}
/**
* @dev Internal function to convert an amount from shared decimals into local decimals.
* @param _amountSD The amount in shared decimals.
* @return amountLD The amount in local decimals.
*/
function _toLD(uint64 _amountSD) internal view virtual returns (uint256 amountLD) {
return _amountSD * decimalConversionRate;
}
/**
* @dev Internal function to convert an amount from local decimals into shared decimals.
* @param _amountLD The amount in local decimals.
* @return amountSD The amount in shared decimals.
*/
function _toSD(uint256 _amountLD) internal view virtual returns (uint64 amountSD) {
return uint64(_amountLD / decimalConversionRate);
}
/**
* @dev Internal function to mock the amount mutation from a OFT debit() operation.
* @param _amountLD The amount to send in local decimals.
* @param _minAmountLD The minimum amount to send in local decimals.
* @dev _dstEid The destination endpoint ID.
* @return amountSentLD The amount sent, in local decimals.
* @return amountReceivedLD The amount to be received on the remote chain, in local decimals.
*
* @dev This is where things like fees would be calculated and deducted from the amount to be received on the remote.
*/
function _debitView(
uint256 _amountLD,
uint256 _minAmountLD,
uint32 /*_dstEid*/
) internal view virtual returns (uint256 amountSentLD, uint256 amountReceivedLD) {
// @dev Remove the dust so nothing is lost on the conversion between chains with different decimals for the token.
amountSentLD = _removeDust(_amountLD);
// @dev The amount to send is the same as amount received in the default implementation.
amountReceivedLD = amountSentLD;
// @dev Check for slippage.
if (amountReceivedLD < _minAmountLD) {
revert SlippageExceeded(amountReceivedLD, _minAmountLD);
}
}
/**
* @dev Internal function to perform a debit operation.
* @param _from The address to debit from.
* @param _amountLD The amount to send in local decimals.
* @param _minAmountLD The minimum amount to send in local decimals.
* @param _dstEid The destination endpoint ID.
* @return amountSentLD The amount sent in local decimals.
* @return amountReceivedLD The amount received in local decimals on the remote.
*
* @dev Defined here but are intended to be overriden depending on the OFT implementation.
* @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.
*/
function _debit(
address _from,
uint256 _amountLD,
uint256 _minAmountLD,
uint32 _dstEid
) internal virtual returns (uint256 amountSentLD, uint256 amountReceivedLD);
/**
* @dev Internal function to perform a credit operation.
* @param _to The address to credit.
* @param _amountLD The amount to credit in local decimals.
* @param _srcEid The source endpoint ID.
* @return amountReceivedLD The amount ACTUALLY received in local decimals.
*
* @dev Defined here but are intended to be overriden depending on the OFT implementation.
* @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.
*/
function _credit(
address _to,
uint256 _amountLD,
uint32 _srcEid
) internal virtual returns (uint256 amountReceivedLD);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { IMessageLibManager } from "./IMessageLibManager.sol";
import { IMessagingComposer } from "./IMessagingComposer.sol";
import { IMessagingChannel } from "./IMessagingChannel.sol";
import { IMessagingContext } from "./IMessagingContext.sol";
struct MessagingParams {
uint32 dstEid;
bytes32 receiver;
bytes message;
bytes options;
bool payInLzToken;
}
struct MessagingReceipt {
bytes32 guid;
uint64 nonce;
MessagingFee fee;
}
struct MessagingFee {
uint256 nativeFee;
uint256 lzTokenFee;
}
struct Origin {
uint32 srcEid;
bytes32 sender;
uint64 nonce;
}
interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {
event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);
event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);
event PacketDelivered(Origin origin, address receiver);
event LzReceiveAlert(
address indexed receiver,
address indexed executor,
Origin origin,
bytes32 guid,
uint256 gas,
uint256 value,
bytes message,
bytes extraData,
bytes reason
);
event LzTokenSet(address token);
event DelegateSet(address sender, address delegate);
function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);
function send(
MessagingParams calldata _params,
address _refundAddress
) external payable returns (MessagingReceipt memory);
function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;
function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);
function initializable(Origin calldata _origin, address _receiver) external view returns (bool);
function lzReceive(
Origin calldata _origin,
address _receiver,
bytes32 _guid,
bytes calldata _message,
bytes calldata _extraData
) external payable;
// oapp can burn messages partially by calling this function with its own business logic if messages are verified in order
function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;
function setLzToken(address _lzToken) external;
function lzToken() external view returns (address);
function nativeToken() external view returns (address);
function setDelegate(address _delegate) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MessagingParams, MessagingFee, MessagingReceipt } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { OAppCore } from "./OAppCore.sol";
/**
* @title OAppSender
* @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.
*/
abstract contract OAppSender is OAppCore {
using SafeERC20 for IERC20;
// Custom error messages
error NotEnoughNative(uint256 msgValue);
error LzTokenUnavailable();
// @dev The version of the OAppSender implementation.
// @dev Version is bumped when changes are made to this contract.
uint64 internal constant SENDER_VERSION = 1;
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*
* @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented.
* ie. this is a SEND only OApp.
* @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions
*/
function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
return (SENDER_VERSION, 0);
}
/**
* @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.
* @param _dstEid The destination endpoint ID.
* @param _message The message payload.
* @param _options Additional options for the message.
* @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.
* @return fee The calculated MessagingFee for the message.
* - nativeFee: The native fee for the message.
* - lzTokenFee: The LZ token fee for the message.
*/
function _quote(
uint32 _dstEid,
bytes memory _message,
bytes memory _options,
bool _payInLzToken
) internal view virtual returns (MessagingFee memory fee) {
return
endpoint.quote(
MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken),
address(this)
);
}
/**
* @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message.
* @param _dstEid The destination endpoint ID.
* @param _message The message payload.
* @param _options Additional options for the message.
* @param _fee The calculated LayerZero fee for the message.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess fee values sent to the endpoint.
* @return receipt The receipt for the sent message.
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function _lzSend(
uint32 _dstEid,
bytes memory _message,
bytes memory _options,
MessagingFee memory _fee,
address _refundAddress
) internal virtual returns (MessagingReceipt memory receipt) {
// @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint.
uint256 messageValue = _payNative(_fee.nativeFee);
if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee);
return
// solhint-disable-next-line check-send-result
endpoint.send{ value: messageValue }(
MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0),
_refundAddress
);
}
/**
* @dev Internal function to pay the native fee associated with the message.
* @param _nativeFee The native fee to be paid.
* @return nativeFee The amount of native currency paid.
*
* @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction,
* this will need to be overridden because msg.value would contain multiple lzFees.
* @dev Should be overridden in the event the LayerZero endpoint requires a different native currency.
* @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees.
* @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time.
*/
function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) {
if (msg.value != _nativeFee) revert NotEnoughNative(msg.value);
return _nativeFee;
}
/**
* @dev Internal function to pay the LZ token fee associated with the message.
* @param _lzTokenFee The LZ token fee to be paid.
*
* @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint.
* @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend().
*/
function _payLzToken(uint256 _lzTokenFee) internal virtual {
// @dev Cannot cache the token because it is not immutable in the endpoint.
address lzToken = endpoint.lzToken();
if (lzToken == address(0)) revert LzTokenUnavailable();
// Pay LZ token fee by sending tokens to the endpoint.
IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee);
}
}// 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, uint256 _start, uint256 _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, uint256 _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, uint256 _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, uint256 _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, uint256 _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, uint256 _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, uint256 _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, uint256 _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, uint256 _start) internal pure returns (uint256) { require(_bytes.length >= _start + 32, "toUint256_outOfBounds"); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint256 _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 equal_nonAligned(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 endMinusWord := add(_preBytes, length) let mc := add(_preBytes, 0x20) let cc := add(_postBytes, 0x20) for { // the next line is the loop condition: // while(uint256(mc < endWord) + cb == 2) } eq(add(lt(mc, endMinusWord), 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 } } // Only if still successful // For <1 word tail bytes if gt(success, 0) { // Get the remainder of length/32 // length % 32 = AND(length, 32 - 1) let numTailBytes := and(length, 0x1f) let mcRem := mload(mc) let ccRem := mload(cc) for { let i := 0 // the next line is the loop condition: // while(uint256(i < numTailBytes) + cb == 2) } eq(add(lt(i, numTailBytes), cb), 2) { i := add(i, 1) } { if iszero(eq(byte(i, mcRem), byte(i, ccRem))) { // 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; } }
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
}// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol";
library ExecutorOptions {
using CalldataBytesLib for bytes;
uint8 internal constant WORKER_ID = 1;
uint8 internal constant OPTION_TYPE_LZRECEIVE = 1;
uint8 internal constant OPTION_TYPE_NATIVE_DROP = 2;
uint8 internal constant OPTION_TYPE_LZCOMPOSE = 3;
uint8 internal constant OPTION_TYPE_ORDERED_EXECUTION = 4;
uint8 internal constant OPTION_TYPE_LZREAD = 5;
error Executor_InvalidLzReceiveOption();
error Executor_InvalidNativeDropOption();
error Executor_InvalidLzComposeOption();
error Executor_InvalidLzReadOption();
/// @dev decode the next executor option from the options starting from the specified cursor
/// @param _options [executor_id][executor_option][executor_id][executor_option]...
/// executor_option = [option_size][option_type][option]
/// option_size = len(option_type) + len(option)
/// executor_id: uint8, option_size: uint16, option_type: uint8, option: bytes
/// @param _cursor the cursor to start decoding from
/// @return optionType the type of the option
/// @return option the option of the executor
/// @return cursor the cursor to start decoding the next executor option
function nextExecutorOption(
bytes calldata _options,
uint256 _cursor
) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) {
unchecked {
// skip worker id
cursor = _cursor + 1;
// read option size
uint16 size = _options.toU16(cursor);
cursor += 2;
// read option type
optionType = _options.toU8(cursor);
// startCursor and endCursor are used to slice the option from _options
uint256 startCursor = cursor + 1; // skip option type
uint256 endCursor = cursor + size;
option = _options[startCursor:endCursor];
cursor += size;
}
}
function decodeLzReceiveOption(bytes calldata _option) internal pure returns (uint128 gas, uint128 value) {
if (_option.length != 16 && _option.length != 32) revert Executor_InvalidLzReceiveOption();
gas = _option.toU128(0);
value = _option.length == 32 ? _option.toU128(16) : 0;
}
function decodeNativeDropOption(bytes calldata _option) internal pure returns (uint128 amount, bytes32 receiver) {
if (_option.length != 48) revert Executor_InvalidNativeDropOption();
amount = _option.toU128(0);
receiver = _option.toB32(16);
}
function decodeLzComposeOption(
bytes calldata _option
) internal pure returns (uint16 index, uint128 gas, uint128 value) {
if (_option.length != 18 && _option.length != 34) revert Executor_InvalidLzComposeOption();
index = _option.toU16(0);
gas = _option.toU128(2);
value = _option.length == 34 ? _option.toU128(18) : 0;
}
function decodeLzReadOption(
bytes calldata _option
) internal pure returns (uint128 gas, uint32 calldataSize, uint128 value) {
if (_option.length != 20 && _option.length != 36) revert Executor_InvalidLzReadOption();
gas = _option.toU128(0);
calldataSize = _option.toU32(16);
value = _option.length == 36 ? _option.toU128(20) : 0;
}
function encodeLzReceiveOption(uint128 _gas, uint128 _value) internal pure returns (bytes memory) {
return _value == 0 ? abi.encodePacked(_gas) : abi.encodePacked(_gas, _value);
}
function encodeNativeDropOption(uint128 _amount, bytes32 _receiver) internal pure returns (bytes memory) {
return abi.encodePacked(_amount, _receiver);
}
function encodeLzComposeOption(uint16 _index, uint128 _gas, uint128 _value) internal pure returns (bytes memory) {
return _value == 0 ? abi.encodePacked(_index, _gas) : abi.encodePacked(_index, _gas, _value);
}
function encodeLzReadOption(
uint128 _gas,
uint32 _calldataSize,
uint128 _value
) internal pure returns (bytes memory) {
return _value == 0 ? abi.encodePacked(_gas, _calldataSize) : abi.encodePacked(_gas, _calldataSize, _value);
}
}// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { BytesLib } from "solidity-bytes-utils/contracts/BytesLib.sol";
import { BitMap256 } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/BitMaps.sol";
import { CalldataBytesLib } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol";
library DVNOptions {
using CalldataBytesLib for bytes;
using BytesLib for bytes;
uint8 internal constant WORKER_ID = 2;
uint8 internal constant OPTION_TYPE_PRECRIME = 1;
error DVN_InvalidDVNIdx();
error DVN_InvalidDVNOptions(uint256 cursor);
/// @dev group dvn options by its idx
/// @param _options [dvn_id][dvn_option][dvn_id][dvn_option]...
/// dvn_option = [option_size][dvn_idx][option_type][option]
/// option_size = len(dvn_idx) + len(option_type) + len(option)
/// dvn_id: uint8, dvn_idx: uint8, option_size: uint16, option_type: uint8, option: bytes
/// @return dvnOptions the grouped options, still share the same format of _options
/// @return dvnIndices the dvn indices
function groupDVNOptionsByIdx(
bytes memory _options
) internal pure returns (bytes[] memory dvnOptions, uint8[] memory dvnIndices) {
if (_options.length == 0) return (dvnOptions, dvnIndices);
uint8 numDVNs = getNumDVNs(_options);
// if there is only 1 dvn, we can just return the whole options
if (numDVNs == 1) {
dvnOptions = new bytes[](1);
dvnOptions[0] = _options;
dvnIndices = new uint8[](1);
dvnIndices[0] = _options.toUint8(3); // dvn idx
return (dvnOptions, dvnIndices);
}
// otherwise, we need to group the options by dvn_idx
dvnIndices = new uint8[](numDVNs);
dvnOptions = new bytes[](numDVNs);
unchecked {
uint256 cursor = 0;
uint256 start = 0;
uint8 lastDVNIdx = 255; // 255 is an invalid dvn_idx
while (cursor < _options.length) {
++cursor; // skip worker_id
// optionLength asserted in getNumDVNs (skip check)
uint16 optionLength = _options.toUint16(cursor);
cursor += 2;
// dvnIdx asserted in getNumDVNs (skip check)
uint8 dvnIdx = _options.toUint8(cursor);
// dvnIdx must equal to the lastDVNIdx for the first option
// so it is always skipped in the first option
// this operation slices out options whenever the scan finds a different lastDVNIdx
if (lastDVNIdx == 255) {
lastDVNIdx = dvnIdx;
} else if (dvnIdx != lastDVNIdx) {
uint256 len = cursor - start - 3; // 3 is for worker_id and option_length
bytes memory opt = _options.slice(start, len);
_insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, opt);
// reset the start and lastDVNIdx
start += len;
lastDVNIdx = dvnIdx;
}
cursor += optionLength;
}
// skip check the cursor here because the cursor is asserted in getNumDVNs
// if we have reached the end of the options, we need to process the last dvn
uint256 size = cursor - start;
bytes memory op = _options.slice(start, size);
_insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, op);
// revert dvnIndices to start from 0
for (uint8 i = 0; i < numDVNs; ++i) {
--dvnIndices[i];
}
}
}
function _insertDVNOptions(
bytes[] memory _dvnOptions,
uint8[] memory _dvnIndices,
uint8 _dvnIdx,
bytes memory _newOptions
) internal pure {
// dvnIdx starts from 0 but default value of dvnIndices is 0,
// so we tell if the slot is empty by adding 1 to dvnIdx
if (_dvnIdx == 255) revert DVN_InvalidDVNIdx();
uint8 dvnIdxAdj = _dvnIdx + 1;
for (uint256 j = 0; j < _dvnIndices.length; ++j) {
uint8 index = _dvnIndices[j];
if (dvnIdxAdj == index) {
_dvnOptions[j] = abi.encodePacked(_dvnOptions[j], _newOptions);
break;
} else if (index == 0) {
// empty slot, that means it is the first time we see this dvn
_dvnIndices[j] = dvnIdxAdj;
_dvnOptions[j] = _newOptions;
break;
}
}
}
/// @dev get the number of unique dvns
/// @param _options the format is the same as groupDVNOptionsByIdx
function getNumDVNs(bytes memory _options) internal pure returns (uint8 numDVNs) {
uint256 cursor = 0;
BitMap256 bitmap;
// find number of unique dvn_idx
unchecked {
while (cursor < _options.length) {
++cursor; // skip worker_id
uint16 optionLength = _options.toUint16(cursor);
cursor += 2;
if (optionLength < 2) revert DVN_InvalidDVNOptions(cursor); // at least 1 byte for dvn_idx and 1 byte for option_type
uint8 dvnIdx = _options.toUint8(cursor);
// if dvnIdx is not set, increment numDVNs
// max num of dvns is 255, 255 is an invalid dvn_idx
// The order of the dvnIdx is not required to be sequential, as enforcing the order may weaken
// the composability of the options. e.g. if we refrain from enforcing the order, an OApp that has
// already enforced certain options can append additional options to the end of the enforced
// ones without restrictions.
if (dvnIdx == 255) revert DVN_InvalidDVNIdx();
if (!bitmap.get(dvnIdx)) {
++numDVNs;
bitmap = bitmap.set(dvnIdx);
}
cursor += optionLength;
}
}
if (cursor != _options.length) revert DVN_InvalidDVNOptions(cursor);
}
/// @dev decode the next dvn option from _options starting from the specified cursor
/// @param _options the format is the same as groupDVNOptionsByIdx
/// @param _cursor the cursor to start decoding
/// @return optionType the type of the option
/// @return option the option
/// @return cursor the cursor to start decoding the next option
function nextDVNOption(
bytes calldata _options,
uint256 _cursor
) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) {
unchecked {
// skip worker id
cursor = _cursor + 1;
// read option size
uint16 size = _options.toU16(cursor);
cursor += 2;
// read option type
optionType = _options.toU8(cursor + 1); // skip dvn_idx
// startCursor and endCursor are used to slice the option from _options
uint256 startCursor = cursor + 2; // skip option type and dvn_idx
uint256 endCursor = cursor + size;
option = _options[startCursor:endCursor];
cursor += size;
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IOAppReceiver, Origin } from "./interfaces/IOAppReceiver.sol";
import { OAppCore } from "./OAppCore.sol";
/**
* @title OAppReceiver
* @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers.
*/
abstract contract OAppReceiver is IOAppReceiver, OAppCore {
// Custom error message for when the caller is not the registered endpoint/
error OnlyEndpoint(address addr);
// @dev The version of the OAppReceiver implementation.
// @dev Version is bumped when changes are made to this contract.
uint64 internal constant RECEIVER_VERSION = 2;
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*
* @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented.
* ie. this is a RECEIVE only OApp.
* @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions.
*/
function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
return (0, RECEIVER_VERSION);
}
/**
* @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.
* @dev _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @dev _message The lzReceive payload.
* @param _sender The sender address.
* @return isSender Is a valid sender.
*
* @dev Applications can optionally choose to implement separate composeMsg senders that are NOT the bridging layer.
* @dev The default sender IS the OAppReceiver implementer.
*/
function isComposeMsgSender(
Origin calldata /*_origin*/,
bytes calldata /*_message*/,
address _sender
) public view virtual returns (bool) {
return _sender == address(this);
}
/**
* @notice Checks if the path initialization is allowed based on the provided origin.
* @param origin The origin information containing the source endpoint and sender address.
* @return Whether the path has been initialized.
*
* @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received.
* @dev This defaults to assuming if a peer has been set, its initialized.
* Can be overridden by the OApp if there is other logic to determine this.
*/
function allowInitializePath(Origin calldata origin) public view virtual returns (bool) {
return peers[origin.srcEid] == origin.sender;
}
/**
* @notice Retrieves the next nonce for a given source endpoint and sender address.
* @dev _srcEid The source endpoint ID.
* @dev _sender The sender address.
* @return nonce The next nonce.
*
* @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement.
* @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered.
* @dev This is also enforced by the OApp.
* @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.
*/
function nextNonce(uint32 /*_srcEid*/, bytes32 /*_sender*/) public view virtual returns (uint64 nonce) {
return 0;
}
/**
* @dev Entry point for receiving messages or packets from the endpoint.
* @param _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @param _guid The unique identifier for the received LayerZero message.
* @param _message The payload of the received message.
* @param _executor The address of the executor for the received message.
* @param _extraData Additional arbitrary data provided by the corresponding executor.
*
* @dev Entry point for receiving msg/packet from the LayerZero endpoint.
*/
function lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) public payable virtual {
// Ensures that only the endpoint can attempt to lzReceive() messages to this OApp.
if (address(endpoint) != msg.sender) revert OnlyEndpoint(msg.sender);
// Ensure that the sender matches the expected peer for the source endpoint.
if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender);
// Call the internal OApp implementation of lzReceive.
_lzReceive(_origin, _guid, _message, _executor, _extraData);
}
/**
* @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation.
*/
function _lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) internal virtual;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IOAppCore, ILayerZeroEndpointV2 } from "./interfaces/IOAppCore.sol";
/**
* @title OAppCore
* @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.
*/
abstract contract OAppCore is IOAppCore, Ownable {
// The LayerZero endpoint associated with the given OApp
ILayerZeroEndpointV2 public immutable endpoint;
// Mapping to store peers associated with corresponding endpoints
mapping(uint32 eid => bytes32 peer) public peers;
/**
* @dev Constructor to initialize the OAppCore with the provided endpoint and delegate.
* @param _endpoint The address of the LOCAL Layer Zero endpoint.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*
* @dev The delegate typically should be set as the owner of the contract.
*/
constructor(address _endpoint, address _delegate) {
endpoint = ILayerZeroEndpointV2(_endpoint);
if (_delegate == address(0)) revert InvalidDelegate();
endpoint.setDelegate(_delegate);
}
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
* @dev Set this to bytes32(0) to remove the peer address.
* @dev Peer is a bytes32 to accommodate non-evm chains.
*/
function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner {
_setPeer(_eid, _peer);
}
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*
* @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
* @dev Set this to bytes32(0) to remove the peer address.
* @dev Peer is a bytes32 to accommodate non-evm chains.
*/
function _setPeer(uint32 _eid, bytes32 _peer) internal virtual {
peers[_eid] = _peer;
emit PeerSet(_eid, _peer);
}
/**
* @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set.
* ie. the peer is set to bytes32(0).
* @param _eid The endpoint ID.
* @return peer The address of the peer associated with the specified endpoint.
*/
function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) {
bytes32 peer = peers[_eid];
if (peer == bytes32(0)) revert NoPeer(_eid);
return peer;
}
/**
* @notice Sets the delegate address for the OApp.
* @param _delegate The address of the delegate to be set.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract.
*/
function setDelegate(address _delegate) public onlyOwner {
endpoint.setDelegate(_delegate);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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 towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// (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 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 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.
uint256 twos = denominator & (0 - denominator);
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 (unsignedRoundsUp(rounding) && 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
* towards zero.
*
* 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* 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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* 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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* 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 256, 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
// @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers
// solhint-disable-next-line no-unused-import
import { OAppSenderUpgradeable, MessagingFee, MessagingReceipt } from "./OAppSenderUpgradeable.sol";
// @dev Import the 'Origin' so it's exposed to OApp implementers
// solhint-disable-next-line no-unused-import
import { OAppReceiverUpgradeable, Origin } from "./OAppReceiverUpgradeable.sol";
import { OAppCoreUpgradeable } from "./OAppCoreUpgradeable.sol";
/**
* @title OApp
* @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality.
*/
abstract contract OAppUpgradeable is OAppSenderUpgradeable, OAppReceiverUpgradeable {
/**
* @dev Constructor to initialize the OApp with the provided endpoint and owner.
* @param _endpoint The address of the LOCAL LayerZero endpoint.
*/
constructor(address _endpoint) OAppCoreUpgradeable(_endpoint) {}
/**
* @dev Initializes the OApp with the provided delegate.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*
* @dev The delegate typically should be set as the owner of the contract.
* @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to
* accommodate the different version of Ownable.
*/
function __OApp_init(address _delegate) internal onlyInitializing {
__OAppCore_init(_delegate);
__OAppReceiver_init_unchained();
__OAppSender_init_unchained();
}
function __OApp_init_unchained() internal onlyInitializing {}
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol implementation.
* @return receiverVersion The version of the OAppReceiver.sol implementation.
*/
function oAppVersion()
public
pure
virtual
override(OAppSenderUpgradeable, OAppReceiverUpgradeable)
returns (uint64 senderVersion, uint64 receiverVersion)
{
return (SENDER_VERSION, RECEIVER_VERSION);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { IOAppOptionsType3, EnforcedOptionParam } from "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppOptionsType3.sol";
/**
* @title OAppOptionsType3
* @dev Abstract contract implementing the IOAppOptionsType3 interface with type 3 options.
*/
abstract contract OAppOptionsType3Upgradeable is IOAppOptionsType3, OwnableUpgradeable {
struct OAppOptionsType3Storage {
// @dev The "msgType" should be defined in the child contract.
mapping(uint32 => mapping(uint16 => bytes)) enforcedOptions;
}
// keccak256(abi.encode(uint256(keccak256("layerzerov2.storage.oappoptionstype3")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OAPP_OPTIONS_TYPE_3_STORAGE_LOCATION =
0x8d2bda5d9f6ffb5796910376005392955773acee5548d0fcdb10e7c264ea0000;
uint16 internal constant OPTION_TYPE_3 = 3;
function _getOAppOptionsType3Storage() internal pure returns (OAppOptionsType3Storage storage $) {
assembly {
$.slot := OAPP_OPTIONS_TYPE_3_STORAGE_LOCATION
}
}
/**
* @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to
* accommodate the different version of Ownable.
*/
function __OAppOptionsType3_init() internal onlyInitializing {}
function __OAppOptionsType3_init_unchained() internal onlyInitializing {}
function enforcedOptions(uint32 _eid, uint16 _msgType) public view returns (bytes memory) {
OAppOptionsType3Storage storage $ = _getOAppOptionsType3Storage();
return $.enforcedOptions[_eid][_msgType];
}
/**
* @dev Sets the enforced options for specific endpoint and message type combinations.
* @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.
* @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.
* eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay
* if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().
*/
function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) public virtual onlyOwner {
OAppOptionsType3Storage storage $ = _getOAppOptionsType3Storage();
for (uint256 i = 0; i < _enforcedOptions.length; i++) {
// @dev Enforced options are only available for optionType 3, as type 1 and 2 dont support combining.
_assertOptionsType3(_enforcedOptions[i].options);
$.enforcedOptions[_enforcedOptions[i].eid][_enforcedOptions[i].msgType] = _enforcedOptions[i].options;
}
emit EnforcedOptionSet(_enforcedOptions);
}
/**
* @notice Combines options for a given endpoint and message type.
* @param _eid The endpoint ID.
* @param _msgType The OAPP message type.
* @param _extraOptions Additional options passed by the caller.
* @return options The combination of caller specified options AND enforced options.
*
* @dev If there is an enforced lzReceive option:
* - {gasLimit: 200k, msg.value: 1 ether} AND a caller supplies a lzReceive option: {gasLimit: 100k, msg.value: 0.5 ether}
* - The resulting options will be {gasLimit: 300k, msg.value: 1.5 ether} when the message is executed on the remote lzReceive() function.
* @dev This presence of duplicated options is handled off-chain in the verifier/executor.
*/
function combineOptions(
uint32 _eid,
uint16 _msgType,
bytes calldata _extraOptions
) public view virtual returns (bytes memory) {
OAppOptionsType3Storage storage $ = _getOAppOptionsType3Storage();
bytes memory enforced = $.enforcedOptions[_eid][_msgType];
// No enforced options, pass whatever the caller supplied, even if it's empty or legacy type 1/2 options.
if (enforced.length == 0) return _extraOptions;
// No caller options, return enforced
if (_extraOptions.length == 0) return enforced;
// @dev If caller provided _extraOptions, must be type 3 as its the ONLY type that can be combined.
if (_extraOptions.length >= 2) {
_assertOptionsType3(_extraOptions);
// @dev Remove the first 2 bytes containing the type from the _extraOptions and combine with enforced.
return bytes.concat(enforced, _extraOptions[2:]);
}
// No valid set of options was found.
revert InvalidOptions(_extraOptions);
}
/**
* @dev Internal function to assert that options are of type 3.
* @param _options The options to be checked.
*/
function _assertOptionsType3(bytes calldata _options) internal pure virtual {
uint16 optionsType = uint16(bytes2(_options[0:2]));
if (optionsType != OPTION_TYPE_3) revert InvalidOptions(_options);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title IOAppMsgInspector
* @dev Interface for the OApp Message Inspector, allowing examination of message and options contents.
*/
interface IOAppMsgInspector {
// Custom error message for inspection failure
error InspectionFailed(bytes message, bytes options);
/**
* @notice Allows the inspector to examine LayerZero message contents and optionally throw a revert if invalid.
* @param _message The message payload to be inspected.
* @param _options Additional options or parameters for inspection.
* @return valid A boolean indicating whether the inspection passed (true) or failed (false).
*
* @dev Optionally done as a revert, OR use the boolean provided to handle the failure.
*/
function inspect(bytes calldata _message, bytes calldata _options) external view returns (bool valid);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { IPreCrime } from "@layerzerolabs/oapp-evm/contracts/precrime/interfaces/IPreCrime.sol";
import { IOAppPreCrimeSimulator, InboundPacket, Origin } from "@layerzerolabs/oapp-evm/contracts/precrime/interfaces/IOAppPreCrimeSimulator.sol";
/**
* @title OAppPreCrimeSimulator
* @dev Abstract contract serving as the base for preCrime simulation functionality in an OApp.
*/
abstract contract OAppPreCrimeSimulatorUpgradeable is IOAppPreCrimeSimulator, OwnableUpgradeable {
struct OAppPreCrimeSimulatorStorage {
// The address of the preCrime implementation.
address preCrime;
}
// keccak256(abi.encode(uint256(keccak256("layerzerov2.storage.oappprecrimesimulator")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OAPP_PRE_CRIME_SIMULATOR_STORAGE_LOCATION =
0xefb041d771d6daaa55702fff6eb740d63ba559a75d2d1d3e151c78ff2480b600;
function _getOAppPreCrimeSimulatorStorage() internal pure returns (OAppPreCrimeSimulatorStorage storage $) {
assembly {
$.slot := OAPP_PRE_CRIME_SIMULATOR_STORAGE_LOCATION
}
}
/**
* @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to
* accommodate the different version of Ownable.
*/
function __OAppPreCrimeSimulator_init() internal onlyInitializing {}
function __OAppPreCrimeSimulator_init_unchained() internal onlyInitializing {}
function preCrime() external view override returns (address) {
OAppPreCrimeSimulatorStorage storage $ = _getOAppPreCrimeSimulatorStorage();
return $.preCrime;
}
/**
* @dev Retrieves the address of the OApp contract.
* @return The address of the OApp contract.
*
* @dev The simulator contract is the base contract for the OApp by default.
* @dev If the simulator is a separate contract, override this function.
*/
function oApp() external view virtual returns (address) {
return address(this);
}
/**
* @dev Sets the preCrime contract address.
* @param _preCrime The address of the preCrime contract.
*/
function setPreCrime(address _preCrime) public virtual onlyOwner {
OAppPreCrimeSimulatorStorage storage $ = _getOAppPreCrimeSimulatorStorage();
$.preCrime = _preCrime;
emit PreCrimeSet(_preCrime);
}
/**
* @dev Interface for pre-crime simulations. Always reverts at the end with the simulation results.
* @param _packets An array of InboundPacket objects representing received packets to be delivered.
*
* @dev WARNING: MUST revert at the end with the simulation results.
* @dev Gives the preCrime implementation the ability to mock sending packets to the lzReceive function,
* WITHOUT actually executing them.
*/
function lzReceiveAndRevert(InboundPacket[] calldata _packets) public payable virtual {
for (uint256 i = 0; i < _packets.length; i++) {
InboundPacket calldata packet = _packets[i];
// Ignore packets that are not from trusted peers.
if (!isPeer(packet.origin.srcEid, packet.origin.sender)) continue;
// @dev Because a verifier is calling this function, it doesnt have access to executor params:
// - address _executor
// - bytes calldata _extraData
// preCrime will NOT work for OApps that rely on these two parameters inside of their _lzReceive().
// They are instead stubbed to default values, address(0) and bytes("")
// @dev Calling this.lzReceiveSimulate removes ability for assembly return 0 callstack exit,
// which would cause the revert to be ignored.
this.lzReceiveSimulate{ value: packet.value }(
packet.origin,
packet.guid,
packet.message,
packet.executor,
packet.extraData
);
}
// @dev Revert with the simulation results. msg.sender must implement IPreCrime.buildSimulationResult().
revert SimulationResult(IPreCrime(msg.sender).buildSimulationResult());
}
/**
* @dev Is effectively an internal function because msg.sender must be address(this).
* Allows resetting the call stack for 'internal' calls.
* @param _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @param _guid The unique identifier of the packet.
* @param _message The message payload of the packet.
* @param _executor The executor address for the packet.
* @param _extraData Additional data for the packet.
*/
function lzReceiveSimulate(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) external payable virtual {
// @dev Ensure ONLY can be called 'internally'.
if (msg.sender != address(this)) revert OnlySelf();
_lzReceiveSimulate(_origin, _guid, _message, _executor, _extraData);
}
/**
* @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.
* @param _origin The origin information.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address from the src chain.
* - nonce: The nonce of the LayerZero message.
* @param _guid The GUID of the LayerZero message.
* @param _message The LayerZero message.
* @param _executor The address of the off-chain executor.
* @param _extraData Arbitrary data passed by the msg executor.
*
* @dev Enables the preCrime simulator to mock sending lzReceive() messages,
* routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.
*/
function _lzReceiveSimulate(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) internal virtual;
/**
* @dev checks if the specified peer is considered 'trusted' by the OApp.
* @param _eid The endpoint Id to check.
* @param _peer The peer to check.
* @return Whether the peer passed is considered 'trusted' by the OApp.
*/
function isPeer(uint32 _eid, bytes32 _peer) public view virtual returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library OFTMsgCodec {
// Offset constants for encoding and decoding OFT messages
uint8 private constant SEND_TO_OFFSET = 32;
uint8 private constant SEND_AMOUNT_SD_OFFSET = 40;
/**
* @dev Encodes an OFT LayerZero message.
* @param _sendTo The recipient address.
* @param _amountShared The amount in shared decimals.
* @param _composeMsg The composed message.
* @return _msg The encoded message.
* @return hasCompose A boolean indicating whether the message has a composed payload.
*/
function encode(
bytes32 _sendTo,
uint64 _amountShared,
bytes memory _composeMsg
) internal view returns (bytes memory _msg, bool hasCompose) {
hasCompose = _composeMsg.length > 0;
// @dev Remote chains will want to know the composed function caller ie. msg.sender on the src.
_msg = hasCompose
? abi.encodePacked(_sendTo, _amountShared, addressToBytes32(msg.sender), _composeMsg)
: abi.encodePacked(_sendTo, _amountShared);
}
/**
* @dev Checks if the OFT message is composed.
* @param _msg The OFT message.
* @return A boolean indicating whether the message is composed.
*/
function isComposed(bytes calldata _msg) internal pure returns (bool) {
return _msg.length > SEND_AMOUNT_SD_OFFSET;
}
/**
* @dev Retrieves the recipient address from the OFT message.
* @param _msg The OFT message.
* @return The recipient address.
*/
function sendTo(bytes calldata _msg) internal pure returns (bytes32) {
return bytes32(_msg[:SEND_TO_OFFSET]);
}
/**
* @dev Retrieves the amount in shared decimals from the OFT message.
* @param _msg The OFT message.
* @return The amount in shared decimals.
*/
function amountSD(bytes calldata _msg) internal pure returns (uint64) {
return uint64(bytes8(_msg[SEND_TO_OFFSET:SEND_AMOUNT_SD_OFFSET]));
}
/**
* @dev Retrieves the composed message from the OFT message.
* @param _msg The OFT message.
* @return The composed message.
*/
function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {
return _msg[SEND_AMOUNT_SD_OFFSET:];
}
/**
* @dev Converts an address to bytes32.
* @param _addr The address to convert.
* @return The bytes32 representation of the address.
*/
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
/**
* @dev Converts bytes32 to an address.
* @param _b The bytes32 value to convert.
* @return The address representation of bytes32.
*/
function bytes32ToAddress(bytes32 _b) internal pure returns (address) {
return address(uint160(uint256(_b)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library OFTComposeMsgCodec {
// Offset constants for decoding composed messages
uint8 private constant NONCE_OFFSET = 8;
uint8 private constant SRC_EID_OFFSET = 12;
uint8 private constant AMOUNT_LD_OFFSET = 44;
uint8 private constant COMPOSE_FROM_OFFSET = 76;
/**
* @dev Encodes a OFT composed message.
* @param _nonce The nonce value.
* @param _srcEid The source endpoint ID.
* @param _amountLD The amount in local decimals.
* @param _composeMsg The composed message.
* @return _msg The encoded Composed message.
*/
function encode(
uint64 _nonce,
uint32 _srcEid,
uint256 _amountLD,
bytes memory _composeMsg // 0x[composeFrom][composeMsg]
) internal pure returns (bytes memory _msg) {
_msg = abi.encodePacked(_nonce, _srcEid, _amountLD, _composeMsg);
}
/**
* @dev Retrieves the nonce for the composed message.
* @param _msg The message.
* @return The nonce value.
*/
function nonce(bytes calldata _msg) internal pure returns (uint64) {
return uint64(bytes8(_msg[:NONCE_OFFSET]));
}
/**
* @dev Retrieves the source endpoint ID for the composed message.
* @param _msg The message.
* @return The source endpoint ID.
*/
function srcEid(bytes calldata _msg) internal pure returns (uint32) {
return uint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET]));
}
/**
* @dev Retrieves the amount in local decimals from the composed message.
* @param _msg The message.
* @return The amount in local decimals.
*/
function amountLD(bytes calldata _msg) internal pure returns (uint256) {
return uint256(bytes32(_msg[SRC_EID_OFFSET:AMOUNT_LD_OFFSET]));
}
/**
* @dev Retrieves the composeFrom value from the composed message.
* @param _msg The message.
* @return The composeFrom value.
*/
function composeFrom(bytes calldata _msg) internal pure returns (bytes32) {
return bytes32(_msg[AMOUNT_LD_OFFSET:COMPOSE_FROM_OFFSET]);
}
/**
* @dev Retrieves the composed message.
* @param _msg The message.
* @return The composed message.
*/
function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {
return _msg[COMPOSE_FROM_OFFSET:];
}
/**
* @dev Converts an address to bytes32.
* @param _addr The address to convert.
* @return The bytes32 representation of the address.
*/
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
/**
* @dev Converts bytes32 to an address.
* @param _b The bytes32 value to convert.
* @return The address representation of bytes32.
*/
function bytes32ToAddress(bytes32 _b) internal pure returns (address) {
return address(uint160(uint256(_b)));
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
struct SetConfigParam {
uint32 eid;
uint32 configType;
bytes config;
}
interface IMessageLibManager {
struct Timeout {
address lib;
uint256 expiry;
}
event LibraryRegistered(address newLib);
event DefaultSendLibrarySet(uint32 eid, address newLib);
event DefaultReceiveLibrarySet(uint32 eid, address newLib);
event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);
event SendLibrarySet(address sender, uint32 eid, address newLib);
event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);
event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);
function registerLibrary(address _lib) external;
function isRegisteredLibrary(address _lib) external view returns (bool);
function getRegisteredLibraries() external view returns (address[] memory);
function setDefaultSendLibrary(uint32 _eid, address _newLib) external;
function defaultSendLibrary(uint32 _eid) external view returns (address);
function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _timeout) external;
function defaultReceiveLibrary(uint32 _eid) external view returns (address);
function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;
function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);
function isSupportedEid(uint32 _eid) external view returns (bool);
function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);
/// ------------------- OApp interfaces -------------------
function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;
function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);
function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);
function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;
function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);
function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _gracePeriod) external;
function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);
function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;
function getConfig(
address _oapp,
address _lib,
uint32 _eid,
uint32 _configType
) external view returns (bytes memory config);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingComposer {
event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);
event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);
event LzComposeAlert(
address indexed from,
address indexed to,
address indexed executor,
bytes32 guid,
uint16 index,
uint256 gas,
uint256 value,
bytes message,
bytes extraData,
bytes reason
);
function composeQueue(
address _from,
address _to,
bytes32 _guid,
uint16 _index
) external view returns (bytes32 messageHash);
function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;
function lzCompose(
address _from,
address _to,
bytes32 _guid,
uint16 _index,
bytes calldata _message,
bytes calldata _extraData
) external payable;
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingChannel {
event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);
event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
function eid() external view returns (uint32);
// this is an emergency function if a message cannot be verified for some reasons
// required to provide _nextNonce to avoid race condition
function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;
function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);
function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);
function inboundPayloadHash(
address _receiver,
uint32 _srcEid,
bytes32 _sender,
uint64 _nonce
) external view returns (bytes32);
function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingContext {
function isSendingMessage() external view returns (bool);
function getSendContext() external view returns (uint32 dstEid, address sender);
}// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
library CalldataBytesLib {
function toU8(bytes calldata _bytes, uint256 _start) internal pure returns (uint8) {
return uint8(_bytes[_start]);
}
function toU16(bytes calldata _bytes, uint256 _start) internal pure returns (uint16) {
unchecked {
uint256 end = _start + 2;
return uint16(bytes2(_bytes[_start:end]));
}
}
function toU32(bytes calldata _bytes, uint256 _start) internal pure returns (uint32) {
unchecked {
uint256 end = _start + 4;
return uint32(bytes4(_bytes[_start:end]));
}
}
function toU64(bytes calldata _bytes, uint256 _start) internal pure returns (uint64) {
unchecked {
uint256 end = _start + 8;
return uint64(bytes8(_bytes[_start:end]));
}
}
function toU128(bytes calldata _bytes, uint256 _start) internal pure returns (uint128) {
unchecked {
uint256 end = _start + 16;
return uint128(bytes16(_bytes[_start:end]));
}
}
function toU256(bytes calldata _bytes, uint256 _start) internal pure returns (uint256) {
unchecked {
uint256 end = _start + 32;
return uint256(bytes32(_bytes[_start:end]));
}
}
function toAddr(bytes calldata _bytes, uint256 _start) internal pure returns (address) {
unchecked {
uint256 end = _start + 20;
return address(bytes20(_bytes[_start:end]));
}
}
function toB32(bytes calldata _bytes, uint256 _start) internal pure returns (bytes32) {
unchecked {
uint256 end = _start + 32;
return bytes32(_bytes[_start:end]);
}
}
}// SPDX-License-Identifier: MIT
// modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/BitMaps.sol
pragma solidity ^0.8.20;
type BitMap256 is uint256;
using BitMaps for BitMap256 global;
library BitMaps {
/**
* @dev Returns whether the bit at `index` is set.
*/
function get(BitMap256 bitmap, uint8 index) internal pure returns (bool) {
uint256 mask = 1 << index;
return BitMap256.unwrap(bitmap) & mask != 0;
}
/**
* @dev Sets the bit at `index`.
*/
function set(BitMap256 bitmap, uint8 index) internal pure returns (BitMap256) {
uint256 mask = 1 << index;
return BitMap256.wrap(BitMap256.unwrap(bitmap) | mask);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { ILayerZeroReceiver, Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol";
interface IOAppReceiver is ILayerZeroReceiver {
/**
* @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.
* @param _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @param _message The lzReceive payload.
* @param _sender The sender address.
* @return isSender Is a valid sender.
*
* @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer.
* @dev The default sender IS the OAppReceiver implementer.
*/
function isComposeMsgSender(
Origin calldata _origin,
bytes calldata _message,
address _sender
) external view returns (bool isSender);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MessagingParams, MessagingFee, MessagingReceipt } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { OAppCoreUpgradeable } from "./OAppCoreUpgradeable.sol";
/**
* @title OAppSender
* @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.
*/
abstract contract OAppSenderUpgradeable is OAppCoreUpgradeable {
using SafeERC20 for IERC20;
// Custom error messages
error NotEnoughNative(uint256 msgValue);
error LzTokenUnavailable();
// @dev The version of the OAppSender implementation.
// @dev Version is bumped when changes are made to this contract.
uint64 internal constant SENDER_VERSION = 1;
/**
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
* @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to
* accommodate the different version of Ownable.
*/
function __OAppSender_init(address _delegate) internal onlyInitializing {
__OAppCore_init(_delegate);
}
function __OAppSender_init_unchained() internal onlyInitializing {}
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*
* @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented.
* ie. this is a SEND only OApp.
* @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions
*/
function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
return (SENDER_VERSION, 0);
}
/**
* @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.
* @param _dstEid The destination endpoint ID.
* @param _message The message payload.
* @param _options Additional options for the message.
* @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.
* @return fee The calculated MessagingFee for the message.
* - nativeFee: The native fee for the message.
* - lzTokenFee: The LZ token fee for the message.
*/
function _quote(
uint32 _dstEid,
bytes memory _message,
bytes memory _options,
bool _payInLzToken
) internal view virtual returns (MessagingFee memory fee) {
return
endpoint.quote(
MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken),
address(this)
);
}
/**
* @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message.
* @param _dstEid The destination endpoint ID.
* @param _message The message payload.
* @param _options Additional options for the message.
* @param _fee The calculated LayerZero fee for the message.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess fee values sent to the endpoint.
* @return receipt The receipt for the sent message.
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function _lzSend(
uint32 _dstEid,
bytes memory _message,
bytes memory _options,
MessagingFee memory _fee,
address _refundAddress
) internal virtual returns (MessagingReceipt memory receipt) {
// @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint.
uint256 messageValue = _payNative(_fee.nativeFee);
if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee);
return
// solhint-disable-next-line check-send-result
endpoint.send{ value: messageValue }(
MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0),
_refundAddress
);
}
/**
* @dev Internal function to pay the native fee associated with the message.
* @param _nativeFee The native fee to be paid.
* @return nativeFee The amount of native currency paid.
*
* @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction,
* this will need to be overridden because msg.value would contain multiple lzFees.
* @dev Should be overridden in the event the LayerZero endpoint requires a different native currency.
* @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees.
* @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time.
*/
function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) {
if (msg.value != _nativeFee) revert NotEnoughNative(msg.value);
return _nativeFee;
}
/**
* @dev Internal function to pay the LZ token fee associated with the message.
* @param _lzTokenFee The LZ token fee to be paid.
*
* @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint.
* @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend().
*/
function _payLzToken(uint256 _lzTokenFee) internal virtual {
// @dev Cannot cache the token because it is not immutable in the endpoint.
address lzToken = endpoint.lzToken();
if (lzToken == address(0)) revert LzTokenUnavailable();
// Pay LZ token fee by sending tokens to the endpoint.
IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IOAppReceiver, Origin } from "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppReceiver.sol";
import { OAppCoreUpgradeable } from "./OAppCoreUpgradeable.sol";
/**
* @title OAppReceiver
* @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers.
*/
abstract contract OAppReceiverUpgradeable is IOAppReceiver, OAppCoreUpgradeable {
// Custom error message for when the caller is not the registered endpoint/
error OnlyEndpoint(address addr);
// @dev The version of the OAppReceiver implementation.
// @dev Version is bumped when changes are made to this contract.
uint64 internal constant RECEIVER_VERSION = 2;
/**
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
* @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to
* accommodate the different version of Ownable.
*/
function __OAppReceiver_init(address _delegate) internal onlyInitializing {
__OAppCore_init(_delegate);
}
function __OAppReceiver_init_unchained() internal onlyInitializing {}
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*
* @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented.
* ie. this is a RECEIVE only OApp.
* @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions.
*/
function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
return (0, RECEIVER_VERSION);
}
/**
* @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.
* @dev _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @dev _message The lzReceive payload.
* @param _sender The sender address.
* @return isSender Is a valid sender.
*
* @dev Applications can optionally choose to implement separate composeMsg senders that are NOT the bridging layer.
* @dev The default sender IS the OAppReceiver implementer.
*/
function isComposeMsgSender(
Origin calldata /*_origin*/,
bytes calldata /*_message*/,
address _sender
) public view virtual returns (bool) {
return _sender == address(this);
}
/**
* @notice Checks if the path initialization is allowed based on the provided origin.
* @param origin The origin information containing the source endpoint and sender address.
* @return Whether the path has been initialized.
*
* @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received.
* @dev This defaults to assuming if a peer has been set, its initialized.
* Can be overridden by the OApp if there is other logic to determine this.
*/
function allowInitializePath(Origin calldata origin) public view virtual returns (bool) {
return peers(origin.srcEid) == origin.sender;
}
/**
* @notice Retrieves the next nonce for a given source endpoint and sender address.
* @dev _srcEid The source endpoint ID.
* @dev _sender The sender address.
* @return nonce The next nonce.
*
* @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement.
* @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered.
* @dev This is also enforced by the OApp.
* @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.
*/
function nextNonce(uint32, /*_srcEid*/ bytes32 /*_sender*/) public view virtual returns (uint64 nonce) {
return 0;
}
/**
* @dev Entry point for receiving messages or packets from the endpoint.
* @param _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @param _guid The unique identifier for the received LayerZero message.
* @param _message The payload of the received message.
* @param _executor The address of the executor for the received message.
* @param _extraData Additional arbitrary data provided by the corresponding executor.
*
* @dev Entry point for receiving msg/packet from the LayerZero endpoint.
*/
function lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) public payable virtual {
// Ensures that only the endpoint can attempt to lzReceive() messages to this OApp.
if (address(endpoint) != msg.sender) revert OnlyEndpoint(msg.sender);
// Ensure that the sender matches the expected peer for the source endpoint.
if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender);
// Call the internal OApp implementation of lzReceive.
_lzReceive(_origin, _guid, _message, _executor, _extraData);
}
/**
* @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation.
*/
function _lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) internal virtual;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { IOAppCore, ILayerZeroEndpointV2 } from "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppCore.sol";
/**
* @title OAppCore
* @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.
*/
abstract contract OAppCoreUpgradeable is IOAppCore, OwnableUpgradeable {
struct OAppCoreStorage {
mapping(uint32 => bytes32) peers;
}
// keccak256(abi.encode(uint256(keccak256("layerzerov2.storage.oappcore")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant OAPP_CORE_STORAGE_LOCATION =
0x72ab1bc1039b79dc4724ffca13de82c96834302d3c7e0d4252232d4b2dd8f900;
function _getOAppCoreStorage() internal pure returns (OAppCoreStorage storage $) {
assembly {
$.slot := OAPP_CORE_STORAGE_LOCATION
}
}
// The LayerZero endpoint associated with the given OApp
ILayerZeroEndpointV2 public immutable endpoint;
/**
* @dev Constructor to initialize the OAppCore with the provided endpoint and delegate.
* @param _endpoint The address of the LOCAL Layer Zero endpoint.
*/
constructor(address _endpoint) {
endpoint = ILayerZeroEndpointV2(_endpoint);
}
/**
* @dev Initializes the OAppCore with the provided delegate.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*
* @dev The delegate typically should be set as the owner of the contract.
* @dev Ownable is not initialized here on purpose. It should be initialized in the child contract to
* accommodate the different version of Ownable.
*/
function __OAppCore_init(address _delegate) internal onlyInitializing {
__OAppCore_init_unchained(_delegate);
}
function __OAppCore_init_unchained(address _delegate) internal onlyInitializing {
if (_delegate == address(0)) revert InvalidDelegate();
endpoint.setDelegate(_delegate);
}
/**
* @notice Returns the peer address (OApp instance) associated with a specific endpoint.
* @param _eid The endpoint ID.
* @return peer The address of the peer associated with the specified endpoint.
*/
function peers(uint32 _eid) public view override returns (bytes32) {
OAppCoreStorage storage $ = _getOAppCoreStorage();
return $.peers[_eid];
}
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
* @dev Set this to bytes32(0) to remove the peer address.
* @dev Peer is a bytes32 to accommodate non-evm chains.
*/
function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner {
OAppCoreStorage storage $ = _getOAppCoreStorage();
$.peers[_eid] = _peer;
emit PeerSet(_eid, _peer);
}
/**
* @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set.
* ie. the peer is set to bytes32(0).
* @param _eid The endpoint ID.
* @return peer The address of the peer associated with the specified endpoint.
*/
function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) {
OAppCoreStorage storage $ = _getOAppCoreStorage();
bytes32 peer = $.peers[_eid];
if (peer == bytes32(0)) revert NoPeer(_eid);
return peer;
}
/**
* @notice Sets the delegate address for the OApp.
* @param _delegate The address of the delegate to be set.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract.
*/
function setDelegate(address _delegate) public onlyOwner {
endpoint.setDelegate(_delegate);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
struct PreCrimePeer {
uint32 eid;
bytes32 preCrime;
bytes32 oApp;
}
// TODO not done yet
interface IPreCrime {
error OnlyOffChain();
// for simulate()
error PacketOversize(uint256 max, uint256 actual);
error PacketUnsorted();
error SimulationFailed(bytes reason);
// for preCrime()
error SimulationResultNotFound(uint32 eid);
error InvalidSimulationResult(uint32 eid, bytes reason);
error CrimeFound(bytes crime);
function getConfig(bytes[] calldata _packets, uint256[] calldata _packetMsgValues) external returns (bytes memory);
function simulate(
bytes[] calldata _packets,
uint256[] calldata _packetMsgValues
) external payable returns (bytes memory);
function buildSimulationResult() external view returns (bytes memory);
function preCrime(
bytes[] calldata _packets,
uint256[] calldata _packetMsgValues,
bytes[] calldata _simulations
) external;
function version() external view returns (uint64 major, uint8 minor);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
// @dev Import the Origin so it's exposed to OAppPreCrimeSimulator implementers.
// solhint-disable-next-line no-unused-import
import { InboundPacket, Origin } from "../libs/Packet.sol";
/**
* @title IOAppPreCrimeSimulator Interface
* @dev Interface for the preCrime simulation functionality in an OApp.
*/
interface IOAppPreCrimeSimulator {
// @dev simulation result used in PreCrime implementation
error SimulationResult(bytes result);
error OnlySelf();
/**
* @dev Emitted when the preCrime contract address is set.
* @param preCrimeAddress The address of the preCrime contract.
*/
event PreCrimeSet(address preCrimeAddress);
/**
* @dev Retrieves the address of the preCrime contract implementation.
* @return The address of the preCrime contract.
*/
function preCrime() external view returns (address);
/**
* @dev Retrieves the address of the OApp contract.
* @return The address of the OApp contract.
*/
function oApp() external view returns (address);
/**
* @dev Sets the preCrime contract address.
* @param _preCrime The address of the preCrime contract.
*/
function setPreCrime(address _preCrime) external;
/**
* @dev Mocks receiving a packet, then reverts with a series of data to infer the state/result.
* @param _packets An array of LayerZero InboundPacket objects representing received packets.
*/
function lzReceiveAndRevert(InboundPacket[] calldata _packets) external payable;
/**
* @dev checks if the specified peer is considered 'trusted' by the OApp.
* @param _eid The endpoint Id to check.
* @param _peer The peer to check.
* @return Whether the peer passed is considered 'trusted' by the OApp.
*/
function isPeer(uint32 _eid, bytes32 _peer) external view returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { Origin } from "./ILayerZeroEndpointV2.sol";
interface ILayerZeroReceiver {
function allowInitializePath(Origin calldata _origin) external view returns (bool);
function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);
function lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) external payable;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { PacketV1Codec } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol";
/**
* @title InboundPacket
* @dev Structure representing an inbound packet received by the contract.
*/
struct InboundPacket {
Origin origin; // Origin information of the packet.
uint32 dstEid; // Destination endpointId of the packet.
address receiver; // Receiver address for the packet.
bytes32 guid; // Unique identifier of the packet.
uint256 value; // msg.value of the packet.
address executor; // Executor address for the packet.
bytes message; // Message payload of the packet.
bytes extraData; // Additional arbitrary data for the packet.
}
/**
* @title PacketDecoder
* @dev Library for decoding LayerZero packets.
*/
library PacketDecoder {
using PacketV1Codec for bytes;
/**
* @dev Decode an inbound packet from the given packet data.
* @param _packet The packet data to decode.
* @return packet An InboundPacket struct representing the decoded packet.
*/
function decode(bytes calldata _packet) internal pure returns (InboundPacket memory packet) {
packet.origin = Origin(_packet.srcEid(), _packet.sender(), _packet.nonce());
packet.dstEid = _packet.dstEid();
packet.receiver = _packet.receiverB20();
packet.guid = _packet.guid();
packet.message = _packet.message();
}
/**
* @dev Decode multiple inbound packets from the given packet data and associated message values.
* @param _packets An array of packet data to decode.
* @param _packetMsgValues An array of associated message values for each packet.
* @return packets An array of InboundPacket structs representing the decoded packets.
*/
function decode(
bytes[] calldata _packets,
uint256[] memory _packetMsgValues
) internal pure returns (InboundPacket[] memory packets) {
packets = new InboundPacket[](_packets.length);
for (uint256 i = 0; i < _packets.length; i++) {
bytes calldata packet = _packets[i];
packets[i] = PacketDecoder.decode(packet);
// @dev Allows the verifier to specify the msg.value that gets passed in lzReceive.
packets[i].value = _packetMsgValues[i];
}
}
}// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { Packet } from "../../interfaces/ISendLib.sol";
import { AddressCast } from "../../libs/AddressCast.sol";
library PacketV1Codec {
using AddressCast for address;
using AddressCast for bytes32;
uint8 internal constant PACKET_VERSION = 1;
// header (version + nonce + path)
// version
uint256 private constant PACKET_VERSION_OFFSET = 0;
// nonce
uint256 private constant NONCE_OFFSET = 1;
// path
uint256 private constant SRC_EID_OFFSET = 9;
uint256 private constant SENDER_OFFSET = 13;
uint256 private constant DST_EID_OFFSET = 45;
uint256 private constant RECEIVER_OFFSET = 49;
// payload (guid + message)
uint256 private constant GUID_OFFSET = 81; // keccak256(nonce + path)
uint256 private constant MESSAGE_OFFSET = 113;
function encode(Packet memory _packet) internal pure returns (bytes memory encodedPacket) {
encodedPacket = abi.encodePacked(
PACKET_VERSION,
_packet.nonce,
_packet.srcEid,
_packet.sender.toBytes32(),
_packet.dstEid,
_packet.receiver,
_packet.guid,
_packet.message
);
}
function encodePacketHeader(Packet memory _packet) internal pure returns (bytes memory) {
return
abi.encodePacked(
PACKET_VERSION,
_packet.nonce,
_packet.srcEid,
_packet.sender.toBytes32(),
_packet.dstEid,
_packet.receiver
);
}
function encodePayload(Packet memory _packet) internal pure returns (bytes memory) {
return abi.encodePacked(_packet.guid, _packet.message);
}
function header(bytes calldata _packet) internal pure returns (bytes calldata) {
return _packet[0:GUID_OFFSET];
}
function version(bytes calldata _packet) internal pure returns (uint8) {
return uint8(bytes1(_packet[PACKET_VERSION_OFFSET:NONCE_OFFSET]));
}
function nonce(bytes calldata _packet) internal pure returns (uint64) {
return uint64(bytes8(_packet[NONCE_OFFSET:SRC_EID_OFFSET]));
}
function srcEid(bytes calldata _packet) internal pure returns (uint32) {
return uint32(bytes4(_packet[SRC_EID_OFFSET:SENDER_OFFSET]));
}
function sender(bytes calldata _packet) internal pure returns (bytes32) {
return bytes32(_packet[SENDER_OFFSET:DST_EID_OFFSET]);
}
function senderAddressB20(bytes calldata _packet) internal pure returns (address) {
return sender(_packet).toAddress();
}
function dstEid(bytes calldata _packet) internal pure returns (uint32) {
return uint32(bytes4(_packet[DST_EID_OFFSET:RECEIVER_OFFSET]));
}
function receiver(bytes calldata _packet) internal pure returns (bytes32) {
return bytes32(_packet[RECEIVER_OFFSET:GUID_OFFSET]);
}
function receiverB20(bytes calldata _packet) internal pure returns (address) {
return receiver(_packet).toAddress();
}
function guid(bytes calldata _packet) internal pure returns (bytes32) {
return bytes32(_packet[GUID_OFFSET:MESSAGE_OFFSET]);
}
function message(bytes calldata _packet) internal pure returns (bytes calldata) {
return bytes(_packet[MESSAGE_OFFSET:]);
}
function payload(bytes calldata _packet) internal pure returns (bytes calldata) {
return bytes(_packet[GUID_OFFSET:]);
}
function payloadHash(bytes calldata _packet) internal pure returns (bytes32) {
return keccak256(payload(_packet));
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { MessagingFee } from "./ILayerZeroEndpointV2.sol";
import { IMessageLib } from "./IMessageLib.sol";
struct Packet {
uint64 nonce;
uint32 srcEid;
address sender;
uint32 dstEid;
bytes32 receiver;
bytes32 guid;
bytes message;
}
interface ISendLib is IMessageLib {
function send(
Packet calldata _packet,
bytes calldata _options,
bool _payInLzToken
) external returns (MessagingFee memory, bytes memory encodedPacket);
function quote(
Packet calldata _packet,
bytes calldata _options,
bool _payInLzToken
) external view returns (MessagingFee memory);
function setTreasury(address _treasury) external;
function withdrawFee(address _to, uint256 _amount) external;
function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external;
}// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
library AddressCast {
error AddressCast_InvalidSizeForAddress();
error AddressCast_InvalidAddress();
function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) {
if (_addressBytes.length > 32) revert AddressCast_InvalidAddress();
result = bytes32(_addressBytes);
unchecked {
uint256 offset = 32 - _addressBytes.length;
result = result >> (offset * 8);
}
}
function toBytes32(address _address) internal pure returns (bytes32 result) {
result = bytes32(uint256(uint160(_address)));
}
function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) {
if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress();
result = new bytes(_size);
unchecked {
uint256 offset = 256 - _size * 8;
assembly {
mstore(add(result, 32), shl(offset, _addressBytes32))
}
}
}
function toAddress(bytes32 _addressBytes32) internal pure returns (address result) {
result = address(uint160(uint256(_addressBytes32)));
}
function toAddress(bytes calldata _addressBytes) internal pure returns (address result) {
if (_addressBytes.length != 20) revert AddressCast_InvalidAddress();
result = address(bytes20(_addressBytes));
}
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import { SetConfigParam } from "./IMessageLibManager.sol";
enum MessageLibType {
Send,
Receive,
SendAndReceive
}
interface IMessageLib is IERC165 {
function setConfig(address _oapp, SetConfigParam[] calldata _config) external;
function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);
function isSupportedEid(uint32 _eid) external view returns (bool);
// message libs of same major version are compatible
function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);
function messageLibType() external view returns (MessageLibType);
}{
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@uniswap/v3-periphery/=lib/v3-periphery/",
"@uniswap/v3-core/=lib/v3-core/",
"@openzeppelin/foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"@chainlink/contracts/=lib/chainlink/contracts/",
"@chainlink/local/=lib/chainlink-local/",
"@create3/contracts/=lib/create3/contracts/",
"@balancer/contracts/=lib/balancer-v2-monorepo/pkg/",
"@balancer-labs/v2-interfaces/=lib/balancer-v2-monorepo/pkg/interfaces/",
"@balancer-labs/v2-pool-utils/=lib/balancer-v2-monorepo/pkg/pool-utils/",
"@balancer-labs/v2-solidity-utils/=lib/balancer-v2-monorepo/pkg/solidity-utils/",
"@layerzerolabs/oft-evm/=lib/devtools/packages/oft-evm/",
"@layerzerolabs/oft-evm-upgradeable/=lib/devtools/packages/oft-evm-upgradeable/",
"@layerzerolabs/oapp-evm/=lib/devtools/packages/oapp-evm/",
"@layerzerolabs/oapp-evm-upgradeable/=lib/devtools/packages/oapp-evm-upgradeable/",
"@layerzerolabs/lz-evm-protocol-v2/=lib/layerzero-v2/packages/layerzero-v2/evm/protocol/",
"@layerzerolabs/lz-evm-messagelib-v2/=lib/layerzero-v2/packages/layerzero-v2/evm/messagelib/",
"@layerzerolabs/test-devtools-evm-foundry/=lib/devtools/packages/test-devtools-evm-foundry/",
"@layerzerolabs/lz-evm-v1-0.7/=lib/LayerZero-v1/",
"solidity-bytes-utils/=lib/solidity-bytes-utils/",
"@chainlink/contracts-ccip/=lib/chainlink-local/lib/ccip/contracts/",
"LayerZero-v1/=lib/LayerZero-v1/contracts/",
"balancer-v2-monorepo/=lib/balancer-v2-monorepo/",
"ccip/=lib/chainlink-local/lib/ccip/",
"chainlink-brownie-contracts/=lib/chainlink-local/lib/chainlink-brownie-contracts/contracts/src/v0.6/vendor/@arbitrum/nitro-contracts/src/",
"chainlink-local/=lib/chainlink-local/src/",
"chainlink/=lib/chainlink/",
"create3/=lib/create3/contracts/",
"devtools/=lib/devtools/packages/toolbox-foundry/src/",
"ds-test/=lib/chainlink-local/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"layerzero-v2/=lib/layerzero-v2/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
"v3-core/=lib/v3-core/",
"v3-periphery/=lib/v3-periphery/contracts/"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"metadata": {
"useLiteralContent": false,
"bytecodeHash": "ipfs",
"appendCBOR": true
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "prague",
"viaIR": true
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[],"name":"AuctionRecentlyStarted","type":"error"},{"inputs":[],"name":"CallerIsNotPool","type":"error"},{"inputs":[],"name":"CallerIsNotPoolFactory","type":"error"},{"inputs":[],"name":"CallerIsNotSecurityCouncil","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"ERC2612ExpiredSignature","type":"error"},{"inputs":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"ERC2612InvalidSigner","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"currentNonce","type":"uint256"}],"name":"InvalidAccountNonce","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","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":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"currentPeriod","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"sharesPerToken","type":"uint256"}],"name":"IncreasedAssetPeriod","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","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":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"lastUpdatedPeriod","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"indexedAmountShares","type":"uint256"}],"name":"UpdatedUserAssets","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DISTRIBUTOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"GOV_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINTER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SHARES_DECIMALS","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"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":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"fromWhitelist","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"currentPeriod","type":"uint256"}],"name":"getIndexedUserAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"}],"name":"getIndexedUserAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPreviousPoolAmounts","outputs":[{"components":[{"internalType":"uint256","name":"period","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"sharesPerToken","type":"uint256"}],"internalType":"struct BondToken.PoolAmount[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"globalPool","outputs":[{"internalType":"uint256","name":"currentPeriod","type":"uint256"},{"internalType":"uint256","name":"sharesPerToken","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"sharesPerToken","type":"uint256"}],"name":"increaseIndexedAssetPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"address","name":"minter","type":"address"},{"internalType":"address","name":"governance","type":"address"},{"internalType":"address","name":"_poolFactory","type":"address"},{"internalType":"uint256","name":"sharesPerToken","type":"uint256"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"pool","outputs":[{"internalType":"contract Pool","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolFactory","outputs":[{"internalType":"contract PoolFactory","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"user","type":"address"},{"internalType":"bool","name":"resetLastIndexedPeriodBalance","type":"bool"}],"name":"resetIndexedUserAssets","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_auctionStartBlock","type":"uint256"}],"name":"setAuctionStartBlock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_auctionStartTransfersPause","type":"uint256"}],"name":"setAuctionStartTransfersPause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bool","name":"isWhitelisted","type":"bool"}],"name":"setFromWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_pool","type":"address"}],"name":"setPool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_sharesPerToken","type":"uint256"}],"name":"setSharesPerToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bool","name":"isWhitelisted","type":"bool"}],"name":"setToWhitelist","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"toWhitelist","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userAssets","outputs":[{"internalType":"uint256","name":"lastUpdatedPeriod","type":"uint256"},{"internalType":"uint256","name":"indexedAmountShares","type":"uint256"},{"internalType":"uint256","name":"lastIndexedPeriodBalance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"zeroLastSharesPerToken","outputs":[],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
60a080604052346100c257306080525f5160206133965f395f51905f525460ff8160401c166100b3576002600160401b03196001600160401b03821601610060575b6040516132cf90816100c782396080518181816119720152611a150152f35b6001600160401b0319166001600160401b039081175f5160206133965f395f51905f525581527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a15f80610041565b63f92ee8a960e01b5f5260045ffd5b5f80fdfe6080806040526004361015610012575f80fd5b5f3560e01c90816301ffc9a71461232a5750806306fdde031461226d578063095ea7b31461224757806310c049321461221157806311f9e065146121d357806316f0115b146121ab57806318160ddd146121825780631b8ab222146121615780631dde38b81461213657806323b872dd1461205e5780632464bb5a14612033578063248a9ca314611ffc5780632f2ff15d14611fb2578063313ce56714611f975780633644e51514611f7557806336568abe14611f315780633911578414611f0e5780633f4ba83a14611dd157806340c10f1914611c6b5780634219dc4014611c435780634437152a14611be7578063474e19f214611bcc5780634f1ef286146119c657806352d1902d146119605780635c975abb1461193257806366676424146118f457806370a08231146118b05780637362d149146118765780637ecebe00146118205780638456cb59146116c657806384b0196e1461157c5780638678f6861461153f57806391d14854146114ea57806395d89b41146113f45780639dc29fac1461124d578063a217fddf14611233578063a9059cbb14611202578063ad3cb1cc146111b7578063ad7d9c82146110cf578063b239b08d14611092578063b25f15db1461103d578063b536818a14611016578063bbe7f8ea14610f75578063d505accf14610e13578063d539139314610dec578063d547741f14610d9b578063dd62ed3e14610d54578063ed4e7e0614610d05578063edf3e29e1461039b578063ef4be9c41461028b5763f0bd87cc1461024d575f80fd5b34610287575f3660031901126102875760206040517ffbd454f36a7e1a388bd6fc3ab10d434aa4578f811acbbcf33afb1c697486313c8152f35b5f80fd5b34610287576020366003190112610287576004356102a7612800565b6102af612d97565b5f545f51602061319a5f395f51905f525490604051906102ce826123fc565b8152602081019182526040810183815260025468010000000000000000811015610387578060016103029201600255612696565b93909361037457600292518455516001840155519101555f545f198114610360577fc3986d9e944a9d21282778706c27434cc1a9d0ddc2954e2960855f0d9a064a7f9160016040920190815f558060015582519182526020820152a1005b634e487b7160e01b5f52601160045260245ffd5b634e487b7160e01b5f525f60045260245ffd5b634e487b7160e01b5f52604160045260245ffd5b346102875760c03660031901126102875760043567ffffffffffffffff8111610287576103cc9036906004016124c4565b60243567ffffffffffffffff8111610287576103ec9036906004016124c4565b6044356001600160a01b038116810361028757606435906001600160a01b0382168203610287576084356001600160a01b03811690819003610287575f51602061325a5f395f51905f52549360ff8560401c16159467ffffffffffffffff811680159081610cfd575b6001149081610cf3575b159081610cea575b50610cdb5767ffffffffffffffff1981166001175f51602061325a5f395f51905f525585610caf575b50610499612f6f565b6104a1612f6f565b855167ffffffffffffffff8111610387576104c95f51602061311a5f395f51905f52546124e2565b601f8111610c40575b50806020601f8211600114610bc2575f91610bb7575b508160011b915f199060031b1c1916175f51602061311a5f395f51905f52555b80519067ffffffffffffffff82116103875781906105335f51602061317a5f395f51905f52546124e2565b601f8111610b3d575b50602090601f8311600114610abf575f92610ab4575b50508160011b915f199060031b1c1916175f51602061317a5f395f51905f52555b61057b612f6f565b60409485519061058b8783612418565b60018252603160f81b60208301526105a1612f6f565b80519067ffffffffffffffff82116103875781906105cc5f51602061315a5f395f51905f52546124e2565b601f8111610a3a575b50602090601f83116001146109bc575f926109b1575b50508160011b915f199060031b1c1916175f51602061315a5f395f51905f52555b80519067ffffffffffffffff8211610387576106355f5160206131ba5f395f51905f52546124e2565b601f8111610942575b50602090601f83116001146108bc579180610725949261072b9796945f926108b1575b50508160011b915f199060031b1c1916175f5160206131ba5f395f51905f52555b5f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100555f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d101556106d0612f6f565b6106d8612f6f565b6106e0612f6f565b60ff195f51602061323a5f395f51905f5254165f51602061323a5f395f51905f52556bffffffffffffffffffffffff60a01b600354161760035560a435600155612ae0565b50612b9e565b505f51602061327a5f395f51905f525f8181525f51602061321a5f395f51905f526020528381206001018054908390559082907fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9080a47ffbd454f36a7e1a388bd6fc3ab10d434aa4578f811acbbcf33afb1c697486313c5f8181525f51602061321a5f395f51905f5260205283812060010180545f51602061327a5f395f51905f5291829055909290917fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9080a45f5160206131fa5f395f51905f525f8181525f51602061321a5f395f51905f526020528381206001018054908390559082907fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9080a4600360065561085b57005b60207fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29168ff0000000000000000195f51602061325a5f395f51905f5254165f51602061325a5f395f51905f52555160018152a1005b015190508980610661565b90601f198316915f5160206131ba5f395f51905f525f52815f20925f5b81811061092a575092600192859261072b999896610725989610610912575b505050811b015f5160206131ba5f395f51905f5255610682565b01515f1960f88460031b161c191690558980806108f8565b929360206001819287860151815501950193016108d9565b5f5160206131ba5f395f51905f525f527f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b75601f840160051c810191602085106109a7575b601f0160051c01905b81811061099c575061063e565b5f815560010161098f565b9091508190610986565b0151905088806105eb565b5f51602061315a5f395f51905f525f9081528281209350601f198516905b818110610a225750908460019594939210610a0a575b505050811b015f51602061315a5f395f51905f525561060c565b01515f1960f88460031b161c191690558880806109f0565b929360206001819287860151815501950193016109da565b5f51602061315a5f395f51905f525f529091507f42ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57d601f840160051c81019160208510610aaa575b90601f859493920160051c01905b818110610a9c57506105d5565b5f8155849350600101610a8f565b9091508190610a81565b015190508780610552565b5f51602061317a5f395f51905f525f9081528281209350601f198516905b818110610b255750908460019594939210610b0d575b505050811b015f51602061317a5f395f51905f5255610573565b01515f1960f88460031b161c19169055878080610af3565b92936020600181928786015181550195019301610add565b5f51602061317a5f395f51905f525f529091507f46a2803e59a4de4e7a4c574b1243f25977ac4c77d5a1a4a609b5394cebb4a2aa601f840160051c81019160208510610bad575b90601f859493920160051c01905b818110610b9f575061053c565b5f8155849350600101610b92565b9091508190610b84565b9050870151886104e8565b5f51602061311a5f395f51905f525f9081528181209250601f198416905b8a828210610c285750509083600194939210610c10575b5050811b015f51602061311a5f395f51905f5255610508565b8901515f1960f88460031b161c191690558880610bf7565b60018495602093958493015181550194019201610be0565b5f51602061311a5f395f51905f525f527f2ae08a8e29253f69ac5d979a101956ab8f8d9d7ded63fa7a83b16fc47648eab0601f830160051c81019160208410610ca5575b601f0160051c01905b818110610c9a57506104d2565b5f8155600101610c8d565b9091508190610c84565b68ffffffffffffffffff191668010000000000000001175f51602061325a5f395f51905f525586610490565b63f92ee8a960e01b5f5260045ffd5b90501588610467565b303b15915061045f565b879150610455565b34610287576020366003190112610287576001600160a01b03610d266123a1565b165f526005602052606060405f20805490600260018201549101549060405192835260208301526040820152f35b3461028757604036600319011261028757610d6d6123a1565b610d7e610d786123b7565b9161248c565b9060018060a01b03165f52602052602060405f2054604051908152f35b3461028757604036600319011261028757610dea600435610dba6123b7565b90610de5610de0825f525f51602061321a5f395f51905f52602052600160405f20015490565b612927565b612cfb565b005b34610287575f3660031901126102875760206040515f5160206131fa5f395f51905f528152f35b346102875760e036600319011261028757610e2c6123a1565b610e346123b7565b604435906064359260843560ff8116810361028757844211610f6257610f27610f309160018060a01b03841696875f527f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb0060205260405f20908154916001830190556040519060208201927f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c984528a604084015260018060a01b038916606084015289608084015260a083015260c082015260c08152610ef560e082612418565b519020610f00612e12565b906040519161190160f01b83526002830152602282015260c43591604260a4359220612e79565b90929192612efb565b6001600160a01b0316848103610f4b5750610dea9350612daf565b84906325c0072360e11b5f5260045260245260445ffd5b8463313c898160e11b5f5260045260245ffd5b3461028757610f83366123cd565b90610f8c612800565b610f94612d97565b6001600160a01b0381165f818152600560205260408120600101559115610fda5750805f5260056020525f60026040822001555b5f805491815260056020526040902055005b610fff90825f525f51602061313a5f395f51905f5260205260405f20545f549161270e565b9050815f526005602052600260405f200155610fc8565b34610287575f3660031901126102875760206040515f51602061327a5f395f51905f528152f35b3461028757602036600319011261028757604061108661105b6123a1565b6001600160a01b0381165f9081525f51602061313a5f395f51905f526020528381205490549161270e565b82519182526020820152f35b34610287576020366003190112610287576001600160a01b036110b36123a1565b165f526009602052602060ff60405f2054166040519015158152f35b34610287575f3660031901126102875760025467ffffffffffffffff81116103875760208160051b01906111066040519283612418565b80825260208201908160025f527f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace5f915b838310611199578486604051918291602083019060208452518091526040830191905f5b818110611169575050500390f35b9193509160206060600192604087518051835284810151858401520151604082015201940191019184939261115b565b600360206001926111a9856126c6565b815201920192019190611137565b34610287575f366003190112610287576111fe6040516111d8604082612418565b60058152640352e302e360dc1b602082015260405191829160208352602083019061237d565b0390f35b346102875760403660031901126102875761122861121e6123a1565b602435903361296d565b602060405160018152f35b34610287575f3660031901126102875760206040515f8152f35b34610287576040366003190112610287576112666123a1565b602435906112726128cb565b6001600160a01b0381169081156113e15760ff5f51602061323a5f395f51905f525416611383575b6112a960075460065490612701565b4310611374576112d290825f525f51602061313a5f395f51905f5260205260405f205490612f9a565b805f525f51602061313a5f395f51905f5260205260405f205482811061135b576020835f947fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef938587525f51602061313a5f395f51905f528452036040862055805f51602061319a5f395f51905f5254035f51602061319a5f395f51905f5255604051908152a3005b9063391434e360e21b5f5260045260245260445260645ffd5b63026c02a160e51b5f5260045ffd5b815f52600960205260ff60405f20541680156113ae575b61129a575b63d93c066560e01b5f5260045ffd5b505f805260086020527f5eff886ea0ce6ca488a3d6e336d6c0f75f46d19b42c06ce5ee98e42c96d256c75460ff1661139a565b634b637e8f60e11b5f525f60045260245ffd5b34610287575f366003190112610287576040515f5f51602061317a5f395f51905f5254611420816124e2565b80845290600181169081156114c6575060011461145c575b6111fe8361144881850382612418565b60405191829160208352602083019061237d565b5f51602061317a5f395f51905f525f9081527f46a2803e59a4de4e7a4c574b1243f25977ac4c77d5a1a4a609b5394cebb4a2aa939250905b8082106114ac57509091508101602001611448611438565b919260018160209254838588010152019101909291611494565b60ff191660208086019190915291151560051b840190910191506114489050611438565b34610287576040366003190112610287576115036123b7565b6004355f525f51602061321a5f395f51905f5260205260405f209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b34610287576020366003190112610287576001600160a01b036115606123a1565b165f526008602052602060ff60405f2054166040519015158152f35b34610287575f366003190112610287577fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10054158061169d575b15611660576116046115c561251a565b6115cd6125e9565b6020611612604051926115e08385612418565b5f84525f368137604051958695600f60f81b875260e08588015260e087019061237d565b90858203604087015261237d565b4660608501523060808501525f60a085015283810360c08501528180845192838152019301915f5b82811061164957505050500390f35b83518552869550938101939281019260010161163a565b60405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b6044820152606490fd5b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10154156115b5565b34610287575f3660031901126102875760035460405163b9fe5cf760e01b81526001600160a01b0390911690602081600481855afa9081156117e1575f916117ec575b50604051632474521560e21b815260048101919091523360248201529060209082908180604481015b03915afa9081156117e1575f916117b2575b50156117a357611752612d97565b600160ff195f51602061323a5f395f51905f525416175f51602061323a5f395f51905f52557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1005b63508105ef60e11b5f5260045ffd5b6117d4915060203d6020116117da575b6117cc8183612418565b8101906127e8565b81611744565b503d6117c2565b6040513d5f823e3d90fd5b90506020813d602011611818575b8161180760209383612418565b810103126102875751611732611709565b3d91506117fa565b34610287576020366003190112610287576118396123a1565b60018060a01b03165f527f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00602052602060405f2054604051908152f35b34610287576020366003190112610287576004546001600160a01b031633036118a157600435600155005b637a9c87e360e11b5f5260045ffd5b34610287576020366003190112610287576001600160a01b036118d16123a1565b165f525f51602061313a5f395f51905f52602052602060405f2054604051908152f35b3461028757610dea611905366123cd565b9061190e61286f565b60018060a01b03165f52600860205260405f209060ff801983541691151516179055565b34610287575f36600319011261028757602060ff5f51602061323a5f395f51905f5254166040519015158152f35b34610287575f366003190112610287577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031630036119b75760206040515f5160206131da5f395f51905f528152f35b63703e46dd60e11b5f5260045ffd5b6040366003190112610287576119da6123a1565b60243567ffffffffffffffff8111610287573660238201121561028757611a0b903690602481600401359101612456565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016308114908115611baa575b506119b757611a4d61286f565b6040516352d1902d60e01b81526001600160a01b0383169290602081600481875afa5f9181611b76575b50611a8f5783634c9c8ce360e01b5f5260045260245ffd5b805f5160206131da5f395f51905f52859203611b645750813b15611b52575f5160206131da5f395f51905f5280546001600160a01b031916821790557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115611b3a575f80836020610dea95519101845af43d15611b32573d91611b168361243a565b92611b246040519485612418565b83523d5f602085013e6130bb565b6060916130bb565b505034611b4357005b63b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b632a87526960e21b5f5260045260245ffd5b9091506020813d602011611ba2575b81611b9260209383612418565b8101031261028757519085611a77565b3d9150611b85565b5f5160206131da5f395f51905f52546001600160a01b03161415905083611a40565b34610287575f36600319011261028757602060405160068152f35b3461028757602036600319011261028757611c006123a1565b6003546001600160a01b03163303611c3457600480546001600160a01b0319166001600160a01b0392909216919091179055005b63cf158be360e01b5f5260045ffd5b34610287575f366003190112610287576003546040516001600160a01b039091168152602090f35b3461028757604036600319011261028757611c846123a1565b60243590611c906128cb565b6001600160a01b038116918215611dbe5760ff5f51602061323a5f395f51905f525416611d61575b611cc760075460065490612701565b43106113745760207fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91611d145f948686525f51602061313a5f395f51905f528452604086205490612f9a565b611d2c815f51602061319a5f395f51905f5254612701565b5f51602061319a5f395f51905f52558484525f51602061313a5f395f51905f52825260408420818154019055604051908152a3005b5f805260096020527fec8156718a8372b1db44bb411437d0870f3e3790d4a08526d024ce1b0b668f6b5460ff168015611da8575b611cb85763d93c066560e01b5f5260045ffd5b50825f52600860205260ff60405f205416611d95565b63ec442f0560e01b5f525f60045260245ffd5b34610287575f3660031901126102875760035460405163b9fe5cf760e01b81526001600160a01b0390911690602081600481855afa9081156117e1575f91611eda575b50604051632474521560e21b815260048101919091523360248201529060209082908180604481015b03915afa9081156117e1575f91611ebb575b50156117a3575f51602061323a5f395f51905f525460ff811615611eac5760ff19165f51602061323a5f395f51905f52557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1005b638dfc202b60e01b5f5260045ffd5b611ed4915060203d6020116117da576117cc8183612418565b81611e4f565b90506020813d602011611f06575b81611ef560209383612418565b810103126102875751611e3d611e14565b3d9150611ee8565b34610287575f3660031901126102875760405f5460015482519182526020820152f35b3461028757604036600319011261028757611f4a6123b7565b336001600160a01b03821603611f6657610dea90600435612cfb565b63334bd91960e11b5f5260045ffd5b34610287575f366003190112610287576020611f8f612e12565b604051908152f35b34610287575f36600319011261028757602060405160128152f35b3461028757604036600319011261028757610dea600435611fd16123b7565b90611ff7610de0825f525f51602061321a5f395f51905f52602052600160405f20015490565b612c57565b34610287576020366003190112610287576020611f8f6004355f525f51602061321a5f395f51905f52602052600160405f20015490565b34610287576020366003190112610287576004546001600160a01b031633036118a157600435600755005b34610287576060366003190112610287576120776123a1565b61207f6123b7565b6044359061208c8361248c565b335f908152602091909152604090205492600184016120b0575b611228935061296d565b82841061211b576001600160a01b038116156121085733156120f557611228936120d98261248c565b60018060a01b0333165f526020528360405f20910390556120a6565b634a1406b160e11b5f525f60045260245ffd5b63e602df0560e01b5f525f60045260245ffd5b8284637dc7a0d960e11b5f523360045260245260445260645ffd5b346102875760603660031901126102875760406110866121546123a1565b604435906024359061270e565b346102875760203660031901126102875761217a61286f565b600435600655005b34610287575f3660031901126102875760205f51602061319a5f395f51905f5254604051908152f35b34610287575f366003190112610287576004546040516001600160a01b039091168152602090f35b3461028757610dea6121e4366123cd565b906121ed61286f565b60018060a01b03165f52600960205260405f209060ff801983541691151516179055565b34610287575f36600319011261028757612229612800565b5f545f1981019081116103605760026122425f92612696565b500155005b34610287576040366003190112610287576112286122636123a1565b6024359033612daf565b34610287575f366003190112610287576040515f5f51602061311a5f395f51905f5254612299816124e2565b80845290600181169081156114c657506001146122c0576111fe8361144881850382612418565b5f51602061311a5f395f51905f525f9081527f2ae08a8e29253f69ac5d979a101956ab8f8d9d7ded63fa7a83b16fc47648eab0939250905b80821061231057509091508101602001611448611438565b9192600181602092548385880101520191019092916122f8565b34610287576020366003190112610287576004359063ffffffff60e01b821680920361028757602091637965db0b60e01b811490811561236c575b5015158152f35b6301ffc9a760e01b14905083612365565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b038216820361028757565b602435906001600160a01b038216820361028757565b6040906003190112610287576004356001600160a01b0381168103610287579060243580151581036102875790565b6060810190811067ffffffffffffffff82111761038757604052565b90601f8019910116810190811067ffffffffffffffff82111761038757604052565b67ffffffffffffffff811161038757601f01601f191660200190565b9291926124628261243a565b916124706040519384612418565b829481845281830111610287578281602093845f960137010152565b6001600160a01b03165f9081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020526040902090565b9080601f83011215610287578160206124df93359101612456565b90565b90600182811c92168015612510575b60208310146124fc57565b634e487b7160e01b5f52602260045260245ffd5b91607f16916124f1565b604051905f825f51602061315a5f395f51905f525491612539836124e2565b80835292600181169081156125ca575060011461255f575b61255d92500383612418565b565b505f51602061315a5f395f51905f525f90815290917f42ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57d5b8183106125ae57505090602061255d92820101612551565b6020919350806001915483858901015201910190918492612596565b6020925061255d94915060ff191682840152151560051b820101612551565b604051905f825f5160206131ba5f395f51905f525491612608836124e2565b80835292600181169081156125ca575060011461262b5761255d92500383612418565b505f5160206131ba5f395f51905f525f90815290917f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b755b81831061267a57505090602061255d92820101612551565b6020919350806001915483858901015201910190918492612662565b6002548110156126b25760025f52600360205f20910201905f90565b634e487b7160e01b5f52603260045260245ffd5b906040516126d3816123fc565b60406002829480548452600181015460208501520154910152565b8181029291811591840414171561036057565b9190820180921161036057565b6001600160a01b03165f908152600560205260409020909290612730906126c6565b9081516040602084015193015184156127dc578482146127d35781935b5f1986018681116103605785101561278f57612787600191620f424061278060026127778a612696565b5001548b6126ee565b0490612701565b94019361274d565b929450909250826127a2575b5090509190565b5f19830192831161036057612780620f42409160026127c36127cc96612696565b500154906126ee565b805f61279b565b94505091509190565b5050925050505f905f90565b90816020910312610287575180151581036102875790565b335f9081527fb2ce6f3a0968c56a08b54f4f0d1d0af4871f2c3340441c6ce862aaa53c9d37c7602052604090205460ff161561283857565b63e2517d3f60e01b5f52336004527ffbd454f36a7e1a388bd6fc3ab10d434aa4578f811acbbcf33afb1c697486313c60245260445ffd5b335f9081527fa7d0f56144dc2cc0b8cc25b72dae5de5732359403e6b65d51614ec6c3aaaf2c8602052604090205460ff16156128a757565b63e2517d3f60e01b5f52336004525f51602061327a5f395f51905f5260245260445ffd5b335f9081527f549fe2656c81d2947b3b913f0a53b9ea86c71e049f3a1b8aa23c09a8a05cb8d4602052604090205460ff161561290357565b63e2517d3f60e01b5f52336004525f5160206131fa5f395f51905f5260245260445ffd5b5f8181525f51602061321a5f395f51905f526020908152604080832033845290915290205460ff16156129575750565b63e2517d3f60e01b5f523360045260245260445ffd5b90916001600160a01b0382169182156113e1576001600160a01b038416938415611dbe5760ff5f51602061323a5f395f51905f525416612aa0575b6129b760075460065490612701565b4310611374576129e3612a0292855f525f51602061313a5f395f51905f5260205260405f205490612f9a565b845f525f51602061313a5f395f51905f5260205260405f205490612f9a565b815f525f51602061313a5f395f51905f5260205260405f2054818110612a8757817fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92602092855f525f51602061313a5f395f51905f5284520360405f2055845f525f51602061313a5f395f51905f52825260405f20818154019055604051908152a3565b8263391434e360e21b5f5260045260245260445260645ffd5b835f52600960205260ff60405f2054168015612aca575b6129a85763d93c066560e01b5f5260045ffd5b50845f52600860205260ff60405f205416612ab7565b6001600160a01b0381165f9081527f549fe2656c81d2947b3b913f0a53b9ea86c71e049f3a1b8aa23c09a8a05cb8d4602052604090205460ff16612b99576001600160a01b03165f8181527f549fe2656c81d2947b3b913f0a53b9ea86c71e049f3a1b8aa23c09a8a05cb8d460205260408120805460ff191660011790553391905f5160206131fa5f395f51905f52907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b505f90565b6001600160a01b0381165f9081527fa7d0f56144dc2cc0b8cc25b72dae5de5732359403e6b65d51614ec6c3aaaf2c8602052604090205460ff16612b99576001600160a01b03165f8181527fa7d0f56144dc2cc0b8cc25b72dae5de5732359403e6b65d51614ec6c3aaaf2c860205260408120805460ff191660011790553391905f51602061327a5f395f51905f52907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b5f8181525f51602061321a5f395f51905f52602090815260408083206001600160a01b038616845290915290205460ff16612cf5575f8181525f51602061321a5f395f51905f52602090815260408083206001600160a01b0395909516808452949091528120805460ff19166001179055339291907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b50505f90565b5f8181525f51602061321a5f395f51905f52602090815260408083206001600160a01b038616845290915290205460ff1615612cf5575f8181525f51602061321a5f395f51905f52602090815260408083206001600160a01b0395909516808452949091528120805460ff19169055339291907ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9080a4600190565b60ff5f51602061323a5f395f51905f52541661139f57565b916001600160a01b038316918215612108576001600160a01b03169283156120f5577f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591612dfe60209261248c565b855f5282528060405f2055604051908152a3565b612e1a61300c565b612e22613076565b6040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a08152612e7360c082612418565b51902090565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411612ef0579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa156117e1575f516001600160a01b03811615612ee657905f905f90565b505f906001905f90565b5050505f9160039190565b6004811015612f5b5780612f0d575050565b60018103612f245763f645eedf60e01b5f5260045ffd5b60028103612f3f575063fce698f760e01b5f5260045260245ffd5b600314612f495750565b6335e2f38360e21b5f5260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b60ff5f51602061325a5f395f51905f525460401c1615612f8b57565b631afcd79f60e31b5f5260045ffd5b7f6b9c497481d518e22778a9623f00f75d627901dcdbb45461f008d640e34ed4f691606091612fcc5f5480938361270e565b6001600160a01b039092165f81815260056020908152604091829020600181018590558681556002019490945580519182529281019390935290820152a1565b61301461251a565b8051908115613024576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1005480156130515790565b507fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090565b61307e6125e9565b805190811561308e576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1015480156130515790565b906130df57508051156130d057805190602001fd5b630a12f52160e11b5f5260045ffd5b81511580613110575b6130f0575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b156130e856fe52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0352c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10252c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0452c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a602dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800cd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a000603f2636f0ca34ae3ea5a23bb826e2bd2ffd59fb1c01edc1ba10fba2899d1baa2646970667358221220216c651b798b40dbfb362c9682490d6df9c3a20f8239e2caed3dc07c6f539dce64736f6c634300081e0033f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00
Deployed Bytecode
0x6080806040526004361015610012575f80fd5b5f3560e01c90816301ffc9a71461232a5750806306fdde031461226d578063095ea7b31461224757806310c049321461221157806311f9e065146121d357806316f0115b146121ab57806318160ddd146121825780631b8ab222146121615780631dde38b81461213657806323b872dd1461205e5780632464bb5a14612033578063248a9ca314611ffc5780632f2ff15d14611fb2578063313ce56714611f975780633644e51514611f7557806336568abe14611f315780633911578414611f0e5780633f4ba83a14611dd157806340c10f1914611c6b5780634219dc4014611c435780634437152a14611be7578063474e19f214611bcc5780634f1ef286146119c657806352d1902d146119605780635c975abb1461193257806366676424146118f457806370a08231146118b05780637362d149146118765780637ecebe00146118205780638456cb59146116c657806384b0196e1461157c5780638678f6861461153f57806391d14854146114ea57806395d89b41146113f45780639dc29fac1461124d578063a217fddf14611233578063a9059cbb14611202578063ad3cb1cc146111b7578063ad7d9c82146110cf578063b239b08d14611092578063b25f15db1461103d578063b536818a14611016578063bbe7f8ea14610f75578063d505accf14610e13578063d539139314610dec578063d547741f14610d9b578063dd62ed3e14610d54578063ed4e7e0614610d05578063edf3e29e1461039b578063ef4be9c41461028b5763f0bd87cc1461024d575f80fd5b34610287575f3660031901126102875760206040517ffbd454f36a7e1a388bd6fc3ab10d434aa4578f811acbbcf33afb1c697486313c8152f35b5f80fd5b34610287576020366003190112610287576004356102a7612800565b6102af612d97565b5f545f51602061319a5f395f51905f525490604051906102ce826123fc565b8152602081019182526040810183815260025468010000000000000000811015610387578060016103029201600255612696565b93909361037457600292518455516001840155519101555f545f198114610360577fc3986d9e944a9d21282778706c27434cc1a9d0ddc2954e2960855f0d9a064a7f9160016040920190815f558060015582519182526020820152a1005b634e487b7160e01b5f52601160045260245ffd5b634e487b7160e01b5f525f60045260245ffd5b634e487b7160e01b5f52604160045260245ffd5b346102875760c03660031901126102875760043567ffffffffffffffff8111610287576103cc9036906004016124c4565b60243567ffffffffffffffff8111610287576103ec9036906004016124c4565b6044356001600160a01b038116810361028757606435906001600160a01b0382168203610287576084356001600160a01b03811690819003610287575f51602061325a5f395f51905f52549360ff8560401c16159467ffffffffffffffff811680159081610cfd575b6001149081610cf3575b159081610cea575b50610cdb5767ffffffffffffffff1981166001175f51602061325a5f395f51905f525585610caf575b50610499612f6f565b6104a1612f6f565b855167ffffffffffffffff8111610387576104c95f51602061311a5f395f51905f52546124e2565b601f8111610c40575b50806020601f8211600114610bc2575f91610bb7575b508160011b915f199060031b1c1916175f51602061311a5f395f51905f52555b80519067ffffffffffffffff82116103875781906105335f51602061317a5f395f51905f52546124e2565b601f8111610b3d575b50602090601f8311600114610abf575f92610ab4575b50508160011b915f199060031b1c1916175f51602061317a5f395f51905f52555b61057b612f6f565b60409485519061058b8783612418565b60018252603160f81b60208301526105a1612f6f565b80519067ffffffffffffffff82116103875781906105cc5f51602061315a5f395f51905f52546124e2565b601f8111610a3a575b50602090601f83116001146109bc575f926109b1575b50508160011b915f199060031b1c1916175f51602061315a5f395f51905f52555b80519067ffffffffffffffff8211610387576106355f5160206131ba5f395f51905f52546124e2565b601f8111610942575b50602090601f83116001146108bc579180610725949261072b9796945f926108b1575b50508160011b915f199060031b1c1916175f5160206131ba5f395f51905f52555b5f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100555f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d101556106d0612f6f565b6106d8612f6f565b6106e0612f6f565b60ff195f51602061323a5f395f51905f5254165f51602061323a5f395f51905f52556bffffffffffffffffffffffff60a01b600354161760035560a435600155612ae0565b50612b9e565b505f51602061327a5f395f51905f525f8181525f51602061321a5f395f51905f526020528381206001018054908390559082907fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9080a47ffbd454f36a7e1a388bd6fc3ab10d434aa4578f811acbbcf33afb1c697486313c5f8181525f51602061321a5f395f51905f5260205283812060010180545f51602061327a5f395f51905f5291829055909290917fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9080a45f5160206131fa5f395f51905f525f8181525f51602061321a5f395f51905f526020528381206001018054908390559082907fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9080a4600360065561085b57005b60207fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29168ff0000000000000000195f51602061325a5f395f51905f5254165f51602061325a5f395f51905f52555160018152a1005b015190508980610661565b90601f198316915f5160206131ba5f395f51905f525f52815f20925f5b81811061092a575092600192859261072b999896610725989610610912575b505050811b015f5160206131ba5f395f51905f5255610682565b01515f1960f88460031b161c191690558980806108f8565b929360206001819287860151815501950193016108d9565b5f5160206131ba5f395f51905f525f527f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b75601f840160051c810191602085106109a7575b601f0160051c01905b81811061099c575061063e565b5f815560010161098f565b9091508190610986565b0151905088806105eb565b5f51602061315a5f395f51905f525f9081528281209350601f198516905b818110610a225750908460019594939210610a0a575b505050811b015f51602061315a5f395f51905f525561060c565b01515f1960f88460031b161c191690558880806109f0565b929360206001819287860151815501950193016109da565b5f51602061315a5f395f51905f525f529091507f42ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57d601f840160051c81019160208510610aaa575b90601f859493920160051c01905b818110610a9c57506105d5565b5f8155849350600101610a8f565b9091508190610a81565b015190508780610552565b5f51602061317a5f395f51905f525f9081528281209350601f198516905b818110610b255750908460019594939210610b0d575b505050811b015f51602061317a5f395f51905f5255610573565b01515f1960f88460031b161c19169055878080610af3565b92936020600181928786015181550195019301610add565b5f51602061317a5f395f51905f525f529091507f46a2803e59a4de4e7a4c574b1243f25977ac4c77d5a1a4a609b5394cebb4a2aa601f840160051c81019160208510610bad575b90601f859493920160051c01905b818110610b9f575061053c565b5f8155849350600101610b92565b9091508190610b84565b9050870151886104e8565b5f51602061311a5f395f51905f525f9081528181209250601f198416905b8a828210610c285750509083600194939210610c10575b5050811b015f51602061311a5f395f51905f5255610508565b8901515f1960f88460031b161c191690558880610bf7565b60018495602093958493015181550194019201610be0565b5f51602061311a5f395f51905f525f527f2ae08a8e29253f69ac5d979a101956ab8f8d9d7ded63fa7a83b16fc47648eab0601f830160051c81019160208410610ca5575b601f0160051c01905b818110610c9a57506104d2565b5f8155600101610c8d565b9091508190610c84565b68ffffffffffffffffff191668010000000000000001175f51602061325a5f395f51905f525586610490565b63f92ee8a960e01b5f5260045ffd5b90501588610467565b303b15915061045f565b879150610455565b34610287576020366003190112610287576001600160a01b03610d266123a1565b165f526005602052606060405f20805490600260018201549101549060405192835260208301526040820152f35b3461028757604036600319011261028757610d6d6123a1565b610d7e610d786123b7565b9161248c565b9060018060a01b03165f52602052602060405f2054604051908152f35b3461028757604036600319011261028757610dea600435610dba6123b7565b90610de5610de0825f525f51602061321a5f395f51905f52602052600160405f20015490565b612927565b612cfb565b005b34610287575f3660031901126102875760206040515f5160206131fa5f395f51905f528152f35b346102875760e036600319011261028757610e2c6123a1565b610e346123b7565b604435906064359260843560ff8116810361028757844211610f6257610f27610f309160018060a01b03841696875f527f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb0060205260405f20908154916001830190556040519060208201927f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c984528a604084015260018060a01b038916606084015289608084015260a083015260c082015260c08152610ef560e082612418565b519020610f00612e12565b906040519161190160f01b83526002830152602282015260c43591604260a4359220612e79565b90929192612efb565b6001600160a01b0316848103610f4b5750610dea9350612daf565b84906325c0072360e11b5f5260045260245260445ffd5b8463313c898160e11b5f5260045260245ffd5b3461028757610f83366123cd565b90610f8c612800565b610f94612d97565b6001600160a01b0381165f818152600560205260408120600101559115610fda5750805f5260056020525f60026040822001555b5f805491815260056020526040902055005b610fff90825f525f51602061313a5f395f51905f5260205260405f20545f549161270e565b9050815f526005602052600260405f200155610fc8565b34610287575f3660031901126102875760206040515f51602061327a5f395f51905f528152f35b3461028757602036600319011261028757604061108661105b6123a1565b6001600160a01b0381165f9081525f51602061313a5f395f51905f526020528381205490549161270e565b82519182526020820152f35b34610287576020366003190112610287576001600160a01b036110b36123a1565b165f526009602052602060ff60405f2054166040519015158152f35b34610287575f3660031901126102875760025467ffffffffffffffff81116103875760208160051b01906111066040519283612418565b80825260208201908160025f527f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace5f915b838310611199578486604051918291602083019060208452518091526040830191905f5b818110611169575050500390f35b9193509160206060600192604087518051835284810151858401520151604082015201940191019184939261115b565b600360206001926111a9856126c6565b815201920192019190611137565b34610287575f366003190112610287576111fe6040516111d8604082612418565b60058152640352e302e360dc1b602082015260405191829160208352602083019061237d565b0390f35b346102875760403660031901126102875761122861121e6123a1565b602435903361296d565b602060405160018152f35b34610287575f3660031901126102875760206040515f8152f35b34610287576040366003190112610287576112666123a1565b602435906112726128cb565b6001600160a01b0381169081156113e15760ff5f51602061323a5f395f51905f525416611383575b6112a960075460065490612701565b4310611374576112d290825f525f51602061313a5f395f51905f5260205260405f205490612f9a565b805f525f51602061313a5f395f51905f5260205260405f205482811061135b576020835f947fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef938587525f51602061313a5f395f51905f528452036040862055805f51602061319a5f395f51905f5254035f51602061319a5f395f51905f5255604051908152a3005b9063391434e360e21b5f5260045260245260445260645ffd5b63026c02a160e51b5f5260045ffd5b815f52600960205260ff60405f20541680156113ae575b61129a575b63d93c066560e01b5f5260045ffd5b505f805260086020527f5eff886ea0ce6ca488a3d6e336d6c0f75f46d19b42c06ce5ee98e42c96d256c75460ff1661139a565b634b637e8f60e11b5f525f60045260245ffd5b34610287575f366003190112610287576040515f5f51602061317a5f395f51905f5254611420816124e2565b80845290600181169081156114c6575060011461145c575b6111fe8361144881850382612418565b60405191829160208352602083019061237d565b5f51602061317a5f395f51905f525f9081527f46a2803e59a4de4e7a4c574b1243f25977ac4c77d5a1a4a609b5394cebb4a2aa939250905b8082106114ac57509091508101602001611448611438565b919260018160209254838588010152019101909291611494565b60ff191660208086019190915291151560051b840190910191506114489050611438565b34610287576040366003190112610287576115036123b7565b6004355f525f51602061321a5f395f51905f5260205260405f209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b34610287576020366003190112610287576001600160a01b036115606123a1565b165f526008602052602060ff60405f2054166040519015158152f35b34610287575f366003190112610287577fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10054158061169d575b15611660576116046115c561251a565b6115cd6125e9565b6020611612604051926115e08385612418565b5f84525f368137604051958695600f60f81b875260e08588015260e087019061237d565b90858203604087015261237d565b4660608501523060808501525f60a085015283810360c08501528180845192838152019301915f5b82811061164957505050500390f35b83518552869550938101939281019260010161163a565b60405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b6044820152606490fd5b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10154156115b5565b34610287575f3660031901126102875760035460405163b9fe5cf760e01b81526001600160a01b0390911690602081600481855afa9081156117e1575f916117ec575b50604051632474521560e21b815260048101919091523360248201529060209082908180604481015b03915afa9081156117e1575f916117b2575b50156117a357611752612d97565b600160ff195f51602061323a5f395f51905f525416175f51602061323a5f395f51905f52557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1005b63508105ef60e11b5f5260045ffd5b6117d4915060203d6020116117da575b6117cc8183612418565b8101906127e8565b81611744565b503d6117c2565b6040513d5f823e3d90fd5b90506020813d602011611818575b8161180760209383612418565b810103126102875751611732611709565b3d91506117fa565b34610287576020366003190112610287576118396123a1565b60018060a01b03165f527f5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00602052602060405f2054604051908152f35b34610287576020366003190112610287576004546001600160a01b031633036118a157600435600155005b637a9c87e360e11b5f5260045ffd5b34610287576020366003190112610287576001600160a01b036118d16123a1565b165f525f51602061313a5f395f51905f52602052602060405f2054604051908152f35b3461028757610dea611905366123cd565b9061190e61286f565b60018060a01b03165f52600860205260405f209060ff801983541691151516179055565b34610287575f36600319011261028757602060ff5f51602061323a5f395f51905f5254166040519015158152f35b34610287575f366003190112610287577f00000000000000000000000051c5d0648648f789ab0dfcf91325332bf91069f16001600160a01b031630036119b75760206040515f5160206131da5f395f51905f528152f35b63703e46dd60e11b5f5260045ffd5b6040366003190112610287576119da6123a1565b60243567ffffffffffffffff8111610287573660238201121561028757611a0b903690602481600401359101612456565b6001600160a01b037f00000000000000000000000051c5d0648648f789ab0dfcf91325332bf91069f116308114908115611baa575b506119b757611a4d61286f565b6040516352d1902d60e01b81526001600160a01b0383169290602081600481875afa5f9181611b76575b50611a8f5783634c9c8ce360e01b5f5260045260245ffd5b805f5160206131da5f395f51905f52859203611b645750813b15611b52575f5160206131da5f395f51905f5280546001600160a01b031916821790557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115611b3a575f80836020610dea95519101845af43d15611b32573d91611b168361243a565b92611b246040519485612418565b83523d5f602085013e6130bb565b6060916130bb565b505034611b4357005b63b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b632a87526960e21b5f5260045260245ffd5b9091506020813d602011611ba2575b81611b9260209383612418565b8101031261028757519085611a77565b3d9150611b85565b5f5160206131da5f395f51905f52546001600160a01b03161415905083611a40565b34610287575f36600319011261028757602060405160068152f35b3461028757602036600319011261028757611c006123a1565b6003546001600160a01b03163303611c3457600480546001600160a01b0319166001600160a01b0392909216919091179055005b63cf158be360e01b5f5260045ffd5b34610287575f366003190112610287576003546040516001600160a01b039091168152602090f35b3461028757604036600319011261028757611c846123a1565b60243590611c906128cb565b6001600160a01b038116918215611dbe5760ff5f51602061323a5f395f51905f525416611d61575b611cc760075460065490612701565b43106113745760207fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91611d145f948686525f51602061313a5f395f51905f528452604086205490612f9a565b611d2c815f51602061319a5f395f51905f5254612701565b5f51602061319a5f395f51905f52558484525f51602061313a5f395f51905f52825260408420818154019055604051908152a3005b5f805260096020527fec8156718a8372b1db44bb411437d0870f3e3790d4a08526d024ce1b0b668f6b5460ff168015611da8575b611cb85763d93c066560e01b5f5260045ffd5b50825f52600860205260ff60405f205416611d95565b63ec442f0560e01b5f525f60045260245ffd5b34610287575f3660031901126102875760035460405163b9fe5cf760e01b81526001600160a01b0390911690602081600481855afa9081156117e1575f91611eda575b50604051632474521560e21b815260048101919091523360248201529060209082908180604481015b03915afa9081156117e1575f91611ebb575b50156117a3575f51602061323a5f395f51905f525460ff811615611eac5760ff19165f51602061323a5f395f51905f52557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1005b638dfc202b60e01b5f5260045ffd5b611ed4915060203d6020116117da576117cc8183612418565b81611e4f565b90506020813d602011611f06575b81611ef560209383612418565b810103126102875751611e3d611e14565b3d9150611ee8565b34610287575f3660031901126102875760405f5460015482519182526020820152f35b3461028757604036600319011261028757611f4a6123b7565b336001600160a01b03821603611f6657610dea90600435612cfb565b63334bd91960e11b5f5260045ffd5b34610287575f366003190112610287576020611f8f612e12565b604051908152f35b34610287575f36600319011261028757602060405160128152f35b3461028757604036600319011261028757610dea600435611fd16123b7565b90611ff7610de0825f525f51602061321a5f395f51905f52602052600160405f20015490565b612c57565b34610287576020366003190112610287576020611f8f6004355f525f51602061321a5f395f51905f52602052600160405f20015490565b34610287576020366003190112610287576004546001600160a01b031633036118a157600435600755005b34610287576060366003190112610287576120776123a1565b61207f6123b7565b6044359061208c8361248c565b335f908152602091909152604090205492600184016120b0575b611228935061296d565b82841061211b576001600160a01b038116156121085733156120f557611228936120d98261248c565b60018060a01b0333165f526020528360405f20910390556120a6565b634a1406b160e11b5f525f60045260245ffd5b63e602df0560e01b5f525f60045260245ffd5b8284637dc7a0d960e11b5f523360045260245260445260645ffd5b346102875760603660031901126102875760406110866121546123a1565b604435906024359061270e565b346102875760203660031901126102875761217a61286f565b600435600655005b34610287575f3660031901126102875760205f51602061319a5f395f51905f5254604051908152f35b34610287575f366003190112610287576004546040516001600160a01b039091168152602090f35b3461028757610dea6121e4366123cd565b906121ed61286f565b60018060a01b03165f52600960205260405f209060ff801983541691151516179055565b34610287575f36600319011261028757612229612800565b5f545f1981019081116103605760026122425f92612696565b500155005b34610287576040366003190112610287576112286122636123a1565b6024359033612daf565b34610287575f366003190112610287576040515f5f51602061311a5f395f51905f5254612299816124e2565b80845290600181169081156114c657506001146122c0576111fe8361144881850382612418565b5f51602061311a5f395f51905f525f9081527f2ae08a8e29253f69ac5d979a101956ab8f8d9d7ded63fa7a83b16fc47648eab0939250905b80821061231057509091508101602001611448611438565b9192600181602092548385880101520191019092916122f8565b34610287576020366003190112610287576004359063ffffffff60e01b821680920361028757602091637965db0b60e01b811490811561236c575b5015158152f35b6301ffc9a760e01b14905083612365565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b600435906001600160a01b038216820361028757565b602435906001600160a01b038216820361028757565b6040906003190112610287576004356001600160a01b0381168103610287579060243580151581036102875790565b6060810190811067ffffffffffffffff82111761038757604052565b90601f8019910116810190811067ffffffffffffffff82111761038757604052565b67ffffffffffffffff811161038757601f01601f191660200190565b9291926124628261243a565b916124706040519384612418565b829481845281830111610287578281602093845f960137010152565b6001600160a01b03165f9081527f52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace016020526040902090565b9080601f83011215610287578160206124df93359101612456565b90565b90600182811c92168015612510575b60208310146124fc57565b634e487b7160e01b5f52602260045260245ffd5b91607f16916124f1565b604051905f825f51602061315a5f395f51905f525491612539836124e2565b80835292600181169081156125ca575060011461255f575b61255d92500383612418565b565b505f51602061315a5f395f51905f525f90815290917f42ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57d5b8183106125ae57505090602061255d92820101612551565b6020919350806001915483858901015201910190918492612596565b6020925061255d94915060ff191682840152151560051b820101612551565b604051905f825f5160206131ba5f395f51905f525491612608836124e2565b80835292600181169081156125ca575060011461262b5761255d92500383612418565b505f5160206131ba5f395f51905f525f90815290917f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b755b81831061267a57505090602061255d92820101612551565b6020919350806001915483858901015201910190918492612662565b6002548110156126b25760025f52600360205f20910201905f90565b634e487b7160e01b5f52603260045260245ffd5b906040516126d3816123fc565b60406002829480548452600181015460208501520154910152565b8181029291811591840414171561036057565b9190820180921161036057565b6001600160a01b03165f908152600560205260409020909290612730906126c6565b9081516040602084015193015184156127dc578482146127d35781935b5f1986018681116103605785101561278f57612787600191620f424061278060026127778a612696565b5001548b6126ee565b0490612701565b94019361274d565b929450909250826127a2575b5090509190565b5f19830192831161036057612780620f42409160026127c36127cc96612696565b500154906126ee565b805f61279b565b94505091509190565b5050925050505f905f90565b90816020910312610287575180151581036102875790565b335f9081527fb2ce6f3a0968c56a08b54f4f0d1d0af4871f2c3340441c6ce862aaa53c9d37c7602052604090205460ff161561283857565b63e2517d3f60e01b5f52336004527ffbd454f36a7e1a388bd6fc3ab10d434aa4578f811acbbcf33afb1c697486313c60245260445ffd5b335f9081527fa7d0f56144dc2cc0b8cc25b72dae5de5732359403e6b65d51614ec6c3aaaf2c8602052604090205460ff16156128a757565b63e2517d3f60e01b5f52336004525f51602061327a5f395f51905f5260245260445ffd5b335f9081527f549fe2656c81d2947b3b913f0a53b9ea86c71e049f3a1b8aa23c09a8a05cb8d4602052604090205460ff161561290357565b63e2517d3f60e01b5f52336004525f5160206131fa5f395f51905f5260245260445ffd5b5f8181525f51602061321a5f395f51905f526020908152604080832033845290915290205460ff16156129575750565b63e2517d3f60e01b5f523360045260245260445ffd5b90916001600160a01b0382169182156113e1576001600160a01b038416938415611dbe5760ff5f51602061323a5f395f51905f525416612aa0575b6129b760075460065490612701565b4310611374576129e3612a0292855f525f51602061313a5f395f51905f5260205260405f205490612f9a565b845f525f51602061313a5f395f51905f5260205260405f205490612f9a565b815f525f51602061313a5f395f51905f5260205260405f2054818110612a8757817fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92602092855f525f51602061313a5f395f51905f5284520360405f2055845f525f51602061313a5f395f51905f52825260405f20818154019055604051908152a3565b8263391434e360e21b5f5260045260245260445260645ffd5b835f52600960205260ff60405f2054168015612aca575b6129a85763d93c066560e01b5f5260045ffd5b50845f52600860205260ff60405f205416612ab7565b6001600160a01b0381165f9081527f549fe2656c81d2947b3b913f0a53b9ea86c71e049f3a1b8aa23c09a8a05cb8d4602052604090205460ff16612b99576001600160a01b03165f8181527f549fe2656c81d2947b3b913f0a53b9ea86c71e049f3a1b8aa23c09a8a05cb8d460205260408120805460ff191660011790553391905f5160206131fa5f395f51905f52907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b505f90565b6001600160a01b0381165f9081527fa7d0f56144dc2cc0b8cc25b72dae5de5732359403e6b65d51614ec6c3aaaf2c8602052604090205460ff16612b99576001600160a01b03165f8181527fa7d0f56144dc2cc0b8cc25b72dae5de5732359403e6b65d51614ec6c3aaaf2c860205260408120805460ff191660011790553391905f51602061327a5f395f51905f52907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b5f8181525f51602061321a5f395f51905f52602090815260408083206001600160a01b038616845290915290205460ff16612cf5575f8181525f51602061321a5f395f51905f52602090815260408083206001600160a01b0395909516808452949091528120805460ff19166001179055339291907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b50505f90565b5f8181525f51602061321a5f395f51905f52602090815260408083206001600160a01b038616845290915290205460ff1615612cf5575f8181525f51602061321a5f395f51905f52602090815260408083206001600160a01b0395909516808452949091528120805460ff19169055339291907ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9080a4600190565b60ff5f51602061323a5f395f51905f52541661139f57565b916001600160a01b038316918215612108576001600160a01b03169283156120f5577f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591612dfe60209261248c565b855f5282528060405f2055604051908152a3565b612e1a61300c565b612e22613076565b6040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a08152612e7360c082612418565b51902090565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411612ef0579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa156117e1575f516001600160a01b03811615612ee657905f905f90565b505f906001905f90565b5050505f9160039190565b6004811015612f5b5780612f0d575050565b60018103612f245763f645eedf60e01b5f5260045ffd5b60028103612f3f575063fce698f760e01b5f5260045260245ffd5b600314612f495750565b6335e2f38360e21b5f5260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b60ff5f51602061325a5f395f51905f525460401c1615612f8b57565b631afcd79f60e31b5f5260045ffd5b7f6b9c497481d518e22778a9623f00f75d627901dcdbb45461f008d640e34ed4f691606091612fcc5f5480938361270e565b6001600160a01b039092165f81815260056020908152604091829020600181018590558681556002019490945580519182529281019390935290820152a1565b61301461251a565b8051908115613024576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1005480156130515790565b507fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090565b61307e6125e9565b805190811561308e576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1015480156130515790565b906130df57508051156130d057805190602001fd5b630a12f52160e11b5f5260045ffd5b81511580613110575b6130f0575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b156130e856fe52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0352c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d10252c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace0452c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace02a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a602dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800cd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a000603f2636f0ca34ae3ea5a23bb826e2bd2ffd59fb1c01edc1ba10fba2899d1baa2646970667358221220216c651b798b40dbfb362c9682490d6df9c3a20f8239e2caed3dc07c6f539dce64736f6c634300081e0033
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 34 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.