ETH Price: $4,481.31 (-4.82%)

Contract

0x64866d080CfEf0e45A3a64A558dA6eEAD7542657
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Token Holdings

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Get Reward235328442025-10-08 11:50:471 hr ago1759924247IN
0x64866d08...AD7542657
0 ETH0.00013771.65945416
Get Reward235246962025-10-07 8:30:4728 hrs ago1759825847IN
0x64866d08...AD7542657
0 ETH0.000009990.2218298
Withdraw235246872025-10-07 8:28:5928 hrs ago1759825739IN
0x64866d08...AD7542657
0 ETH0.000033290.23013502
Get Reward235185112025-10-06 11:44:112 days ago1759751051IN
0x64866d08...AD7542657
0 ETH0.000093761.36630622
Withdraw235170002025-10-06 6:40:112 days ago1759732811IN
0x64866d08...AD7542657
0 ETH0.000128331.12466487
Get Reward235159862025-10-06 3:16:232 days ago1759720583IN
0x64866d08...AD7542657
0 ETH0.000070881.10971223
Get Reward234973242025-10-03 12:42:355 days ago1759495355IN
0x64866d08...AD7542657
0 ETH0.000104431.2585212
Distribute Rewar...234956212025-10-03 7:00:115 days ago1759474811IN
0x64866d08...AD7542657
0 ETH0.000140221.11603984
Get Reward234888352025-10-02 8:12:596 days ago1759392779IN
0x64866d08...AD7542657
0 ETH0.000107171.29158129
Withdraw234829232025-10-01 12:22:477 days ago1759321367IN
0x64866d08...AD7542657
0 ETH0.000040190.36387595
Withdraw234687322025-09-29 12:45:239 days ago1759149923IN
0x64866d08...AD7542657
0 ETH0.001427538.41772075
Get Reward234626472025-09-28 16:20:359 days ago1759076435IN
0x64866d08...AD7542657
0 ETH0.000019780.28833047
Distribute Rewar...234454902025-09-26 6:45:1112 days ago1758869111IN
0x64866d08...AD7542657
0 ETH0.000170211.19240757
Get Reward234233642025-09-23 4:32:4715 days ago1758601967IN
0x64866d08...AD7542657
0 ETH0.000042430.61835782
Distribute Rewar...233953932025-09-19 6:40:1119 days ago1758264011IN
0x64866d08...AD7542657
0 ETH0.000152531.21396703
Withdraw233588332025-09-14 4:09:1124 days ago1757822951IN
0x64866d08...AD7542657
0 ETH0.000034270.30260219
Get Reward233582112025-09-14 2:03:5924 days ago1757815439IN
0x64866d08...AD7542657
0 ETH0.000078991.15119367
Delegate233483832025-09-12 17:09:4725 days ago1757696987IN
0x64866d08...AD7542657
0 ETH0.000176471.50738504
Distribute Rewar...233451462025-09-12 6:20:1126 days ago1757658011IN
0x64866d08...AD7542657
0 ETH0.000170351.19338578
Stake233373722025-09-11 4:15:2327 days ago1757564123IN
0x64866d08...AD7542657
0 ETH0.00005290.3928069
Withdraw233243352025-09-09 8:27:1129 days ago1757406431IN
0x64866d08...AD7542657
0 ETH0.000223041.30878187
Get Reward233241682025-09-09 7:53:3529 days ago1757404415IN
0x64866d08...AD7542657
0 ETH0.000084781.32732674
Get Reward233207232025-09-08 20:21:3529 days ago1757362895IN
0x64866d08...AD7542657
0 ETH0.000089751.30799232
Get Reward233069942025-09-06 22:19:5931 days ago1757197199IN
0x64866d08...AD7542657
0 ETH0.000081451.18691336
Distribute Rewar...232950532025-09-05 6:15:1133 days ago1757052911IN
0x64866d08...AD7542657
0 ETH0.000152831.21642142
View all transactions

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Cross-Chain Transactions

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
TempleGoldStaking

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 999999 runs

Other Settings:
paris EvmVersion
File 1 of 43 : TempleGoldStaking.sol
pragma solidity ^0.8.20;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (templegold/TempleGoldStaking.sol)


import { CommonEventsAndErrors } from "contracts/common/CommonEventsAndErrors.sol";
import { TempleElevatedAccess } from "contracts/v2/access/TempleElevatedAccess.sol";
import { ITempleGold } from "contracts/interfaces/templegold/ITempleGold.sol";
import { ITempleGoldStaking } from "contracts/interfaces/templegold/ITempleGoldStaking.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/** 
 * @title Temple Gold Staking
 * @notice Temple Gold Staking contract. Stakers deposit Temple and claim rewards in Temple Gold. 
 * Temple Gold is distributed to staking contract for stakers on mint.
 * Duration for distributing staking rewards is set with `setRewardDuration`. An unstake period is used
 * to encourage longer staking times.
 */
contract TempleGoldStaking is ITempleGoldStaking, TempleElevatedAccess, Pausable {
    using SafeERC20 for IERC20;

    /// @notice The staking token. Temple
    IERC20 public immutable override stakingToken;
    /// @notice Reward token. Temple Gold
    IERC20 public immutable override rewardToken;

    /// @notice Distribution starter
    address public override distributionStarter;
    /// @notice DAO executor
    address public override daoExecutor;
    /// @notice Week length
    uint256 constant public WEEK_LENGTH = 7 days;
    /// @notice Total supply of staking token
    uint256 public override totalSupply;

    /// @notice Store next reward amount for next epoch
    uint256 public override nextRewardAmount;
    /// @notice Duration for rewards distribution
    uint256 public override rewardDuration;
    /// @notice Cooldown time before next distribution of rewards
    /// @dev If set to zero, rewards distribution is callable any time 
    uint160 public override rewardDistributionCoolDown;
    /// @notice Timestamp for last reward notification
    uint96 public override lastRewardNotificationTimestamp;
    /// @notice Cooldown time before unstake
    uint32 public override unstakeCooldown;
    /// @notice Maximum unstake cooldown
    uint32 constant public MAXIMUM_UNSTAKE_COOLDOWN = 30 days;

    /// @notice For use when migrating to a new staking contract if TGLD changes.
    address public override migrator;
    /// @notice Data struct for rewards
    Reward internal rewardData;
    /// @notice Staker balances
    mapping(address account => uint256 balance) private _balances;
    /// @notice Account vote delegates
    mapping(address account => address delegate) public delegates;
    /// @notice Stakers claimable rewards
    mapping(address account => uint256 amount) public override claimableRewards;
    /// @notice Staker reward per token paid
    mapping(address account => uint256 amount) public override userRewardPerTokenPaid;
    /// @notice Track voting checkpoints
    mapping(address account => mapping(uint256 epoch => Checkpoint)) private _checkpoints;
    /// @notice Track number of checkpoint for account
    mapping(address account => uint256 number) public override numCheckpoints;
    /// @notice Track stake times for accounts
    mapping(address account => uint256 stakeTime) public override stakeTimes;
    
    constructor(
        address _rescuer,
        address _executor,
        address _stakingToken,
        address _rewardToken
    ) TempleElevatedAccess(_rescuer, _executor){
        stakingToken = IERC20(_stakingToken);
        rewardToken = IERC20(_rewardToken);
    }

    /**
     * @notice Set unstake cooldown
     * @param _period Cooldown period. Zero value accepted to disable cooldown feature
     */
    function setUnstakeCooldown(uint32 _period) external override onlyElevatedAccess {
        if (_period > MAXIMUM_UNSTAKE_COOLDOWN) { revert CommonEventsAndErrors.InvalidParam(); }
        unstakeCooldown = _period;
        emit UnstakeCooldownSet(_period);
    }

    /**
     * @notice Set reward duration
     * @param _duration Reward duration
     */
    function setRewardDuration(uint256 _duration) external override onlyElevatedAccess {
        // minimum reward duration
        if (_duration < WEEK_LENGTH) { revert CommonEventsAndErrors.InvalidParam(); }
        // only change after reward epoch ends
        if (rewardData.periodFinish >= block.timestamp) { revert InvalidOperation(); }
        rewardDuration = _duration;
        emit RewardDurationSet(_duration);
    }

    /**
     * @notice Set starter of rewards distribution
     * @param _starter Starter address
     */
    function setDistributionStarter(address _starter) external onlyElevatedAccess {
        if (_starter == address(0)) { revert CommonEventsAndErrors.InvalidAddress(); }
        distributionStarter = _starter;
        emit DistributionStarterSet(_starter);
    }

    /**
     * @notice Set migrator
     * @param _migrator Migrator
     */
    function setMigrator(address _migrator) external override onlyElevatedAccessUntilDAO {
        if (_migrator == address(0)) { revert CommonEventsAndErrors.InvalidAddress(); }
        migrator = _migrator;
        emit MigratorSet(_migrator);
    }

    /**
     * @notice Set DAO executor
     * @param _executor DAO executor
     */
    function setDaoExecutor(address _executor) external override onlyElevatedAccessUntilDAO {
        if (_executor == address(0)) { revert CommonEventsAndErrors.InvalidAddress(); }
        daoExecutor = _executor;
        emit DAOExecutorSet(_executor);
    }

    /**
     * @notice Delegate votes from `msg.sender` to `delegatee`
     * @param delegatee The address to delegate votes to
     */
    function delegate(address delegatee) external override {
        return _delegate(msg.sender, delegatee);
    }

    /**
     * @notice Set reward distribution cooldown
     * @param _cooldown Cooldown in seconds
     */
    function setRewardDistributionCoolDown(uint160 _cooldown) external override onlyElevatedAccess {
        /// @dev zero cooldown is allowed
        rewardDistributionCoolDown = _cooldown;
        emit RewardDistributionCoolDownSet(_cooldown);
    }

    /**
      * @notice For migrations to a new staking contract
      *         1. Withdraw `staker`s tokens to the new staking contract (the migrator)
      *         2. Any existing rewards are claimed and sent directly to the `staker`
      * @dev Called only from the new staking contract (the migrator).
      *      `setMigrator(new_staking_contract)` needs to be called first
      * @param staker The staker who is being migrated to a new staking contract.
      * @return Staker balance
      */
    function migrateWithdraw(address staker) external override onlyMigrator returns (uint256) {
        if (staker == address(0)) { revert CommonEventsAndErrors.InvalidAddress(); }
        uint256 stakerBalance = _balances[staker];
        _withdrawFor(staker, msg.sender, stakerBalance, true, staker);
        return stakerBalance;
    }
    
    /**
     * @notice Distributed TGLD rewards minted to this contract to stakers
     * @dev This starts another epoch of rewards distribution. Calculates new `rewardRate` from any left over rewards up until now
     */
    function distributeRewards() external override whenNotPaused updateReward(address(0)) {
        if (msg.sender != distributionStarter) { revert CommonEventsAndErrors.InvalidAccess(); }
        if (totalSupply == 0) { revert NoStaker(); }
        // Mint and distribute TGLD if no cooldown set
        if (lastRewardNotificationTimestamp + rewardDistributionCoolDown > block.timestamp) 
                { revert CannotDistribute(); }
        _distributeGold();
        uint256 rewardAmount = nextRewardAmount;
        // revert if next reward is 0 or less than reward duration (final dust amounts)
        if (rewardAmount < rewardDuration ) { revert CommonEventsAndErrors.ExpectedNonZero(); }
        nextRewardAmount = 0;
        _notifyReward(rewardAmount);
    }

    /**
     * @notice Gets the current votes balance for `account`
     * @param account The address to get votes balance
     * @return The number of current votes for `account`
     */
    function getCurrentVotes(address account) external override view returns (uint256) {
        uint256 nCheckpoints = numCheckpoints[account];
        return nCheckpoints > 0 ? _checkpoints[account][nCheckpoints - 1].votes : 0;
    }

    /**
     * @notice Determine the prior number of votes for an account as of a block number
     * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
     * @param account The address of the account to check
     * @param blockNumber The block number to get the vote balance at
     * @return The number of votes the account had as of the given block
     */
    function getPriorVotes(address account, uint256 blockNumber) external override view returns (uint256) {
        if (blockNumber >= block.number) { revert InvalidBlockNumber(); }

        uint256 nCheckpoints = numCheckpoints[account];
        if (nCheckpoints == 0) {
            return 0;
        }

        // First check most recent balance
        if (_checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
            return _checkpoints[account][nCheckpoints - 1].votes;
        }

        // Next check implicit zero balance
        if (_checkpoints[account][0].fromBlock > blockNumber) {
            return 0;
        }

        uint256 lower = 0;
        uint256 upper = nCheckpoints - 1;
        while (upper > lower) {
            uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
            Checkpoint memory cp = _checkpoints[account][center];
            if (cp.fromBlock == blockNumber) {
                return cp.votes;
            } else if (cp.fromBlock < blockNumber) {
                lower = center;
            } else {
                upper = center - 1;
            }
        }
        return _checkpoints[account][lower].votes;
    }

    /**
     * @notice Stake for an account when contract is not paused
     * @param amount Amount of staking token
     */
    function stake(uint256 amount) external override whenNotPaused {
        _stake(msg.sender, amount);
    }

    /**
     * @notice Private stake function.
     * @param _for Staking account
     * @param _amount Amount of staking token
     */
    function _stake(address _for, uint256 _amount) private  {
        if (_amount == 0) revert CommonEventsAndErrors.ExpectedNonZero();
        
        // pull tokens and apply stake
        stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
        _applyStake(_for, _amount);
        _moveDelegates(address(0), delegates[_for], _amount);
    }

    /**
     * @notice Withdraw staked tokens
     * @param amount Amount to withdraw
     * @param claimRewards Whether to claim rewards
     */
    function withdraw(uint256 amount, bool claimRewards) external override whenNotPaused {
        /// @dev Check here so migrationWithdraw can skip this in emergency cases
        uint256 unstakeTime = stakeTimes[msg.sender] + unstakeCooldown;
        if (unstakeTime > block.timestamp) { revert UnstakeCooldown(block.timestamp, unstakeTime); }
        _withdrawFor(msg.sender, msg.sender, amount, claimRewards, msg.sender);
    }

    /// @notice Owner can pause user swaps from occuring
    function pause() external override onlyElevatedAccess {
        _pause();
    }

    /// @notice Owner can unpause so user swaps can occur
    function unpause() external override onlyElevatedAccess {
        _unpause();
    }

    /**
     * @notice Get account checkpoint data 
     * @param account Account
     * @param epoch Epoch
     * @return Checkpoint data
     */
    function getCheckpoint(address account, uint256 epoch) external override view returns (Checkpoint memory) {
        return _checkpoints[account][epoch];
    }

    /**
     * @notice Get account staked balance
     * @param account Account
     * @return Staked balance of account
     */
    function balanceOf(address account) public override view returns (uint256) {
        return _balances[account];
    }

    /**
     * @notice Get earned rewards of account
     * @param account Account
     * @return Earned rewards of account
     */
    function earned(address account) external override view returns (uint256) {
        uint256 rewardPerToken_ = _rewardPerToken();
        return _earned(account, rewardPerToken_);
    }

    /**
     * @notice Get Temple Gold reward per token of Temple 
     * @return Reward per token
     */
    function rewardPerToken() external override view returns (uint256) {
        return _rewardPerToken();
    }

    /**
     * @notice Get finish timestamp of rewards
     * @return Finish timestamp
     */
    function rewardPeriodFinish() external view returns (uint40) {
        return rewardData.periodFinish;
    }

    /**
     * @notice Get account unstake time
     * @param account Account
     * @return Unstake time
     */
    function getAccountUnstakeTime(address account) external override view returns (uint256) {
        return stakeTimes[account] == 0 ? 0 : stakeTimes[account] + unstakeCooldown;
    }

    /**
     * @notice Elevated access can recover tokens which are not staking or reward tokens
     * @param _token Token to recover
     * @param _to Recipient
     * @param _amount Amount of tokens
     */
    function recoverToken(address _token, address _to, uint256 _amount) external override onlyElevatedAccess {
        if (_token == address(stakingToken) || _token == address(rewardToken )) 
            { revert CommonEventsAndErrors.InvalidAddress(); }

        IERC20(_token).safeTransfer(_to, _amount);
        emit CommonEventsAndErrors.TokenRecovered(_to, _token, _amount);
    }

    /**  
     * @notice Get rewards
     * @param staker Staking account
     */
    function getReward(
        address staker
    ) external override whenNotPaused updateReward(staker) {
        _getReward(staker, staker);
    }

    /**  
     * @notice Mint and distribute Temple Gold rewards 
     */
    function distributeGold() external whenNotPaused {
        _distributeGold();
    }

    /**  
     * @notice Notify rewards distribution. Called by TempleGold contract after successful mint
     * @param amount Amount minted to this contract
     */
    function notifyDistribution(uint256 amount) external override {
        if (msg.sender != address(rewardToken) && !isElevatedAccess(msg.sender, msg.sig)) { revert CommonEventsAndErrors.InvalidAccess(); }
        /// @notice Temple Gold contract mints TGLD amount to contract before calling `notifyDistribution`
        nextRewardAmount += amount;
        emit GoldDistributionNotified(amount, block.timestamp);
    }
    
    /**  
     * @notice Get reward data
     * @return Reward data
     */
    function getRewardData() external override view returns (Reward memory) {
        return rewardData;
    }

    function _getReward(address _staker, address _to) internal {
        uint256 amount = claimableRewards[_staker];
        if (amount > 0) {
            claimableRewards[_staker] = 0;
            rewardToken.safeTransfer(_to, amount);
            emit RewardPaid(_staker, _to, amount);
        }
    }

    function _withdrawFor(
        address _staker,
        address _to,
        uint256 _amount,
        bool _claimRewards,
        address _rewardsTo
    ) private updateReward(_staker) {
        if (_amount == 0) { revert CommonEventsAndErrors.ExpectedNonZero(); }
        uint256 _balance = _balances[_staker];
        if (_amount > _balance) 
            { revert CommonEventsAndErrors.InsufficientBalance(address(stakingToken), _amount, _balance); }
        unchecked {
            _balances[_staker] = _balance - _amount;
        }
        totalSupply -= _amount;
        _moveDelegates(delegates[_staker], address(0), _amount);

        stakingToken.safeTransfer(_to, _amount);
        emit Withdrawn(_staker, _to, _amount);

        // claim reward
        if (_claimRewards) {
            // can call internal because user reward already updated
            _getReward(_staker, _rewardsTo);
        }
    }

    function _earned(
        address account_,
        uint256 rewardPerToken_
    ) internal view returns (uint256) {
        return _balances[account_] * (rewardPerToken_ - userRewardPerTokenPaid[account_]) / 1e18 
            + claimableRewards[account_];
    }

    function _applyStake(address _for, uint256 _amount) internal updateReward(_for) {
        totalSupply += _amount;
        _balances[_for] += _amount;
        stakeTimes[_for] = block.timestamp;
        emit Staked(_for, _amount);
    }

    function _rewardPerToken() internal view returns (uint256) {
        if (totalSupply == 0 || rewardData.lastUpdateTime == rewardData.periodFinish) {
            return rewardData.rewardPerTokenStored;
        }

        return
            rewardData.rewardPerTokenStored +
            (((_lastTimeRewardApplicable(rewardData.periodFinish) -
                rewardData.lastUpdateTime) *
                rewardData.rewardRate * 1e18)
                / totalSupply);
    }

    function _notifyReward(uint256 amount) private {
        uint256 rewardDurationCache = rewardDuration;
        if (block.timestamp >= rewardData.periodFinish) {
            rewardData.rewardRate = uint216(amount / rewardDurationCache);
            // collect dust
            nextRewardAmount = amount - (rewardData.rewardRate * rewardDurationCache);
        } else {
            uint256 remaining = uint256(rewardData.periodFinish) - block.timestamp;
            uint256 leftover = remaining * rewardData.rewardRate;
            rewardData.rewardRate = uint216((amount + leftover) / rewardDurationCache);
            // collect dust
            nextRewardAmount = (amount + leftover) - (rewardData.rewardRate * rewardDurationCache);
        }
        rewardData.lastUpdateTime = uint40(block.timestamp);
        rewardData.periodFinish = uint40(block.timestamp + rewardDurationCache);
        // update reward notification timestamp
        lastRewardNotificationTimestamp = uint32(block.timestamp);
    }

    function _lastTimeRewardApplicable(uint256 _finishTime) internal view returns (uint256) {
        if (_finishTime < block.timestamp) {
            return _finishTime;
        }
        return block.timestamp;
    }

    function _distributeGold() internal {
        /// @dev no op silent fail if nothing to distribute
        ITempleGold(address(rewardToken)).mint();
    }

    function _delegate(address delegator, address delegatee) internal {
        address currentDelegate = delegates[delegator];
        uint256 delegatorBalance = _balances[delegator];
        delegates[delegator] = delegatee;

        emit DelegateChanged(delegator, currentDelegate, delegatee);
        _moveDelegates(currentDelegate, delegatee, delegatorBalance);
    }

    function _moveDelegates(
        address srcRep,
        address dstRep,
        uint256 amount
    ) internal {
        if (srcRep != dstRep && amount > 0) {
            if (srcRep != address(0)) {
                uint256 srcRepNum = numCheckpoints[srcRep];
                uint256 srcRepOld = srcRepNum > 0 ? _checkpoints[srcRep][srcRepNum - 1].votes : 0;
                uint256 srcRepNew = srcRepOld - amount;
                _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
            }

            if (dstRep != address(0)) {
                uint256 dstRepNum = numCheckpoints[dstRep];
                uint256 dstRepOld = dstRepNum > 0 ? _checkpoints[dstRep][dstRepNum - 1].votes : 0;
                uint256 dstRepNew = dstRepOld + amount;
                _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
            }
        }
    }

    function _writeCheckpoint(
        address delegatee,
        uint256 nCheckpoints,
        uint256 oldVotes,
        uint256 newVotes
    ) internal {
        if (nCheckpoints > 0 && _checkpoints[delegatee][nCheckpoints - 1].fromBlock == block.number) {
            _checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
        } else {
            _checkpoints[delegatee][nCheckpoints] = Checkpoint(block.number, newVotes);
            numCheckpoints[delegatee] = nCheckpoints + 1;
        } 
        emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
    }

    modifier updateReward(address _account) {
        {
            uint216 rewardPerTokenCached = rewardData.rewardPerTokenStored = uint216(_rewardPerToken());
            rewardData.lastUpdateTime = uint40(_lastTimeRewardApplicable(rewardData.periodFinish));
            if (_account != address(0)) {
                claimableRewards[_account] = _earned(_account, rewardPerTokenCached);
                userRewardPerTokenPaid[_account] = uint256(rewardPerTokenCached);
            }
        }
        _;
    }
    
    modifier onlyMigrator() {
        if (msg.sender != migrator) { revert CommonEventsAndErrors.InvalidAccess(); }
        _;
    }

    modifier onlyElevatedAccessUntilDAO() {
        if (daoExecutor == address(0)) {
            if (!isElevatedAccess(msg.sender, msg.sig)) revert CommonEventsAndErrors.InvalidAccess();
        } else if(msg.sender != daoExecutor) {
            revert CommonEventsAndErrors.InvalidAccess();
        }
        _;
    }
}

// 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;

/**
 * @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;

/**
 * @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
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 { 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);
    }
}

File 7 of 43 : OApp.sol
// 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

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

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 { 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: MIT

pragma solidity ^0.8.20;

import { MessagingReceipt, MessagingFee } from "../../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 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 a quote for OFT-related operations.
     * @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;

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 from 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 from 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.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;

import { OApp, Origin } from "../oapp/OApp.sol";
import { OAppOptionsType3 } from "../oapp/libs/OAppOptionsType3.sol";
import { IOAppMsgInspector } from "../oapp/interfaces/IOAppMsgInspector.sol";

import { OAppPreCrimeSimulator } from "../precrime/OAppPreCrimeSimulator.sol";

import { IOFT, SendParam, OFTLimit, OFTReceipt, OFTFeeDetail, MessagingReceipt, MessagingFee } from "./interfaces/IOFT.sol";
import { OFTMsgCodec } from "./libs/OFTMsgCodec.sol";
import { OFTComposeMsgCodec } from "./libs/OFTComposeMsgCodec.sol";

/**
 * @title OFTCore
 * @dev Abstract contract for the OftChain (OFT) token.
 */
abstract contract OFTCore is IOFT, OApp, OAppPreCrimeSimulator, OAppOptionsType3 {
    using OFTMsgCodec for bytes;
    using OFTMsgCodec for bytes32;

    // @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;

    // Address of an optional contract to inspect both 'message' and 'options'
    address public msgInspector;
    event MsgInspectorSet(address inspector);

    /**
     * @dev Constructor.
     * @param _localDecimals The decimals of the token on the local chain (this chain).
     * @param _endpoint The address of the LayerZero endpoint.
     * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
     */
    constructor(uint8 _localDecimals, address _endpoint, address _delegate) OApp(_endpoint, _delegate) {
        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 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 view 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 {
        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);

        // @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
        if (msgInspector != address(0)) IOAppMsgInspector(msgInspector).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.
     * @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.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.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;

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: MIT

pragma solidity ^0.8.20;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IPreCrime } from "./interfaces/IPreCrime.sol";
import { IOAppPreCrimeSimulator, InboundPacket, Origin } from "./interfaces/IOAppPreCrimeSimulator.sol";

/**
 * @title OAppPreCrimeSimulator
 * @dev Abstract contract serving as the base for preCrime simulation functionality in an OApp.
 */
abstract contract OAppPreCrimeSimulator is IOAppPreCrimeSimulator, Ownable {
    // The address of the preCrime implementation.
    address public 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 {
        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.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.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.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);
}

// 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 _gracePeriod) 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 _expiry) 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 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 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 IMessagingContext {
    function isSendingMessage() external view returns (bool);

    function getSendContext() external view returns (uint32 dstEid, address sender);
}

// 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: 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
// 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
// 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) (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) (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: 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.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/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/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.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 Pausable is Context {
    bool private _paused;

    /**
     * @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.
     */
    constructor() {
        _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) {
        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 {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

File 37 of 43 : CommonEventsAndErrors.sol
pragma solidity ^0.8.20;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (common/CommonEventsAndErrors.sol)

/// @notice A collection of common errors thrown within the Temple contracts
library CommonEventsAndErrors {
    error InsufficientBalance(address token, uint256 required, uint256 balance);
    error InvalidParam();
    error InvalidAddress();
    error InvalidAccess();
    error InvalidAmount(address token, uint256 amount);
    error ExpectedNonZero();
    error Unimplemented();
    event TokenRecovered(address indexed to, address indexed token, uint256 amount);
}

pragma solidity ^0.8.20;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interfaces/templegold/IAuctionBase.sol)


interface IAuctionBase {
    event Deposit(address indexed depositor, uint256 epochId, uint256 amount);
    event Claim(address indexed user, uint256 epochId, uint256 bidTokenAmount, uint256 auctionTokenAmount);
    event AuctionStarted(uint256 epochId, address indexed starter, uint128 startTime, uint128 endTime, uint256 auctionTokenAmount);
    
    error CannotDeposit();
    error CannotClaim(uint256 epochId);
    error CannotStartAuction();
    error InvalidEpoch();
    error AuctionActive();
    error InvalidOperation();
    error AuctionEnded();
    error AlreadyClaimed();
    error AlreadyRecovered();

    struct EpochInfo {
        /// @notice Start time for epoch
        uint128 startTime;
        /// @notice End time for epoch
        uint128 endTime;
        /// @notice Total amount of bid token deposited
        uint256 totalBidTokenAmount;
        /// @notice Total amount of auction tokens to distribute. Constant value
        uint256 totalAuctionTokenAmount;
    }

    /// @notice Keep track of epochs details
    function getEpochInfo(uint256 epochId) external view returns (EpochInfo memory);
    /// @notice Keep track of depositors for each epoch
    function depositors(address depositor, uint256 epochId) external view returns (uint256);
    /// @notice Keep track of claimed accounts per epoch
    function claimed(address depositor, uint256 epochId) external view returns (bool);
    /// @notice claimed amounts
    function claimedAmount(address depositor, uint256 epochId) external view returns (uint256);

    /**
     * @notice Deposit bid token for current running epoch auction
     * @param amount Amount of bid token to deposit
     */
    function bid(uint256 amount) external;

    /**
     * @notice Start auction. Auction start can be triggered by anyone if `auctionStarter` not set
     * Uses up to date distributed Temple Gold tokens since last auction as total Temple Gold for distribution
     */
    function startAuction() external;

    /**
     * @notice Get current epoch
     * @return Epoch Id
     */
    function currentEpoch() external view returns (uint256);

    /**
     * @notice Recover auction tokens for last but not started auction
     * @param token Token to recover
     * @param to Recipient
     * @param amount Amount to auction tokens
     */
    function recoverToken(address token, address to, uint256 amount) external;

    /// @notice Check if TGLD for epoch without bid is recovered
    function epochsWithoutBidsRecovered(uint256 epochId) external view returns (bool);
}

pragma solidity ^0.8.20;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interfaces/templegold/IStableGoldAuction.sol)

import { IAuctionBase } from "contracts/interfaces/templegold/IAuctionBase.sol";
import { ITempleGold } from "contracts/interfaces/templegold/ITempleGold.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IStableGoldAuction is IAuctionBase {
    event BidTokenSet(address bidToken);
    event GoldDistributionNotified(uint256 amount, uint256 timestamp);
    event AuctionConfigSet(uint256 epochId, AuctionConfig config);
    event AuctionStarterSet(address indexed starter);

    error LowGoldDistributed(uint256 epochGoldAmount);

    struct AuctionConfig {
        /// @notice Time diff between two auctions. Usually 1 week
        uint32 auctionsTimeDiff;
        /// @notice Cooldown after auction start is triggered, to allow deposits
        uint32 auctionStartCooldown;
        /// @notice Minimum Gold distributed to enable auction start
        uint192 auctionMinimumDistributedGold;
    }

    /// @notice Temple Gold address
    function templeGold() external view returns (ITempleGold);

    /// @notice Token to bid for Temple GOLD
    function bidToken() external view returns (IERC20);

    /// @notice Destination address for proceeds of auctions
    function treasury() external view returns (address);

    /// @notice Address that can trigger start of auction. address(0) means anyone
    function auctionStarter() external view returns (address);

    /// @notice Keep track of next epoch auction Temple Gold amount
    function nextAuctionGoldAmount() external view returns (uint256);

    /**
     * @notice Recover auction tokens for epoch with zero bids
     * @param epochId Epoch Id
     * @param to Recipient
     */
    function recoverTempleGoldForZeroBidAuction(uint256 epochId, address to) external;

    /**
     * @notice Get auction configuration
     * @return Auction configuration
     */
    function getAuctionConfig() external view returns (AuctionConfig memory);

    /**
     * @notice Set auction configuration
     * @param _config Auction configuration
     */
    function setAuctionConfig(AuctionConfig calldata _config) external;

    /**
     * @notice Set token used for bidding
     * @param _bidToken Bid token
     */
    function setBidToken(address _bidToken) external;

    /**
     * @notice Set address to trigger auction start. Zero address accepted
     * @param _starter Auction starter
     */
    function setAuctionStarter(address _starter) external;

    /**
     * @notice Get Temple Gold supply for epoch
     * @param epochId Epoch Id
     * @return Temple Gold supply
     */
    function epochGoldSupply(uint256 epochId) external view returns (uint256);

    /**
     * @notice Get next epoch
     * @return Next epoch Id
     */
    function nextEpoch() external view returns (uint256);

    /**
     * @notice Check if current epoch ended. That is, if current auction ended.
     * @return Bool if epoch ended
     */
    function isCurrentEpochEnded() external view returns (bool);

     /**
     * @notice Checkpoint total Temple Gold distributed for next epoch.
     * Can only be called by Temple Gold contract
     * @param amount Amount of Temple Gold to checkpoint
     */
    function notifyDistribution(uint256 amount) external;

    /**
     * @notice Check if current auction epoch is allowing bid deposits
     * @return Bool if allowing deposit
     */
    function canDeposit() external view returns (bool);

    /**
     * @notice Mint and distribute TGLD 
     */
    function distributeGold() external;

    /**
     * @notice Get claimable amount for current epoch
     * @dev For current epoch, function will return claimable at current time. This can change with more user deposits
     * @param depositor Address to check amount for
     * @return Claimable amount
     */
    function getClaimableAtCurrentEpoch(address depositor) external view returns (uint256);

    /**
     * @notice Get claimable amount for an epoch
     * @dev For current epoch, function will return claimable at current time. This can change with more user deposits
     * @param depositor Address to check amount for
     * @param epochId Epoch id
     * @return Claimable amount
     */
    function getClaimableAtEpoch(address depositor, uint256 epochId) external view returns (uint256);

    /**
     * @notice Claim share of Temple Gold for epoch
     * Can only claim for past epochs, not current auction epoch.
     * @param epochId Id of epoch
     */
    function claim(uint256 epochId) external;
}

pragma solidity ^0.8.20;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interface/templegold/ITempleGold.sol)

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IOFT } from "@layerzerolabs/lz-evm-oapp-v2/contracts/oft/OFTCore.sol";
import { IOAppCore } from "@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/interfaces/IOAppCore.sol";
import { IOAppOptionsType3 } from "@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/interfaces/IOAppOptionsType3.sol";
import { ITempleGoldStaking } from "contracts/interfaces/templegold/ITempleGoldStaking.sol";
import { IStableGoldAuction } from "contracts/interfaces/templegold/IStableGoldAuction.sol";

interface ITempleGold is IOFT, IOAppCore, IOAppOptionsType3, IERC20 {
    struct DistributionParams {
        /// @notice staking contract
        uint256 staking;
        /// @notice STABLE_TGLD auction contract
        uint256 auction;
        /// @notice Team gnosis
        uint256 gnosis;
    }

    struct VestingFactor {
        uint128 value;
        uint128 weekMultiplier;
    }

    /// @notice To avoid stack too deep in constructor
    struct InitArgs {
        address executor; // executor is also used as delegate in LayerZero Endpoint
        address layerZeroEndpoint; // local endpoint address
        uint128 mintChainId;
        uint128 mintChainLzEid; // source arb one chain Eid for layerzero
        string name;
        string symbol;
    }

    event ContractAuthorizationSet(address indexed _contract, bool _whitelisted);
    event VestingFactorSet(uint128 numerator, uint128 denominator);
    event DistributionParamsSet(uint256 staking, uint256 auction, uint256 gnosis);
    event Distributed(uint256 stakingAmount, uint256 auctionAmount, uint256 gnosisAmount, uint256 timestamp);
    event StakingSet(address staking);
    event StableGoldAuctionSet(address auction);
    event TeamGnosisSet(address gnosis);
    event CirculatingSupplyUpdated(address indexed sender, uint256 amount, uint256 circulatingSuppply, uint256 totalBurned);
    
    error InvalidTotalShare();
    error MissingParameter();
    error NonTransferrable(address from, address to);
    error WrongChain();
    error CannotCompose();

    /// @notice These addresses are mutable to allow change/upgrade.
    /// @notice Staking contract
    function staking() external view returns (ITempleGoldStaking);

    /// @notice Dai Gold auction contract
    function auction() external view returns (IStableGoldAuction);

    /// @notice Multisig gnosis address
    function teamGnosis() external view returns (address);

    /// @notice Last block timestamp Temple Gold was minted
    function lastMintTimestamp() external view returns (uint32);

    /// @notice Whitelisted addresses for transferrability
    function authorized(address who) external view returns (bool);

    /**
     * @notice Set staking proxy contract address
     * @param _staking Staking proxy contract
     */
    function setStaking(address _staking) external;

    /**
     * @notice Set auctions dai gold auction contract address
     * @param _auction contract address
     */
    function setStableGoldAuction(address _auction) external;

    /**
     * @notice Set team gnosis address
     * @param _gnosis Team gnosis address
     */
    function setTeamGnosis(address _gnosis) external;

    /**
     * @notice Whitelist an address to allow transfer of Temple Gold to or from
     * @param _contract Contract address to whitelist
     * @param _whitelist Boolean whitelist state
     */
    function authorizeContract(address _contract, bool _whitelist) external;

    /**
     * @notice Set distribution percentages of newly minted Temple Gold
     * @param _params Distribution parameters
     */
    function setDistributionParams(DistributionParams calldata _params) external;

    /**
     * @notice Set vesting factor
     * @param _factor Vesting factor
     */
    function setVestingFactor(VestingFactor calldata _factor) external;

    /**
     * @notice Mint new tokens to be distributed. 
     * Enforces minimum mint amount and uses vestin factor to calculate mint token amount.
     * Minting is only possible on source chain Arbitrum
     */
    function mint() external;

    /**
     * @notice Get vesting factor
     * @return Vesting factor
     */
    function getVestingFactor() external view returns (VestingFactor memory);

    /**
     * @notice Get distribution parameters
     * @return Distribution parametersr
     */
    function getDistributionParameters() external view returns (DistributionParams memory);

    /**
     * @notice Get circulating supply across chains
     * @return Circulating supply
     */
    function circulatingSupply() external view returns (uint256);

    /**
     * @notice Check if TGOLD can be distributed
     * @return True if can distribtue
     */
    function canDistribute() external view returns (bool);

    /**
     * @notice Get amount of TGLD tokens that will mint if `mint()` called
     * @return Mint amount
     */
    function getMintAmount() external view returns (uint256);

    /**
     * @notice Burn and update circulating supply on source chain
     * @param amount Amount to burn
     */
    function burn(uint256 amount) external;

    /**
     * @notice Get total distributed Temple Gold. This value has no spice auction redemptions subtracted
     * @dev When this function is called on source chain (arbitrum), you get the actual total distributed
     * @return Total distributed
     */
    function totalDistributed() external view returns (uint256);

    /**
     * @notice Transfer ownership of TGLD to a new contract
     * @param _newOwner New owner
     */
    function transferOwnership(address _newOwner) external;
}

File 41 of 43 : ITempleGoldStaking.sol
pragma solidity ^0.8.20;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interfaces/templegold/ITempleGoldStaking.sol)

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface ITempleGoldStaking {
    event GoldDistributionNotified(uint256 amount, uint256 timestamp);
    event Staked(address indexed staker, uint256 amount);
    event MigratorSet(address migrator);
    event Withdrawn(address indexed staker, address to, uint256 amount);
    event RewardDistributionCoolDownSet(uint160 cooldown);
    event DistributionStarterSet(address indexed starter);
    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
    event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
    event RewardPaid(address indexed staker, address toAddress, uint256 reward);
    event RewardDurationSet(uint256 duration);
    event UnstakeCooldownSet(uint32 period);
    event DAOExecutorSet(address indexed daoExecutor);

    error CannotDistribute();
    error CannotDelegate();
    error InvalidOperation();
    error InvalidBlockNumber();
    error NoStaker();
    error UnstakeCooldown(uint256 timestampnow, uint256 unstakeTime);
    error CannotStake();

    /// @notice Reward parameters
    struct Reward {
        /// @notice The timestamp reward distribution finishes
        uint40 periodFinish;
        /// @notice The reward amount (1e18) per second during the reward period
        uint216 rewardRate;
        /// @notice The timestamp reward parameters were last updated
        uint40 lastUpdateTime;
        /// @notice The reward per token
        uint216 rewardPerTokenStored;
    }

    /// @notice A checkpoint for marking number of votes from a given block
    struct Checkpoint {
        uint256 fromBlock;
        uint256 votes;
    }

    /// @notice The staking token. Temple
    function stakingToken() external view returns (IERC20);
    /// @notice Reward token. Temple Gold
    function rewardToken() external view returns (IERC20);

    /// @notice Distribution starter
    function distributionStarter() external view returns (address);

    /// @notice Dao Executor
    function daoExecutor() external view returns (address);

    /// @notice Total supply of staking token
    function totalSupply() external view returns (uint256);

    /// @notice Store next reward amount for next epoch
    function nextRewardAmount() external view returns (uint256);
    /// @notice Cooldown time before next distribution of rewards
    /// @dev If set to zero, rewards distribution is callable any time 
    function rewardDistributionCoolDown() external view returns (uint160);
    /// @notice Timestamp for last reward notification
    function lastRewardNotificationTimestamp() external view returns (uint96);

    /// @notice For use when migrating to a new staking contract if TGLD changes.
    function migrator() external view returns (address);

    /// @notice Stakers claimable rewards at stake index
    function claimableRewards(address account) external view returns (uint256);
    /// @notice Staker reward per token paid at stake index
    function userRewardPerTokenPaid(address account) external view returns (uint256);

    /**
     * @notice Set migrator
     * @param _migrator Migrator
     */
    function setMigrator(address _migrator) external;

    /**
     * @notice Set DAO executor
     * @param _executor DAO executor
     */
    function setDaoExecutor(address _executor) external;

    /**
     * @notice Stake for an account when contract is not paused
     * @param amount Amount of staking token
     */
    function stake(uint256 amount) external;

    /**
     * @notice Withdraw staked tokens
     * @param amount Amount to withdraw
     * @param claimRewards Whether to claim rewards
     */
    function withdraw(uint256 amount, bool claimRewards) external;

    /// @notice Owner can pause user swaps from occuring
    function pause() external;

    /// @notice Owner can unpause so user swaps can occur
    function unpause() external;

    /**
     * @notice Get account staked balance
     * @param account Account
     * @return Staked balance of account
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @notice Get earned rewards of account
     * @param _account Account
     * @return Earned rewards of account
     */
    function earned(address _account) external view returns (uint256);

    /**
     * @notice Get Temple Gold reward per token of Temple 
     * @return Reward per token
     */
    function rewardPerToken() external view returns (uint256);

    /**
     * @notice Get finish timestamp of rewards
     * @return Finish timestamp
     */
    function rewardPeriodFinish() external view returns (uint40);

    /**
     * @notice Elevated access can recover tokens which are not staking or reward tokens
     * @param _token Token to recover
     * @param _to Recipient
     * @param _amount Amount of tokens
     */
    function recoverToken(address _token, address _to, uint256 _amount) external;

    /**  
     * @notice Get rewards
     * @param staker Staking account
     */
    function getReward(address staker) external;

    /**  
     * @notice Notify rewards distribution. Called by TempleGold contract after successful mint
     * @param amount Amount minted to this contract
     */
    function notifyDistribution(uint256 amount) external;

    /**
     * @notice Set reward distribution cooldown
     * @param _cooldown Cooldown in seconds
     */
    function setRewardDistributionCoolDown(uint160 _cooldown) external;

    /**
     * @notice Mint and distribute TGLD 
     */
    function distributeGold() external;

    /**  
     * @notice Get reward data
     * @return Reward data
     */
    function getRewardData() external view returns (Reward memory);

    /**
      * @notice For migrations to a new staking contract
      *         1. Withdraw `staker`s tokens to the new staking contract (the migrator)
      *         2. Any existing rewards are claimed and sent directly to the `staker`
      * @dev Called only from the new staking contract (the migrator).
      *      `setMigrator(new_staking_contract)` needs to be called first
      * @param staker The staker who is being migrated to a new staking contract.
      * @return Staker balance
      */
    function migrateWithdraw(address staker) external returns (uint256);

    /**
     * @notice Distributed TGLD rewards minted to this contract to stakers
     * @dev This starts another epoch of rewards distribution. Calculates new `rewardRate` from any left over rewards up until now
     */
    function distributeRewards() external;

    /**
     * @notice Get account checkpoint data 
     * @param account Account
     * @param epoch Epoch
     * @return Checkpoint data
     */
    function getCheckpoint(address account, uint256 epoch) external view returns (Checkpoint memory);

    /**
     * @notice Get account number of checkpoints
     * @param account Account
     * @return Number of checkpoints
     */
    function numCheckpoints(address account) external view returns (uint256);

     /**
     * @notice Get account unstake time
     * @param account Account
     * @return Unstake time
     */
    function getAccountUnstakeTime(address account) external view returns (uint256);

    /**
     * @notice Set reward duration
     * @param _duration Reward duration
     */
    function setRewardDuration(uint256 _duration) external;

    /**
     * @notice Delegate votes from `msg.sender` to `delegatee`
     * @param delegatee The address to delegate votes to
     */
    function delegate(address delegatee) external;

    /**   
     * @notice Gets the current votes balance for `account`
     * @param account The address to get votes balance
     * @return The number of current votes for `account`
     */
    function getCurrentVotes(address account) external view returns (uint256);

    /**
     * @notice Determine the prior number of votes for an account as of a block number
     * @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
     * @param account The address of the account to check
     * @param blockNumber The block number to get the vote balance at
     * @return The number of votes the account had as of the given block
     */
    function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256);
    /// @notice Time staker staked
    function stakeTimes(address account) external view returns (uint256);
    /// @notice Cooldown time before unstake
    function unstakeCooldown() external view returns (uint32);

    /**
     * @notice Set unstake cooldown
     * @param _period Cooldown period
     */
    function setUnstakeCooldown(uint32 _period) external;

    function rewardDuration() external view returns (uint256);
}

pragma solidity ^0.8.20;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (interfaces/v2/access/ITempleElevatedAccess.sol)

/**
 * @notice Inherit to add Executor and Rescuer roles for DAO elevated access.
 */ 
interface ITempleElevatedAccess {
    event ExplicitAccessSet(address indexed account, bytes4 indexed fnSelector, bool indexed value);
    event RescueModeSet(bool indexed value);

    event NewRescuerProposed(address indexed oldRescuer, address indexed oldProposedRescuer, address indexed newProposedRescuer);
    event NewRescuerAccepted(address indexed oldRescuer, address indexed newRescuer);

    event NewExecutorProposed(address indexed oldExecutor, address indexed oldProposedExecutor, address indexed newProposedExecutor);
    event NewExecutorAccepted(address indexed oldExecutor, address indexed newExecutor);

    struct ExplicitAccess {
        bytes4 fnSelector;
        bool allowed;
    }

    /**
     * @notice A set of addresses which are approved to execute emergency operations.
     */ 
    function rescuer() external returns (address);

    /**
     * @notice A set of addresses which are approved to execute normal operations on behalf of the DAO.
     */ 
    function executor() external returns (address);

    /**
     * @notice Explicit approval for an address to execute a function.
     * allowedCaller => function selector => true/false
     */
    function explicitFunctionAccess(address contractAddr, bytes4 functionSelector) external returns (bool);

    /**
     * @notice Under normal circumstances, rescuers don't have access to admin/operational functions.
     * However when rescue mode is enabled (by rescuers or executors), they claim the access rights.
     */
    function inRescueMode() external returns (bool);
    
    /**
     * @notice Set the contract into or out of rescue mode.
     * Only the rescuers or executors are allowed to set.
     */
    function setRescueMode(bool value) external;

    /**
     * @notice Proposes a new Rescuer.
     * Can only be called by the current rescuer.
     */
    function proposeNewRescuer(address account) external;

    /**
     * @notice Caller accepts the role as new Rescuer.
     * Can only be called by the proposed rescuer
     */
    function acceptRescuer() external;

    /**
     * @notice Proposes a new Executor.
     * Can only be called by the current executor or resucer (if in resuce mode)
     */
    function proposeNewExecutor(address account) external;

    /**
     * @notice Caller accepts the role as new Executor.
     * Can only be called by the proposed executor
     */
    function acceptExecutor() external;

    /**
     * @notice Grant `allowedCaller` the rights to call the function selectors in the access list.
     * @dev fnSelector == bytes4(keccak256("fn(argType1,argType2,...)"))
     */
    function setExplicitAccess(address allowedCaller, ExplicitAccess[] calldata access) external;
}

pragma solidity ^0.8.20;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Temple (v2/access/TempleElevatedAccess.sol)

import { ITempleElevatedAccess } from "contracts/interfaces/v2/access/ITempleElevatedAccess.sol";
import { CommonEventsAndErrors } from "contracts/common/CommonEventsAndErrors.sol";

/**
 * @notice Inherit to add Executor and Rescuer roles for DAO elevated access.
 */ 
abstract contract TempleElevatedAccess is ITempleElevatedAccess {
    /**
     * @notice The address which is approved to execute emergency operations.
     */ 
    address public override rescuer;

    /**
     * @notice The address which is approved to execute normal operations on behalf of the DAO.
     */ 
    address public override executor;

    /**
     * @notice Explicit approval for an address to execute a function.
     * allowedCaller => function selector => true/false
     */
    mapping(address => mapping(bytes4 => bool)) public override explicitFunctionAccess;

    /**
     * @notice Under normal circumstances, rescuers don't have access to admin/operational functions.
     * However when rescue mode is enabled (by rescuers or executors), they claim the access rights.
     */
    bool public override inRescueMode;

    /// @dev Track proposed rescuer/executor
    address private _proposedNewRescuer;
    address private _proposedNewExecutor;

    constructor(address initialRescuer, address initialExecutor) {
        if (initialRescuer == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        if (initialExecutor == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        if (initialExecutor == initialRescuer) revert CommonEventsAndErrors.InvalidAddress();

        rescuer = initialRescuer;
        executor = initialExecutor;
    }

    /**
     * @notice Set the contract into or out of rescue mode.
     * Only the rescuers are allowed to set.
     */
    function setRescueMode(bool value) external override {
        if (msg.sender != rescuer) revert CommonEventsAndErrors.InvalidAccess();
        emit RescueModeSet(value);
        inRescueMode = value;
    }

    /**
     * @notice Proposes a new Rescuer.
     * Can only be called by the current rescuer.
     */
    function proposeNewRescuer(address account) external override {
        if (msg.sender != rescuer) revert CommonEventsAndErrors.InvalidAccess();
        if (account == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        emit NewRescuerProposed(msg.sender, _proposedNewRescuer, account);
        _proposedNewRescuer = account;
    }

    /**
     * @notice Caller accepts the role as new Rescuer.
     * Can only be called by the proposed rescuer
     */
    function acceptRescuer() external override {
        if (msg.sender != _proposedNewRescuer) revert CommonEventsAndErrors.InvalidAccess();
        if (msg.sender == executor) revert CommonEventsAndErrors.InvalidAddress();

        emit NewRescuerAccepted(rescuer, msg.sender);
        rescuer = msg.sender;
        delete _proposedNewRescuer;
    }

    /**
     * @notice Proposes a new Executor.
     * Can only be called by the current executor or rescuer (if in resuce mode)
     */
    function proposeNewExecutor(address account) external override onlyElevatedAccess {
        if (account == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        emit NewExecutorProposed(executor, _proposedNewExecutor, account);
        _proposedNewExecutor = account;
    }

    /**
     * @notice Caller accepts the role as new Executor.
     * Can only be called by the proposed executor
     */
    function acceptExecutor() external override {
        if (msg.sender != _proposedNewExecutor) revert CommonEventsAndErrors.InvalidAccess();
        if (msg.sender == rescuer) revert CommonEventsAndErrors.InvalidAddress();

        emit NewExecutorAccepted(executor, msg.sender);
        executor = msg.sender;
        delete _proposedNewExecutor;
    }

    /**
     * @notice Grant `allowedCaller` the rights to call the function selectors in the access list.
     * @dev fnSelector == bytes4(keccak256("fn(argType1,argType2,...)"))
     */
    function setExplicitAccess(address allowedCaller, ExplicitAccess[] calldata access) external override onlyElevatedAccess {
        if (allowedCaller == address(0)) revert CommonEventsAndErrors.InvalidAddress();
        uint256 _length = access.length;
        ExplicitAccess memory _access;
        for (uint256 i; i < _length; ++i) {
            _access = access[i];
            emit ExplicitAccessSet(allowedCaller, _access.fnSelector, _access.allowed);
            explicitFunctionAccess[allowedCaller][_access.fnSelector] = _access.allowed;
        }
    }

    function isElevatedAccess(address caller, bytes4 fnSelector) internal view returns (bool) {
        if (inRescueMode) {
            // If we're in rescue mode, then only the rescuers can call
            return caller == rescuer;
        } else if (caller == executor || explicitFunctionAccess[caller][fnSelector]) {
            // If we're not in rescue mode, the executor can call all functions
            // or the caller has been given explicit access on this function
            return true;
        }
        return false;
    }

    /**
     * @notice Under normal operations, only the executors are allowed to call.
     * If 'rescue mode' has been enabled, then only the rescuers are allowed to call.
     * @dev Important: Only for use when called from an *external* contract. 
     * If a function with this modifier is called internally then the `msg.sig` 
     * will still refer to the top level externally called function.
     */
    modifier onlyElevatedAccess() {
        if (!isElevatedAccess(msg.sender, msg.sig)) revert CommonEventsAndErrors.InvalidAccess();
        _;
    }

    /**
     * @notice Only the executors or rescuers can call.
     */
    modifier onlyInRescueMode() {
        if (!(inRescueMode && msg.sender == rescuer)) revert CommonEventsAndErrors.InvalidAccess();
        _;
    }

    modifier notInRescueMode() {
        if (inRescueMode) revert CommonEventsAndErrors.InvalidAccess();
        _;
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 999999
  },
  "evmVersion": "paris",
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_rescuer","type":"address"},{"internalType":"address","name":"_executor","type":"address"},{"internalType":"address","name":"_stakingToken","type":"address"},{"internalType":"address","name":"_rewardToken","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"AddressInsufficientBalance","type":"error"},{"inputs":[],"name":"CannotDelegate","type":"error"},{"inputs":[],"name":"CannotDistribute","type":"error"},{"inputs":[],"name":"CannotStake","type":"error"},{"inputs":[],"name":"EnforcedPause","type":"error"},{"inputs":[],"name":"ExpectedNonZero","type":"error"},{"inputs":[],"name":"ExpectedPause","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"required","type":"uint256"},{"internalType":"uint256","name":"balance","type":"uint256"}],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InvalidAccess","type":"error"},{"inputs":[],"name":"InvalidAddress","type":"error"},{"inputs":[],"name":"InvalidBlockNumber","type":"error"},{"inputs":[],"name":"InvalidOperation","type":"error"},{"inputs":[],"name":"InvalidParam","type":"error"},{"inputs":[],"name":"NoStaker","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[{"internalType":"uint256","name":"timestampnow","type":"uint256"},{"internalType":"uint256","name":"unstakeTime","type":"uint256"}],"name":"UnstakeCooldown","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"daoExecutor","type":"address"}],"name":"DAOExecutorSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"delegator","type":"address"},{"indexed":true,"internalType":"address","name":"fromDelegate","type":"address"},{"indexed":true,"internalType":"address","name":"toDelegate","type":"address"}],"name":"DelegateChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"delegate","type":"address"},{"indexed":false,"internalType":"uint256","name":"previousBalance","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newBalance","type":"uint256"}],"name":"DelegateVotesChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"starter","type":"address"}],"name":"DistributionStarterSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"bytes4","name":"fnSelector","type":"bytes4"},{"indexed":true,"internalType":"bool","name":"value","type":"bool"}],"name":"ExplicitAccessSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"GoldDistributionNotified","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"migrator","type":"address"}],"name":"MigratorSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldExecutor","type":"address"},{"indexed":true,"internalType":"address","name":"newExecutor","type":"address"}],"name":"NewExecutorAccepted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldExecutor","type":"address"},{"indexed":true,"internalType":"address","name":"oldProposedExecutor","type":"address"},{"indexed":true,"internalType":"address","name":"newProposedExecutor","type":"address"}],"name":"NewExecutorProposed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldRescuer","type":"address"},{"indexed":true,"internalType":"address","name":"newRescuer","type":"address"}],"name":"NewRescuerAccepted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldRescuer","type":"address"},{"indexed":true,"internalType":"address","name":"oldProposedRescuer","type":"address"},{"indexed":true,"internalType":"address","name":"newProposedRescuer","type":"address"}],"name":"NewRescuerProposed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bool","name":"value","type":"bool"}],"name":"RescueModeSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint160","name":"cooldown","type":"uint160"}],"name":"RewardDistributionCoolDownSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"duration","type":"uint256"}],"name":"RewardDurationSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"staker","type":"address"},{"indexed":false,"internalType":"address","name":"toAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"staker","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"TokenRecovered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"period","type":"uint32"}],"name":"UnstakeCooldownSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"staker","type":"address"},{"indexed":false,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[],"name":"MAXIMUM_UNSTAKE_COOLDOWN","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WEEK_LENGTH","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"acceptExecutor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"acceptRescuer","outputs":[],"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"}],"name":"claimableRewards","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"daoExecutor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"delegatee","type":"address"}],"name":"delegate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"delegates","outputs":[{"internalType":"address","name":"delegate","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"distributeGold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"distributeRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"distributionStarter","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"earned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"executor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"bytes4","name":"","type":"bytes4"}],"name":"explicitFunctionAccess","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountUnstakeTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"epoch","type":"uint256"}],"name":"getCheckpoint","outputs":[{"components":[{"internalType":"uint256","name":"fromBlock","type":"uint256"},{"internalType":"uint256","name":"votes","type":"uint256"}],"internalType":"struct ITempleGoldStaking.Checkpoint","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getCurrentVotes","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"blockNumber","type":"uint256"}],"name":"getPriorVotes","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"staker","type":"address"}],"name":"getReward","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getRewardData","outputs":[{"components":[{"internalType":"uint40","name":"periodFinish","type":"uint40"},{"internalType":"uint216","name":"rewardRate","type":"uint216"},{"internalType":"uint40","name":"lastUpdateTime","type":"uint40"},{"internalType":"uint216","name":"rewardPerTokenStored","type":"uint216"}],"internalType":"struct ITempleGoldStaking.Reward","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"inRescueMode","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastRewardNotificationTimestamp","outputs":[{"internalType":"uint96","name":"","type":"uint96"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"staker","type":"address"}],"name":"migrateWithdraw","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"migrator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextRewardAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"notifyDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"numCheckpoints","outputs":[{"internalType":"uint256","name":"number","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":"account","type":"address"}],"name":"proposeNewExecutor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"proposeNewRescuer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"recoverToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rescuer","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardDistributionCoolDown","outputs":[{"internalType":"uint160","name":"","type":"uint160"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPeriodFinish","outputs":[{"internalType":"uint40","name":"","type":"uint40"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardToken","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_executor","type":"address"}],"name":"setDaoExecutor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_starter","type":"address"}],"name":"setDistributionStarter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"allowedCaller","type":"address"},{"components":[{"internalType":"bytes4","name":"fnSelector","type":"bytes4"},{"internalType":"bool","name":"allowed","type":"bool"}],"internalType":"struct ITempleElevatedAccess.ExplicitAccess[]","name":"access","type":"tuple[]"}],"name":"setExplicitAccess","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_migrator","type":"address"}],"name":"setMigrator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"value","type":"bool"}],"name":"setRescueMode","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint160","name":"_cooldown","type":"uint160"}],"name":"setRewardDistributionCoolDown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_duration","type":"uint256"}],"name":"setRewardDuration","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"_period","type":"uint32"}],"name":"setUnstakeCooldown","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"stake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"stakeTimes","outputs":[{"internalType":"uint256","name":"stakeTime","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"stakingToken","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unstakeCooldown","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"userRewardPerTokenPaid","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bool","name":"claimRewards","type":"bool"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60c060405234801561001057600080fd5b50604051613ee9380380613ee983398101604081905261002f9161011b565b83836001600160a01b0382166100585760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b03811661007f5760405163e6c4247b60e01b815260040160405180910390fd5b816001600160a01b0316816001600160a01b0316036100b15760405163e6c4247b60e01b815260040160405180910390fd5b600080546001600160a01b03199081166001600160a01b0394851617909155600180549091169183169190911790556004805460ff60a01b191690559182166080521660a0525061016f9050565b80516001600160a01b038116811461011657600080fd5b919050565b6000806000806080858703121561013157600080fd5b61013a856100ff565b9350610148602086016100ff565b9250610156604086016100ff565b9150610164606086016100ff565b905092959194509250565b60805160a051613d1d6101cc6000396000818161099c015281816112c701528181611d6f01528181612c7401526130ec01526000818161071e01528181611d1a015281816129df01528181612aa80152612fae0152613d1d6000f3fe608060405234801561001057600080fd5b506004361061036c5760003560e01c8063763c4036116101d3578063bfccf0ec11610104578063da4e88f2116100a2578063e9a776991161007c578063e9a776991461096e578063f520e7e51461098e578063f7c618c114610997578063fc83c95b146109be57600080fd5b8063da4e88f214610900578063daeccc7914610920578063dc01f60d1461094e57600080fd5b8063c34c08e5116100de578063c34c08e5146108bd578063ccb51004146108dd578063cd3daf9d146108e5578063d9a349c1146108ed57600080fd5b8063bfccf0ec14610884578063c00007b014610897578063c0ed00c9146108aa57600080fd5b80638963888c11610171578063a3f9f7d01161014b578063a3f9f7d014610838578063a694fc3a1461084b578063a7229fd91461085e578063b4b5ea571461087157600080fd5b80638963888c146107b85780638b876347146108055780639c0421991461082557600080fd5b80637cd07e47116101ad5780637cd07e47146107705780637eefd5ae146107985780638112c4af146107a85780638456cb59146107b057600080fd5b8063763c403614610740578063782d6fe11461075357806379dac2a01461076657600080fd5b806338d07436116102ad5780635c975abb1161024b5780636f4a2cd0116102255780636f4a2cd0146106bb5780636fcfff45146106c357806370a08231146106e357806372f702f31461071957600080fd5b80635c975abb1461057e578063654f2fc8146105a1578063668845d8146105b457600080fd5b806347f761f51161028757806347f761f5146104f45780634c92c5cd14610522578063587cde1e146105355780635c19a95c1461056b57600080fd5b806338d07436146104b95780633f4ba83a146104cc578063406194c5146104d457600080fd5b806318160ddd1161031a57806323cf3118116102f457806323cf31181461043f578063279084a61461045257806337a583581461046b57806338a631831461047457600080fd5b806318160ddd1461040e5780631ad25ffb146104175780631f2114051461043757600080fd5b8063135918081161034b57806313591808146103bf57806315ead477146103de5780631810fe7f146103f157600080fd5b80628cc26214610371578063032ef9011461039757806307f184f1146103ac575b600080fd5b61038461037f366004613900565b6109d1565b6040519081526020015b60405180910390f35b6103aa6103a536600461392b565b6109ef565b005b6103aa6103ba366004613900565b610a9e565b6103c962278d0081565b60405163ffffffff909116815260200161038e565b6103aa6103ec366004613900565b610bd6565b6003546103fe9060ff1681565b604051901515815260200161038e565b61038460075481565b610384610425366004613900565b60146020526000908152604090205481565b6103aa610cf6565b6103aa61044d366004613900565b610e15565b600c5460405164ffffffffff909116815260200161038e565b61038460085481565b6000546104949073ffffffffffffffffffffffffffffffffffffffff1681565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200161038e565b6103aa6104c7366004613948565b610fbd565b6103aa611048565b6006546104949073ffffffffffffffffffffffffffffffffffffffff1681565b610507610502366004613978565b6110b6565b6040805182518152602092830151928101929092520161038e565b6103aa610530366004613900565b61110f565b610494610543366004613900565b600f6020526000908152604090205473ffffffffffffffffffffffffffffffffffffffff1681565b6103aa610579366004613900565b6112a2565b60045474010000000000000000000000000000000000000000900460ff166103fe565b6103aa6105af3660046139a4565b6112af565b61063b6040805160808101825260008082526020820181905291810182905260608101919091525060408051608081018252600c5464ffffffffff80821683527affffffffffffffffffffffffffffffffffffffffffffffffffffff650100000000009283900481166020850152600d549182169484019490945204909116606082015290565b60405161038e9190600060808201905064ffffffffff83511682527affffffffffffffffffffffffffffffffffffffffffffffffffffff602084015116602083015264ffffffffff60408401511660408301527affffffffffffffffffffffffffffffffffffffffffffffffffffff606084015116606083015292915050565b6103aa6113a3565b6103846106d1366004613900565b60136020526000908152604090205481565b6103846106f1366004613900565b73ffffffffffffffffffffffffffffffffffffffff166000908152600e602052604090205490565b6104947f000000000000000000000000000000000000000000000000000000000000000081565b61038461074e366004613900565b611649565b610384610761366004613978565b6116ba565b61038462093a8081565b600b5461049490640100000000900473ffffffffffffffffffffffffffffffffffffffff1681565b600b546103c99063ffffffff1681565b6103aa611907565b6103aa611a47565b600a546107e8907401000000000000000000000000000000000000000090046bffffffffffffffffffffffff1681565b6040516bffffffffffffffffffffffff909116815260200161038e565b610384610813366004613900565b60116020526000908152604090205481565b610384610833366004613900565b611ab3565b6103aa6108463660046139bd565b611b98565b6103aa6108593660046139a4565b611ca2565b6103aa61086c3660046139e3565b611cb4565b61038461087f366004613900565b611e81565b6103aa610892366004613a24565b611efd565b6103aa6108a5366004613900565b6120fc565b6103aa6108b83660046139a4565b61222c565b6001546104949073ffffffffffffffffffffffffffffffffffffffff1681565b6103aa612346565b610384612356565b6103aa6108fb366004613900565b612365565b600a546104949073ffffffffffffffffffffffffffffffffffffffff1681565b6103fe61092e366004613ade565b600260209081526000928352604080842090915290825290205460ff1681565b61038461095c366004613900565b60106020526000908152604090205481565b6005546104949073ffffffffffffffffffffffffffffffffffffffff1681565b61038460095481565b6104947f000000000000000000000000000000000000000000000000000000000000000081565b6103aa6109cc366004613900565b6124aa565b6000806109dc612581565b90506109e8838261267b565b9392505050565b60005473ffffffffffffffffffffffffffffffffffffffff163314610a40576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b604051811515907f18f4a9a726c72020fd959c636d2fd464c6cefe90afeaea3c830b971614cf70b690600090a2600380547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016911515919091179055565b60005473ffffffffffffffffffffffffffffffffffffffff163314610aef576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8116610b3c576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60035460405173ffffffffffffffffffffffffffffffffffffffff808416926101009004169033907f374d23b359cab0f8963c5c1715a6de7974f53af00aecc27de50d93906b70943e90600090a46003805473ffffffffffffffffffffffffffffffffffffffff909216610100027fffffffffffffffffffffff0000000000000000000000000000000000000000ff909216919091179055565b610c04336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b610c3a576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8116610c87576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600580547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff83169081179091556040517f7cbcf2db31edf0f80b106b728f3e8f75d23576649e580cde45821df75db331e990600090a250565b60045473ffffffffffffffffffffffffffffffffffffffff163314610d47576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60005473ffffffffffffffffffffffffffffffffffffffff163303610d98576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600154604051339173ffffffffffffffffffffffffffffffffffffffff16907fe963dc9c0d2165b080440a5d2665566142f2426b1ea15f3da8390b0fd336b06490600090a3600180547fffffffffffffffffffffffff00000000000000000000000000000000000000009081163317909155600480549091169055565b60065473ffffffffffffffffffffffffffffffffffffffff16610e9b57610e60336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b610e96576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b610eec565b60065473ffffffffffffffffffffffffffffffffffffffff163314610eec576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8116610f39576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600b80547fffffffffffffffff0000000000000000000000000000000000000000ffffffff1664010000000073ffffffffffffffffffffffffffffffffffffffff8416908102919091179091556040519081527f3ba4758949febc607e14523620298f8b5995b1848492ad7aa083372ac886ae07906020015b60405180910390a150565b610fc56127c7565b600b54336000908152601460205260408120549091610fec9163ffffffff90911690613b42565b905042811115611036576040517f497e9598000000000000000000000000000000000000000000000000000000008152426004820152602481018290526044015b60405180910390fd5b611043333385853361281c565b505050565b611076336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b6110ac576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6110b4612b3b565b565b6040805180820182526000808252602091820181905273ffffffffffffffffffffffffffffffffffffffff8516815260128252828120848252825282902082518084019093528054835260010154908201525b92915050565b60065473ffffffffffffffffffffffffffffffffffffffff166111955761115a336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b611190576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6111e6565b60065473ffffffffffffffffffffffffffffffffffffffff1633146111e6576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8116611233576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600680547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff83169081179091556040517f16d61a8ae20f45aed7c5f705859e84b0292aabf52ce61496c63db9ab14c228b490600090a250565b6112ac3382612bb8565b50565b3373ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000000000000000000000000000000000000000000001614801590611320575061131e336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b155b15611357576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b80600860008282546113699190613b42565b9091555050604080518281524260208201527f1e215fdd40f0b4854c5a2b2cfe53859ca232f085a5b129c9f65b6bfeb094c5e49101610fb2565b6113ab6127c7565b6000806113b6612581565b600d80547affffffffffffffffffffffffffffffffffffffffffffffffffffff8316650100000000000264ffffffffff91821617909155600c549192506113fd9116612c5d565b600d80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000001664ffffffffff9290921691909117905573ffffffffffffffffffffffffffffffffffffffff8216156114c85761147682827affffffffffffffffffffffffffffffffffffffffffffffffffffff1661267b565b73ffffffffffffffffffffffffffffffffffffffff831660009081526010602090815260408083209390935560119052207affffffffffffffffffffffffffffffffffffffffffffffffffffff821690555b5060055473ffffffffffffffffffffffffffffffffffffffff16331461151a576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600754600003611556576040517f1090380d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600a5442906115a29073ffffffffffffffffffffffffffffffffffffffff8116907401000000000000000000000000000000000000000090046bffffffffffffffffffffffff16613b55565b73ffffffffffffffffffffffffffffffffffffffff1611156115f0576040517f51e624a700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6115f8612c72565b600854600954811015611637576040517f54db0c8c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600060085561164581612cee565b5050565b73ffffffffffffffffffffffffffffffffffffffff8116600090815260146020526040812054156116b257600b5473ffffffffffffffffffffffffffffffffffffffff83166000908152601460205260409020546116ad9163ffffffff1690613b42565b611109565b600092915050565b60004382106116f5576040517f4e47846c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff83166000908152601360205260408120549081900361172d576000915050611109565b73ffffffffffffffffffffffffffffffffffffffff84166000908152601260205260408120849161175f600185613b81565b815260200190815260200160002060000154116117c15773ffffffffffffffffffffffffffffffffffffffff84166000908152601260205260408120906117a7600184613b81565b815260200190815260200160002060010154915050611109565b73ffffffffffffffffffffffffffffffffffffffff84166000908152601260209081526040808320838052909152902054831015611803576000915050611109565b600080611811600184613b81565b90505b818111156118ca576000600261182a8484613b81565b6118349190613b94565b61183e9083613b81565b73ffffffffffffffffffffffffffffffffffffffff881660009081526012602090815260408083208484528252918290208251808401909352805480845260019091015491830191909152919250908790036118a4576020015194506111099350505050565b80518711156118b5578193506118c3565b6118c0600183613b81565b92505b5050611814565b5073ffffffffffffffffffffffffffffffffffffffff85166000908152601260209081526040808320938352929052206001015491505092915050565b600354610100900473ffffffffffffffffffffffffffffffffffffffff16331461195d576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60015473ffffffffffffffffffffffffffffffffffffffff1633036119ae576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60008054604051339273ffffffffffffffffffffffffffffffffffffffff909216917ff07131157ebea15896dc89264eb9a7572e67cc9fad6b855015730fcec10704e091a3600080547fffffffffffffffffffffffff00000000000000000000000000000000000000001633179055600380547fffffffffffffffffffffff0000000000000000000000000000000000000000ff169055565b611a75336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b611aab576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6110b4612eeb565b600b54600090640100000000900473ffffffffffffffffffffffffffffffffffffffff163314611b0f576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8216611b5c576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff82166000908152600e6020526040902054611b9083338360018361281c565b90505b919050565b611bc6336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b611bfc576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b62278d0063ffffffff82161115611c3f576040517fd252903400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600b80547fffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000001663ffffffff83169081179091556040519081527f885b3532bfa278e4874fcd9bcd74c49a1682c9ff7eaa6b301cea6a7969e5813190602001610fb2565b611caa6127c7565b6112ac3382612f5a565b611ce2336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b611d18576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161480611dbd57507f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16145b15611df4576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611e1573ffffffffffffffffffffffffffffffffffffffff84168383613012565b8273ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff167f879f92dded0f26b83c3e00b12e0395dc72cfc3077343d1854ed6988edd1f909683604051611e7491815260200190565b60405180910390a3505050565b73ffffffffffffffffffffffffffffffffffffffff811660009081526013602052604081205480611eb35760006109e8565b73ffffffffffffffffffffffffffffffffffffffff8316600090815260126020526040812090611ee4600184613b81565b8152602001908152602001600020600101549392505050565b611f2b336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b611f61576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8316611fae576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040805180820190915260008082526020820152819060005b828110156120f457848482818110611fe157611fe1613bcf565b905060400201803603810190611ff79190613bfe565b91508160200151151582600001517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19168773ffffffffffffffffffffffffffffffffffffffff167ff5736e75de2c751f775d4c5ed517289f77074f8c337f451ba4c0c3ed1dd7f9ad60405160405180910390a460208281015173ffffffffffffffffffffffffffffffffffffffff8816600090815260028352604080822086517fffffffff000000000000000000000000000000000000000000000000000000001683529093529190912080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016911515919091179055600101611fc7565b505050505050565b6121046127c7565b80600061210f612581565b600d80547affffffffffffffffffffffffffffffffffffffffffffffffffffff8316650100000000000264ffffffffff91821617909155600c549192506121569116612c5d565b600d80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000001664ffffffffff9290921691909117905573ffffffffffffffffffffffffffffffffffffffff821615612221576121cf82827affffffffffffffffffffffffffffffffffffffffffffffffffffff1661267b565b73ffffffffffffffffffffffffffffffffffffffff831660009081526010602090815260408083209390935560119052207affffffffffffffffffffffffffffffffffffffffffffffffffffff821690555b506116458283613093565b61225a336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b612290576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b62093a808110156122cd576040517fd252903400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600c544264ffffffffff90911610612311576040517f398d4d3200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60098190556040518181527f823b3cede11929e1b876086e20886121c9c32f04426a36ed323a85d541df3b8e90602001610fb2565b61234e6127c7565b6110b4612c72565b6000612360612581565b905090565b612393336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b6123c9576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8116612416576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60045460015460405173ffffffffffffffffffffffffffffffffffffffff8085169381169216907f4857570a90fe0a0fc580e89a287e77576141ac8e2e8b3710cd26db44f44156c190600090a4600480547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff92909216919091179055565b6124d8336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b61250e576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600a80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff83169081179091556040519081527ffac87d3c8a428a7011075404cc37f2669246fcd04ff5c3098e32d122de1d9c6890602001610fb2565b6000600754600014806125a25750600c54600d5464ffffffffff9081169116145b156125d45750600d546501000000000090047affffffffffffffffffffffffffffffffffffffffffffffffffffff1690565b600754600c54600d547affffffffffffffffffffffffffffffffffffffffffffffffffffff650100000000008304169164ffffffffff918216916126189116612c5d565b6126229190613b81565b61262c9190613c84565b61263e90670de0b6b3a7640000613c84565b6126489190613b94565b600d5461236091906501000000000090047affffffffffffffffffffffffffffffffffffffffffffffffffffff16613b42565b73ffffffffffffffffffffffffffffffffffffffff82166000908152601060209081526040808320546011909252822054670de0b6b3a7640000906126c09085613b81565b73ffffffffffffffffffffffffffffffffffffffff86166000908152600e60205260409020546126f09190613c84565b6126fa9190613b94565b6109e89190613b42565b60035460009060ff1615612736575060005473ffffffffffffffffffffffffffffffffffffffff838116911614611109565b60015473ffffffffffffffffffffffffffffffffffffffff848116911614806127b1575073ffffffffffffffffffffffffffffffffffffffff831660009081526002602090815260408083207fffffffff000000000000000000000000000000000000000000000000000000008616845290915290205460ff165b156127be57506001611109565b50600092915050565b60045474010000000000000000000000000000000000000000900460ff16156110b4576040517fd93c066500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b846000612827612581565b600d80547affffffffffffffffffffffffffffffffffffffffffffffffffffff8316650100000000000264ffffffffff91821617909155600c5491925061286e9116612c5d565b600d80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000001664ffffffffff9290921691909117905573ffffffffffffffffffffffffffffffffffffffff821615612939576128e782827affffffffffffffffffffffffffffffffffffffffffffffffffffff1661267b565b73ffffffffffffffffffffffffffffffffffffffff831660009081526010602090815260408083209390935560119052207affffffffffffffffffffffffffffffffffffffffffffffffffffff821690555b5083600003612974576040517f54db0c8c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff86166000908152600e602052604090205480851115612a1a576040517fdb42144d00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000166004820152602481018690526044810182905260640161102d565b73ffffffffffffffffffffffffffffffffffffffff87166000908152600e60205260408120868303905560078054879290612a56908490613b81565b909155505073ffffffffffffffffffffffffffffffffffffffff8088166000908152600f6020526040812054612a8e9216908761316c565b612acf73ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168787613012565b6040805173ffffffffffffffffffffffffffffffffffffffff8881168252602082018890528916917fd1c19fbcd4551a5edfb66d43d2e337c04837afda3482b42bdf569a8fccdae5fb910160405180910390a28315612b3257612b328784613093565b50505050505050565b612b4361330f565b600480547fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff1690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390a1565b73ffffffffffffffffffffffffffffffffffffffff8083166000818152600f602081815260408084208054600e845282862054949093528787167fffffffffffffffffffffffff00000000000000000000000000000000000000008416811790915590519190951694919391928592917f3134e8a2e6d97e929a7e54011ea5485d7d196dd5f0ba4d4ef95803e8e3fc257f9190a4612c5782848361316c565b50505050565b600042821015612c6b575090565b5042919050565b7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16631249c58b6040518163ffffffff1660e01b8152600401600060405180830381600087803b158015612cda57600080fd5b505af1158015612c57573d6000803e3d6000fd5b600954600c5464ffffffffff164210612d6857612d0b8183613b94565b600c805464ffffffffff16650100000000007affffffffffffffffffffffffffffffffffffffffffffffffffffff93841681029190911791829055612d569284929190910416613c84565b612d609083613b81565b600855612e35565b600c54600090612d8090429064ffffffffff16613b81565b600c54909150600090612db9906501000000000090047affffffffffffffffffffffffffffffffffffffffffffffffffffff1683613c84565b905082612dc68286613b42565b612dd09190613b94565b600c805464ffffffffff16650100000000007affffffffffffffffffffffffffffffffffffffffffffffffffffff93841681029190911791829055612e1b9286929190910416613c84565b612e258286613b42565b612e2f9190613b81565b60085550505b600d80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000164264ffffffffff811691909117909155612e76908290613b42565b600c80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000001664ffffffffff929092169190911790555050600a805473ffffffffffffffffffffffffffffffffffffffff164263ffffffff167401000000000000000000000000000000000000000002179055565b612ef36127c7565b600480547fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff16740100000000000000000000000000000000000000001790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258612b8e3390565b80600003612f94576040517f54db0c8c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b612fd673ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000000000000000000000000000000000000000000016333084613363565b612fe082826133a9565b73ffffffffffffffffffffffffffffffffffffffff8083166000908152600f602052604081205461164592168361316c565b60405173ffffffffffffffffffffffffffffffffffffffff83811660248301526044820183905261104391859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050613572565b73ffffffffffffffffffffffffffffffffffffffff821660009081526010602052604090205480156110435773ffffffffffffffffffffffffffffffffffffffff808416600090815260106020526040812055613113907f0000000000000000000000000000000000000000000000000000000000000000168383613012565b6040805173ffffffffffffffffffffffffffffffffffffffff8481168252602082018490528516917f540798df468d7b23d11f156fdb954cb19ad414d150722a7b6d55ba369dea792e91015b60405180910390a2505050565b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16141580156131a85750600081115b156110435773ffffffffffffffffffffffffffffffffffffffff8316156132605773ffffffffffffffffffffffffffffffffffffffff831660009081526013602052604081205490816131fc576000613240565b73ffffffffffffffffffffffffffffffffffffffff851660009081526012602052604081209061322d600185613b81565b8152602001908152602001600020600101545b9050600061324e8483613b81565b905061325c86848484613608565b5050505b73ffffffffffffffffffffffffffffffffffffffff8216156110435773ffffffffffffffffffffffffffffffffffffffff821660009081526013602052604081205490816132af5760006132f3565b73ffffffffffffffffffffffffffffffffffffffff84166000908152601260205260408120906132e0600185613b81565b8152602001908152602001600020600101545b905060006133018483613b42565b90506120f485848484613608565b60045474010000000000000000000000000000000000000000900460ff166110b4576040517f8dfc202b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60405173ffffffffffffffffffffffffffffffffffffffff8481166024830152838116604483015260648201839052612c579186918216906323b872dd9060840161304c565b8160006133b4612581565b600d80547affffffffffffffffffffffffffffffffffffffffffffffffffffff8316650100000000000264ffffffffff91821617909155600c549192506133fb9116612c5d565b600d80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000001664ffffffffff9290921691909117905573ffffffffffffffffffffffffffffffffffffffff8216156134c65761347482827affffffffffffffffffffffffffffffffffffffffffffffffffffff1661267b565b73ffffffffffffffffffffffffffffffffffffffff831660009081526010602090815260408083209390935560119052207affffffffffffffffffffffffffffffffffffffffffffffffffffff821690555b5081600760008282546134d99190613b42565b909155505073ffffffffffffffffffffffffffffffffffffffff83166000908152600e602052604081208054849290613513908490613b42565b909155505073ffffffffffffffffffffffffffffffffffffffff831660008181526014602052604090819020429055517f9e71bc8eea02a63969f509818f2dafb9254532904319f9dbda79b67bd34a5f3d9061315f9085815260200190565b600061359473ffffffffffffffffffffffffffffffffffffffff84168361377e565b905080516000141580156135b95750808060200190518101906135b79190613c9b565b155b15611043576040517f5274afe700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8416600482015260240161102d565b600083118015613659575073ffffffffffffffffffffffffffffffffffffffff841660009081526012602052604081204391613645600187613b81565b815260200190815260200160002060000154145b156136a95773ffffffffffffffffffffffffffffffffffffffff841660009081526012602052604081208291613690600187613b81565b8152602081019190915260400160002060010155613727565b604080518082018252438152602080820184815273ffffffffffffffffffffffffffffffffffffffff8816600090815260128352848120888252909252929020905181559051600191820155613700908490613b42565b73ffffffffffffffffffffffffffffffffffffffff85166000908152601360205260409020555b604080518381526020810183905273ffffffffffffffffffffffffffffffffffffffff8616917fdec2bacdd2f05b59de34da9b523dff8be42e5e38e818c82fdb0bae774387a724910160405180910390a250505050565b60606109e883836000846000808573ffffffffffffffffffffffffffffffffffffffff1684866040516137b19190613cb8565b60006040518083038185875af1925050503d80600081146137ee576040519150601f19603f3d011682016040523d82523d6000602084013e6137f3565b606091505b509150915061380386838361380d565b9695505050505050565b6060826138225761381d8261389c565b6109e8565b8151158015613846575073ffffffffffffffffffffffffffffffffffffffff84163b155b15613895576040517f9996b31500000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8516600482015260240161102d565b50806109e8565b8051156138ac5780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff811681146112ac57600080fd5b60006020828403121561391257600080fd5b81356109e8816138de565b80151581146112ac57600080fd5b60006020828403121561393d57600080fd5b81356109e88161391d565b6000806040838503121561395b57600080fd5b82359150602083013561396d8161391d565b809150509250929050565b6000806040838503121561398b57600080fd5b8235613996816138de565b946020939093013593505050565b6000602082840312156139b657600080fd5b5035919050565b6000602082840312156139cf57600080fd5b813563ffffffff811681146109e857600080fd5b6000806000606084860312156139f857600080fd5b8335613a03816138de565b92506020840135613a13816138de565b929592945050506040919091013590565b600080600060408486031215613a3957600080fd5b8335613a44816138de565b9250602084013567ffffffffffffffff811115613a6057600080fd5b8401601f81018613613a7157600080fd5b803567ffffffffffffffff811115613a8857600080fd5b8660208260061b8401011115613a9d57600080fd5b939660209190910195509293505050565b80357fffffffff0000000000000000000000000000000000000000000000000000000081168114611b9357600080fd5b60008060408385031215613af157600080fd5b8235613afc816138de565b9150613b0a60208401613aae565b90509250929050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b8082018082111561110957611109613b13565b73ffffffffffffffffffffffffffffffffffffffff818116838216019081111561110957611109613b13565b8181038181111561110957611109613b13565b600082613bca577f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b500490565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b60006040828403128015613c1157600080fd5b506040805190810167ffffffffffffffff81118282101715613c5c577f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b604052613c6883613aae565b81526020830135613c788161391d565b60208201529392505050565b808202811582820484141761110957611109613b13565b600060208284031215613cad57600080fd5b81516109e88161391d565b6000825160005b81811015613cd95760208186018101518583015201613cbf565b50600092019182525091905056fea264697066735822122025f39ebbee88267208f433ccdfa8f1b30614e16ef2785ac5b001649b6cad6f1764736f6c634300081c00330000000000000000000000009f90430179d9b67341bfa50559bc7b8e35629f1b00000000000000000000000094b62a27a2f23cbdc0220826a8452fb5055cf273000000000000000000000000470ebf5f030ed85fc1ed4c2d36b9dd02e77cf1b70000000000000000000000000e7b53dde30754a94d4b10c9cdcaca1c749ecd1b

Deployed Bytecode

0x608060405234801561001057600080fd5b506004361061036c5760003560e01c8063763c4036116101d3578063bfccf0ec11610104578063da4e88f2116100a2578063e9a776991161007c578063e9a776991461096e578063f520e7e51461098e578063f7c618c114610997578063fc83c95b146109be57600080fd5b8063da4e88f214610900578063daeccc7914610920578063dc01f60d1461094e57600080fd5b8063c34c08e5116100de578063c34c08e5146108bd578063ccb51004146108dd578063cd3daf9d146108e5578063d9a349c1146108ed57600080fd5b8063bfccf0ec14610884578063c00007b014610897578063c0ed00c9146108aa57600080fd5b80638963888c11610171578063a3f9f7d01161014b578063a3f9f7d014610838578063a694fc3a1461084b578063a7229fd91461085e578063b4b5ea571461087157600080fd5b80638963888c146107b85780638b876347146108055780639c0421991461082557600080fd5b80637cd07e47116101ad5780637cd07e47146107705780637eefd5ae146107985780638112c4af146107a85780638456cb59146107b057600080fd5b8063763c403614610740578063782d6fe11461075357806379dac2a01461076657600080fd5b806338d07436116102ad5780635c975abb1161024b5780636f4a2cd0116102255780636f4a2cd0146106bb5780636fcfff45146106c357806370a08231146106e357806372f702f31461071957600080fd5b80635c975abb1461057e578063654f2fc8146105a1578063668845d8146105b457600080fd5b806347f761f51161028757806347f761f5146104f45780634c92c5cd14610522578063587cde1e146105355780635c19a95c1461056b57600080fd5b806338d07436146104b95780633f4ba83a146104cc578063406194c5146104d457600080fd5b806318160ddd1161031a57806323cf3118116102f457806323cf31181461043f578063279084a61461045257806337a583581461046b57806338a631831461047457600080fd5b806318160ddd1461040e5780631ad25ffb146104175780631f2114051461043757600080fd5b8063135918081161034b57806313591808146103bf57806315ead477146103de5780631810fe7f146103f157600080fd5b80628cc26214610371578063032ef9011461039757806307f184f1146103ac575b600080fd5b61038461037f366004613900565b6109d1565b6040519081526020015b60405180910390f35b6103aa6103a536600461392b565b6109ef565b005b6103aa6103ba366004613900565b610a9e565b6103c962278d0081565b60405163ffffffff909116815260200161038e565b6103aa6103ec366004613900565b610bd6565b6003546103fe9060ff1681565b604051901515815260200161038e565b61038460075481565b610384610425366004613900565b60146020526000908152604090205481565b6103aa610cf6565b6103aa61044d366004613900565b610e15565b600c5460405164ffffffffff909116815260200161038e565b61038460085481565b6000546104949073ffffffffffffffffffffffffffffffffffffffff1681565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200161038e565b6103aa6104c7366004613948565b610fbd565b6103aa611048565b6006546104949073ffffffffffffffffffffffffffffffffffffffff1681565b610507610502366004613978565b6110b6565b6040805182518152602092830151928101929092520161038e565b6103aa610530366004613900565b61110f565b610494610543366004613900565b600f6020526000908152604090205473ffffffffffffffffffffffffffffffffffffffff1681565b6103aa610579366004613900565b6112a2565b60045474010000000000000000000000000000000000000000900460ff166103fe565b6103aa6105af3660046139a4565b6112af565b61063b6040805160808101825260008082526020820181905291810182905260608101919091525060408051608081018252600c5464ffffffffff80821683527affffffffffffffffffffffffffffffffffffffffffffffffffffff650100000000009283900481166020850152600d549182169484019490945204909116606082015290565b60405161038e9190600060808201905064ffffffffff83511682527affffffffffffffffffffffffffffffffffffffffffffffffffffff602084015116602083015264ffffffffff60408401511660408301527affffffffffffffffffffffffffffffffffffffffffffffffffffff606084015116606083015292915050565b6103aa6113a3565b6103846106d1366004613900565b60136020526000908152604090205481565b6103846106f1366004613900565b73ffffffffffffffffffffffffffffffffffffffff166000908152600e602052604090205490565b6104947f000000000000000000000000470ebf5f030ed85fc1ed4c2d36b9dd02e77cf1b781565b61038461074e366004613900565b611649565b610384610761366004613978565b6116ba565b61038462093a8081565b600b5461049490640100000000900473ffffffffffffffffffffffffffffffffffffffff1681565b600b546103c99063ffffffff1681565b6103aa611907565b6103aa611a47565b600a546107e8907401000000000000000000000000000000000000000090046bffffffffffffffffffffffff1681565b6040516bffffffffffffffffffffffff909116815260200161038e565b610384610813366004613900565b60116020526000908152604090205481565b610384610833366004613900565b611ab3565b6103aa6108463660046139bd565b611b98565b6103aa6108593660046139a4565b611ca2565b6103aa61086c3660046139e3565b611cb4565b61038461087f366004613900565b611e81565b6103aa610892366004613a24565b611efd565b6103aa6108a5366004613900565b6120fc565b6103aa6108b83660046139a4565b61222c565b6001546104949073ffffffffffffffffffffffffffffffffffffffff1681565b6103aa612346565b610384612356565b6103aa6108fb366004613900565b612365565b600a546104949073ffffffffffffffffffffffffffffffffffffffff1681565b6103fe61092e366004613ade565b600260209081526000928352604080842090915290825290205460ff1681565b61038461095c366004613900565b60106020526000908152604090205481565b6005546104949073ffffffffffffffffffffffffffffffffffffffff1681565b61038460095481565b6104947f0000000000000000000000000e7b53dde30754a94d4b10c9cdcaca1c749ecd1b81565b6103aa6109cc366004613900565b6124aa565b6000806109dc612581565b90506109e8838261267b565b9392505050565b60005473ffffffffffffffffffffffffffffffffffffffff163314610a40576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b604051811515907f18f4a9a726c72020fd959c636d2fd464c6cefe90afeaea3c830b971614cf70b690600090a2600380547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016911515919091179055565b60005473ffffffffffffffffffffffffffffffffffffffff163314610aef576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8116610b3c576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60035460405173ffffffffffffffffffffffffffffffffffffffff808416926101009004169033907f374d23b359cab0f8963c5c1715a6de7974f53af00aecc27de50d93906b70943e90600090a46003805473ffffffffffffffffffffffffffffffffffffffff909216610100027fffffffffffffffffffffff0000000000000000000000000000000000000000ff909216919091179055565b610c04336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b610c3a576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8116610c87576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600580547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff83169081179091556040517f7cbcf2db31edf0f80b106b728f3e8f75d23576649e580cde45821df75db331e990600090a250565b60045473ffffffffffffffffffffffffffffffffffffffff163314610d47576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60005473ffffffffffffffffffffffffffffffffffffffff163303610d98576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600154604051339173ffffffffffffffffffffffffffffffffffffffff16907fe963dc9c0d2165b080440a5d2665566142f2426b1ea15f3da8390b0fd336b06490600090a3600180547fffffffffffffffffffffffff00000000000000000000000000000000000000009081163317909155600480549091169055565b60065473ffffffffffffffffffffffffffffffffffffffff16610e9b57610e60336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b610e96576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b610eec565b60065473ffffffffffffffffffffffffffffffffffffffff163314610eec576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8116610f39576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600b80547fffffffffffffffff0000000000000000000000000000000000000000ffffffff1664010000000073ffffffffffffffffffffffffffffffffffffffff8416908102919091179091556040519081527f3ba4758949febc607e14523620298f8b5995b1848492ad7aa083372ac886ae07906020015b60405180910390a150565b610fc56127c7565b600b54336000908152601460205260408120549091610fec9163ffffffff90911690613b42565b905042811115611036576040517f497e9598000000000000000000000000000000000000000000000000000000008152426004820152602481018290526044015b60405180910390fd5b611043333385853361281c565b505050565b611076336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b6110ac576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6110b4612b3b565b565b6040805180820182526000808252602091820181905273ffffffffffffffffffffffffffffffffffffffff8516815260128252828120848252825282902082518084019093528054835260010154908201525b92915050565b60065473ffffffffffffffffffffffffffffffffffffffff166111955761115a336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b611190576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6111e6565b60065473ffffffffffffffffffffffffffffffffffffffff1633146111e6576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8116611233576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600680547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff83169081179091556040517f16d61a8ae20f45aed7c5f705859e84b0292aabf52ce61496c63db9ab14c228b490600090a250565b6112ac3382612bb8565b50565b3373ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000e7b53dde30754a94d4b10c9cdcaca1c749ecd1b1614801590611320575061131e336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b155b15611357576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b80600860008282546113699190613b42565b9091555050604080518281524260208201527f1e215fdd40f0b4854c5a2b2cfe53859ca232f085a5b129c9f65b6bfeb094c5e49101610fb2565b6113ab6127c7565b6000806113b6612581565b600d80547affffffffffffffffffffffffffffffffffffffffffffffffffffff8316650100000000000264ffffffffff91821617909155600c549192506113fd9116612c5d565b600d80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000001664ffffffffff9290921691909117905573ffffffffffffffffffffffffffffffffffffffff8216156114c85761147682827affffffffffffffffffffffffffffffffffffffffffffffffffffff1661267b565b73ffffffffffffffffffffffffffffffffffffffff831660009081526010602090815260408083209390935560119052207affffffffffffffffffffffffffffffffffffffffffffffffffffff821690555b5060055473ffffffffffffffffffffffffffffffffffffffff16331461151a576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600754600003611556576040517f1090380d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600a5442906115a29073ffffffffffffffffffffffffffffffffffffffff8116907401000000000000000000000000000000000000000090046bffffffffffffffffffffffff16613b55565b73ffffffffffffffffffffffffffffffffffffffff1611156115f0576040517f51e624a700000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6115f8612c72565b600854600954811015611637576040517f54db0c8c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600060085561164581612cee565b5050565b73ffffffffffffffffffffffffffffffffffffffff8116600090815260146020526040812054156116b257600b5473ffffffffffffffffffffffffffffffffffffffff83166000908152601460205260409020546116ad9163ffffffff1690613b42565b611109565b600092915050565b60004382106116f5576040517f4e47846c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff83166000908152601360205260408120549081900361172d576000915050611109565b73ffffffffffffffffffffffffffffffffffffffff84166000908152601260205260408120849161175f600185613b81565b815260200190815260200160002060000154116117c15773ffffffffffffffffffffffffffffffffffffffff84166000908152601260205260408120906117a7600184613b81565b815260200190815260200160002060010154915050611109565b73ffffffffffffffffffffffffffffffffffffffff84166000908152601260209081526040808320838052909152902054831015611803576000915050611109565b600080611811600184613b81565b90505b818111156118ca576000600261182a8484613b81565b6118349190613b94565b61183e9083613b81565b73ffffffffffffffffffffffffffffffffffffffff881660009081526012602090815260408083208484528252918290208251808401909352805480845260019091015491830191909152919250908790036118a4576020015194506111099350505050565b80518711156118b5578193506118c3565b6118c0600183613b81565b92505b5050611814565b5073ffffffffffffffffffffffffffffffffffffffff85166000908152601260209081526040808320938352929052206001015491505092915050565b600354610100900473ffffffffffffffffffffffffffffffffffffffff16331461195d576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60015473ffffffffffffffffffffffffffffffffffffffff1633036119ae576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60008054604051339273ffffffffffffffffffffffffffffffffffffffff909216917ff07131157ebea15896dc89264eb9a7572e67cc9fad6b855015730fcec10704e091a3600080547fffffffffffffffffffffffff00000000000000000000000000000000000000001633179055600380547fffffffffffffffffffffff0000000000000000000000000000000000000000ff169055565b611a75336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b611aab576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6110b4612eeb565b600b54600090640100000000900473ffffffffffffffffffffffffffffffffffffffff163314611b0f576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8216611b5c576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff82166000908152600e6020526040902054611b9083338360018361281c565b90505b919050565b611bc6336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b611bfc576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b62278d0063ffffffff82161115611c3f576040517fd252903400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600b80547fffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000001663ffffffff83169081179091556040519081527f885b3532bfa278e4874fcd9bcd74c49a1682c9ff7eaa6b301cea6a7969e5813190602001610fb2565b611caa6127c7565b6112ac3382612f5a565b611ce2336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b611d18576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b7f000000000000000000000000470ebf5f030ed85fc1ed4c2d36b9dd02e77cf1b773ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161480611dbd57507f0000000000000000000000000e7b53dde30754a94d4b10c9cdcaca1c749ecd1b73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16145b15611df4576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b611e1573ffffffffffffffffffffffffffffffffffffffff84168383613012565b8273ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff167f879f92dded0f26b83c3e00b12e0395dc72cfc3077343d1854ed6988edd1f909683604051611e7491815260200190565b60405180910390a3505050565b73ffffffffffffffffffffffffffffffffffffffff811660009081526013602052604081205480611eb35760006109e8565b73ffffffffffffffffffffffffffffffffffffffff8316600090815260126020526040812090611ee4600184613b81565b8152602001908152602001600020600101549392505050565b611f2b336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b611f61576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8316611fae576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040805180820190915260008082526020820152819060005b828110156120f457848482818110611fe157611fe1613bcf565b905060400201803603810190611ff79190613bfe565b91508160200151151582600001517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19168773ffffffffffffffffffffffffffffffffffffffff167ff5736e75de2c751f775d4c5ed517289f77074f8c337f451ba4c0c3ed1dd7f9ad60405160405180910390a460208281015173ffffffffffffffffffffffffffffffffffffffff8816600090815260028352604080822086517fffffffff000000000000000000000000000000000000000000000000000000001683529093529190912080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016911515919091179055600101611fc7565b505050505050565b6121046127c7565b80600061210f612581565b600d80547affffffffffffffffffffffffffffffffffffffffffffffffffffff8316650100000000000264ffffffffff91821617909155600c549192506121569116612c5d565b600d80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000001664ffffffffff9290921691909117905573ffffffffffffffffffffffffffffffffffffffff821615612221576121cf82827affffffffffffffffffffffffffffffffffffffffffffffffffffff1661267b565b73ffffffffffffffffffffffffffffffffffffffff831660009081526010602090815260408083209390935560119052207affffffffffffffffffffffffffffffffffffffffffffffffffffff821690555b506116458283613093565b61225a336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b612290576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b62093a808110156122cd576040517fd252903400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600c544264ffffffffff90911610612311576040517f398d4d3200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60098190556040518181527f823b3cede11929e1b876086e20886121c9c32f04426a36ed323a85d541df3b8e90602001610fb2565b61234e6127c7565b6110b4612c72565b6000612360612581565b905090565b612393336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b6123c9576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff8116612416576040517fe6c4247b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60045460015460405173ffffffffffffffffffffffffffffffffffffffff8085169381169216907f4857570a90fe0a0fc580e89a287e77576141ac8e2e8b3710cd26db44f44156c190600090a4600480547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff92909216919091179055565b6124d8336000357fffffffff0000000000000000000000000000000000000000000000000000000016612704565b61250e576040517fc0185c6400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600a80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff83169081179091556040519081527ffac87d3c8a428a7011075404cc37f2669246fcd04ff5c3098e32d122de1d9c6890602001610fb2565b6000600754600014806125a25750600c54600d5464ffffffffff9081169116145b156125d45750600d546501000000000090047affffffffffffffffffffffffffffffffffffffffffffffffffffff1690565b600754600c54600d547affffffffffffffffffffffffffffffffffffffffffffffffffffff650100000000008304169164ffffffffff918216916126189116612c5d565b6126229190613b81565b61262c9190613c84565b61263e90670de0b6b3a7640000613c84565b6126489190613b94565b600d5461236091906501000000000090047affffffffffffffffffffffffffffffffffffffffffffffffffffff16613b42565b73ffffffffffffffffffffffffffffffffffffffff82166000908152601060209081526040808320546011909252822054670de0b6b3a7640000906126c09085613b81565b73ffffffffffffffffffffffffffffffffffffffff86166000908152600e60205260409020546126f09190613c84565b6126fa9190613b94565b6109e89190613b42565b60035460009060ff1615612736575060005473ffffffffffffffffffffffffffffffffffffffff838116911614611109565b60015473ffffffffffffffffffffffffffffffffffffffff848116911614806127b1575073ffffffffffffffffffffffffffffffffffffffff831660009081526002602090815260408083207fffffffff000000000000000000000000000000000000000000000000000000008616845290915290205460ff165b156127be57506001611109565b50600092915050565b60045474010000000000000000000000000000000000000000900460ff16156110b4576040517fd93c066500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b846000612827612581565b600d80547affffffffffffffffffffffffffffffffffffffffffffffffffffff8316650100000000000264ffffffffff91821617909155600c5491925061286e9116612c5d565b600d80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000001664ffffffffff9290921691909117905573ffffffffffffffffffffffffffffffffffffffff821615612939576128e782827affffffffffffffffffffffffffffffffffffffffffffffffffffff1661267b565b73ffffffffffffffffffffffffffffffffffffffff831660009081526010602090815260408083209390935560119052207affffffffffffffffffffffffffffffffffffffffffffffffffffff821690555b5083600003612974576040517f54db0c8c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff86166000908152600e602052604090205480851115612a1a576040517fdb42144d00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000470ebf5f030ed85fc1ed4c2d36b9dd02e77cf1b7166004820152602481018690526044810182905260640161102d565b73ffffffffffffffffffffffffffffffffffffffff87166000908152600e60205260408120868303905560078054879290612a56908490613b81565b909155505073ffffffffffffffffffffffffffffffffffffffff8088166000908152600f6020526040812054612a8e9216908761316c565b612acf73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000470ebf5f030ed85fc1ed4c2d36b9dd02e77cf1b7168787613012565b6040805173ffffffffffffffffffffffffffffffffffffffff8881168252602082018890528916917fd1c19fbcd4551a5edfb66d43d2e337c04837afda3482b42bdf569a8fccdae5fb910160405180910390a28315612b3257612b328784613093565b50505050505050565b612b4361330f565b600480547fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff1690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390a1565b73ffffffffffffffffffffffffffffffffffffffff8083166000818152600f602081815260408084208054600e845282862054949093528787167fffffffffffffffffffffffff00000000000000000000000000000000000000008416811790915590519190951694919391928592917f3134e8a2e6d97e929a7e54011ea5485d7d196dd5f0ba4d4ef95803e8e3fc257f9190a4612c5782848361316c565b50505050565b600042821015612c6b575090565b5042919050565b7f0000000000000000000000000e7b53dde30754a94d4b10c9cdcaca1c749ecd1b73ffffffffffffffffffffffffffffffffffffffff16631249c58b6040518163ffffffff1660e01b8152600401600060405180830381600087803b158015612cda57600080fd5b505af1158015612c57573d6000803e3d6000fd5b600954600c5464ffffffffff164210612d6857612d0b8183613b94565b600c805464ffffffffff16650100000000007affffffffffffffffffffffffffffffffffffffffffffffffffffff93841681029190911791829055612d569284929190910416613c84565b612d609083613b81565b600855612e35565b600c54600090612d8090429064ffffffffff16613b81565b600c54909150600090612db9906501000000000090047affffffffffffffffffffffffffffffffffffffffffffffffffffff1683613c84565b905082612dc68286613b42565b612dd09190613b94565b600c805464ffffffffff16650100000000007affffffffffffffffffffffffffffffffffffffffffffffffffffff93841681029190911791829055612e1b9286929190910416613c84565b612e258286613b42565b612e2f9190613b81565b60085550505b600d80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000164264ffffffffff811691909117909155612e76908290613b42565b600c80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000001664ffffffffff929092169190911790555050600a805473ffffffffffffffffffffffffffffffffffffffff164263ffffffff167401000000000000000000000000000000000000000002179055565b612ef36127c7565b600480547fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff16740100000000000000000000000000000000000000001790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258612b8e3390565b80600003612f94576040517f54db0c8c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b612fd673ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000470ebf5f030ed85fc1ed4c2d36b9dd02e77cf1b716333084613363565b612fe082826133a9565b73ffffffffffffffffffffffffffffffffffffffff8083166000908152600f602052604081205461164592168361316c565b60405173ffffffffffffffffffffffffffffffffffffffff83811660248301526044820183905261104391859182169063a9059cbb906064015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050613572565b73ffffffffffffffffffffffffffffffffffffffff821660009081526010602052604090205480156110435773ffffffffffffffffffffffffffffffffffffffff808416600090815260106020526040812055613113907f0000000000000000000000000e7b53dde30754a94d4b10c9cdcaca1c749ecd1b168383613012565b6040805173ffffffffffffffffffffffffffffffffffffffff8481168252602082018490528516917f540798df468d7b23d11f156fdb954cb19ad414d150722a7b6d55ba369dea792e91015b60405180910390a2505050565b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16141580156131a85750600081115b156110435773ffffffffffffffffffffffffffffffffffffffff8316156132605773ffffffffffffffffffffffffffffffffffffffff831660009081526013602052604081205490816131fc576000613240565b73ffffffffffffffffffffffffffffffffffffffff851660009081526012602052604081209061322d600185613b81565b8152602001908152602001600020600101545b9050600061324e8483613b81565b905061325c86848484613608565b5050505b73ffffffffffffffffffffffffffffffffffffffff8216156110435773ffffffffffffffffffffffffffffffffffffffff821660009081526013602052604081205490816132af5760006132f3565b73ffffffffffffffffffffffffffffffffffffffff84166000908152601260205260408120906132e0600185613b81565b8152602001908152602001600020600101545b905060006133018483613b42565b90506120f485848484613608565b60045474010000000000000000000000000000000000000000900460ff166110b4576040517f8dfc202b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60405173ffffffffffffffffffffffffffffffffffffffff8481166024830152838116604483015260648201839052612c579186918216906323b872dd9060840161304c565b8160006133b4612581565b600d80547affffffffffffffffffffffffffffffffffffffffffffffffffffff8316650100000000000264ffffffffff91821617909155600c549192506133fb9116612c5d565b600d80547fffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000001664ffffffffff9290921691909117905573ffffffffffffffffffffffffffffffffffffffff8216156134c65761347482827affffffffffffffffffffffffffffffffffffffffffffffffffffff1661267b565b73ffffffffffffffffffffffffffffffffffffffff831660009081526010602090815260408083209390935560119052207affffffffffffffffffffffffffffffffffffffffffffffffffffff821690555b5081600760008282546134d99190613b42565b909155505073ffffffffffffffffffffffffffffffffffffffff83166000908152600e602052604081208054849290613513908490613b42565b909155505073ffffffffffffffffffffffffffffffffffffffff831660008181526014602052604090819020429055517f9e71bc8eea02a63969f509818f2dafb9254532904319f9dbda79b67bd34a5f3d9061315f9085815260200190565b600061359473ffffffffffffffffffffffffffffffffffffffff84168361377e565b905080516000141580156135b95750808060200190518101906135b79190613c9b565b155b15611043576040517f5274afe700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8416600482015260240161102d565b600083118015613659575073ffffffffffffffffffffffffffffffffffffffff841660009081526012602052604081204391613645600187613b81565b815260200190815260200160002060000154145b156136a95773ffffffffffffffffffffffffffffffffffffffff841660009081526012602052604081208291613690600187613b81565b8152602081019190915260400160002060010155613727565b604080518082018252438152602080820184815273ffffffffffffffffffffffffffffffffffffffff8816600090815260128352848120888252909252929020905181559051600191820155613700908490613b42565b73ffffffffffffffffffffffffffffffffffffffff85166000908152601360205260409020555b604080518381526020810183905273ffffffffffffffffffffffffffffffffffffffff8616917fdec2bacdd2f05b59de34da9b523dff8be42e5e38e818c82fdb0bae774387a724910160405180910390a250505050565b60606109e883836000846000808573ffffffffffffffffffffffffffffffffffffffff1684866040516137b19190613cb8565b60006040518083038185875af1925050503d80600081146137ee576040519150601f19603f3d011682016040523d82523d6000602084013e6137f3565b606091505b509150915061380386838361380d565b9695505050505050565b6060826138225761381d8261389c565b6109e8565b8151158015613846575073ffffffffffffffffffffffffffffffffffffffff84163b155b15613895576040517f9996b31500000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8516600482015260240161102d565b50806109e8565b8051156138ac5780518082602001fd5b6040517f1425ea4200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff811681146112ac57600080fd5b60006020828403121561391257600080fd5b81356109e8816138de565b80151581146112ac57600080fd5b60006020828403121561393d57600080fd5b81356109e88161391d565b6000806040838503121561395b57600080fd5b82359150602083013561396d8161391d565b809150509250929050565b6000806040838503121561398b57600080fd5b8235613996816138de565b946020939093013593505050565b6000602082840312156139b657600080fd5b5035919050565b6000602082840312156139cf57600080fd5b813563ffffffff811681146109e857600080fd5b6000806000606084860312156139f857600080fd5b8335613a03816138de565b92506020840135613a13816138de565b929592945050506040919091013590565b600080600060408486031215613a3957600080fd5b8335613a44816138de565b9250602084013567ffffffffffffffff811115613a6057600080fd5b8401601f81018613613a7157600080fd5b803567ffffffffffffffff811115613a8857600080fd5b8660208260061b8401011115613a9d57600080fd5b939660209190910195509293505050565b80357fffffffff0000000000000000000000000000000000000000000000000000000081168114611b9357600080fd5b60008060408385031215613af157600080fd5b8235613afc816138de565b9150613b0a60208401613aae565b90509250929050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b8082018082111561110957611109613b13565b73ffffffffffffffffffffffffffffffffffffffff818116838216019081111561110957611109613b13565b8181038181111561110957611109613b13565b600082613bca577f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b500490565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b60006040828403128015613c1157600080fd5b506040805190810167ffffffffffffffff81118282101715613c5c577f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b604052613c6883613aae565b81526020830135613c788161391d565b60208201529392505050565b808202811582820484141761110957611109613b13565b600060208284031215613cad57600080fd5b81516109e88161391d565b6000825160005b81811015613cd95760208186018101518583015201613cbf565b50600092019182525091905056fea264697066735822122025f39ebbee88267208f433ccdfa8f1b30614e16ef2785ac5b001649b6cad6f1764736f6c634300081c0033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

0000000000000000000000009f90430179d9b67341bfa50559bc7b8e35629f1b00000000000000000000000094b62a27a2f23cbdc0220826a8452fb5055cf273000000000000000000000000470ebf5f030ed85fc1ed4c2d36b9dd02e77cf1b70000000000000000000000000e7b53dde30754a94d4b10c9cdcaca1c749ecd1b

-----Decoded View---------------
Arg [0] : _rescuer (address): 0x9f90430179D9b67341BFa50559bc7B8E35629f1b
Arg [1] : _executor (address): 0x94b62A27a2f23CBdc0220826a8452fB5055cF273
Arg [2] : _stakingToken (address): 0x470EBf5f030Ed85Fc1ed4C2d36B9DD02e77CF1b7
Arg [3] : _rewardToken (address): 0x0E7B53dDe30754A94D4B10C9CdCaCA1C749ECd1b

-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 0000000000000000000000009f90430179d9b67341bfa50559bc7b8e35629f1b
Arg [1] : 00000000000000000000000094b62a27a2f23cbdc0220826a8452fb5055cf273
Arg [2] : 000000000000000000000000470ebf5f030ed85fc1ed4c2d36b9dd02e77cf1b7
Arg [3] : 0000000000000000000000000e7b53dde30754a94d4b10c9cdcaca1c749ecd1b


Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]

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.