ETH Price: $4,176.04 (-0.47%)

Contract

0xE6f0e997D25B4266479BD36e45a97CCAa8545490

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

N/A
Transaction Hash
Method
Block
From
To

There are no matching entries

1 Internal Transaction found.

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To
63963102025-07-21 23:05:2164 days ago1753139121  Contract Creation0 ETH

Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0xE6f0e997...Aa8545490 in BNB Smart Chain Mainnet
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
AgoraStableSwapFactory

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 100000000 runs

Other Settings:
cancun EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.21;

// ====================================================================
//             _        ______     ___   _______          _
//            / \     .' ___  |  .'   `.|_   __ \        / \
//           / _ \   / .'   \_| /  .-.  \ | |__) |      / _ \
//          / ___ \  | |   ____ | |   | | |  __ /      / ___ \
//        _/ /   \ \_\ `.___]  |\  `-'  /_| |  \ \_  _/ /   \ \_
//       |____| |____|`._____.'  `.___.'|____| |___||____| |____|
// ====================================================================
// ==================== AgoraStableSwapFactory ========================
// ====================================================================

import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";

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

import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import { AgoraAccessControl } from "agora-contracts/access-control/AgoraAccessControl.sol";

import { AgoraStableSwapPair, InitializeParams as AgoraStableSwapPairParams } from "./AgoraStableSwapPair.sol";
import { AgoraTransparentUpgradeableProxy, ConstructorParams as AgoraTransparentUpgradeableProxyParams } from "agora-contracts/proxy/AgoraTransparentUpgradeableProxy.sol";
import { Erc1967Implementation } from "agora-contracts/proxy/Erc1967Implementation.sol";
import { ICreateX } from "createx/ICreateX.sol";

/// @notice The ```InitializeParams``` struct is used to initialize the AgoraStableSwapFactory
/// @param initialStableSwapImplementation The implementation address for the `AgoraStableSwapPair` proxies
/// @param initialStableSwapProxyAdminAddress The ProxyAdmin address for the `AgoraStableSwapPair` proxies deployed by the factory
/// @param initialFactoryAccessControlManager The address that controls the factory
/// @param initialImplementationSetter The address that controls the `AgoraStableSwapPair` implementation used by the factory
/// @param initialApprovedDeployers The addresses that are initially approved to deploy new pairs
/// @param initialDefaultAdminAddress The default address of the initial admin
/// @param initialDefaultWhitelister The default address of the initial whitelister
/// @param initialDefaultFeeSetter The default address of the initial fee setter
/// @param initialDefaultTokenRemover The default address of the initial token remover
/// @param initialDefaultPauser The default address of the initial pauser
/// @param initialDefaultPriceSetter The default address of the initial price setter
/// @param initialDefaultTokenReceiver The default address of the initial token receiver
/// @param initialDefaultFeeReceiver The default address of the initial fee receiver
struct InitializeParams {
    address initialStableSwapImplementation;
    address initialStableSwapProxyAdminAddress;
    address initialFactoryAccessControlManager;
    address initialImplementationSetter;
    address[] initialApprovedDeployers;
    address initialDefaultAdminAddress;
    address initialDefaultWhitelister;
    address initialDefaultFeeSetter;
    address initialDefaultTokenRemover;
    address initialDefaultPauser;
    address initialDefaultPriceSetter;
    address initialDefaultTokenReceiver;
    address initialDefaultFeeReceiver;
}

/// @title AgoraStableSwapFactory
/// @notice The AgoraStableSwapFactory is a contract that manages the deployment of AgoraStableSwapPair contracts
/// @author Agora
contract AgoraStableSwapFactory is AgoraAccessControl, Initializable, Erc1967Implementation {
    using EnumerableSet for EnumerableSet.AddressSet;
    using Strings for uint256;
    using SafeCast for *;

    /// @notice the address of the CREATEX_DEPLOYER contract
    address constant CREATEX_DEPLOYER = 0xba5Ed099633D3B313e4D5F7bdc1305d3c28ba5Ed;

    /// @notice the APPROVED_DEPLOYER identifier
    string public constant APPROVED_DEPLOYER = "APPROVED_DEPLOYER";

    /// @notice the IMPLEMENTATION_SETTER_ROLE identifier
    string public constant IMPLEMENTATION_SETTER_ROLE = "IMPLEMENTATION_SETTER_ROLE";

    //==============================================================================
    // Storage Structs
    //==============================================================================

    /// @notice The ```AgoraStableSwapDefaultParamsStorage``` struct is used to store the initial roles of the `AgoraStableSwapPair`
    /// @param initialDefaultAdminAddress The default address of the initial admin
    /// @param initialDefaultWhitelister The default address of the initial whitelister
    /// @param initialDefaultFeeSetter The default address of the initial fee setter
    /// @param initialDefaultTokenRemover The default address of the initial token remover
    /// @param initialDefaultPauser The default address of the initial pauser
    /// @param initialDefaultPriceSetter The default address of the initial price setter
    /// @param initialDefaultTokenReceiver The default address of the initial token receiver
    /// @param initialDefaultFeeReceiver The default address of the initial fee receiver
    struct AgoraStableSwapDefaultParamsStorage {
        address initialDefaultAdminAddress;
        address initialDefaultWhitelister;
        address initialDefaultFeeSetter;
        address initialDefaultTokenRemover;
        address initialDefaultPauser;
        address initialDefaultPriceSetter;
        address initialDefaultTokenReceiver;
        address initialDefaultFeeReceiver;
    }

    /// @notice The ```AgoraStableSwapFactoryStorage``` struct stores the main state of the factory
    /// @param allPairs A EnumerableSet containing addresses of all pairs created by this factory
    /// @param getPair A mapping from token pairs to their corresponding swap pair contract address
    /// @param stableSwapImplementation The implementation contract address used for all proxy pairs
    /// @param proxyAdminAddress The admin address for all proxy pairs
    /// @param pairDefaultParamsStorage Default parameters used when initializing new pairs
    struct AgoraStableSwapFactoryStorage {
        EnumerableSet.AddressSet allPairs;
        mapping(address => mapping(address => address)) getPair;
        address stableSwapImplementation;
        address proxyAdminAddress;
        AgoraStableSwapDefaultParamsStorage pairDefaultParamsStorage;
    }

    //==============================================================================
    // Constructor & Initalization Functions
    //==============================================================================

    constructor() {
        _disableInitializers();
    }

    /// @notice The ```initialize``` function initializes the AgoraStableSwapFactory contract with initial parameters
    /// @dev This function can only be called once due to the initializer modifier
    /// @param _params The initialization parameters struct
    function initialize(InitializeParams memory _params) external initializer {
        // Set the admin role
        _initializeAgoraAccessControl({ _initialAdminAddress: _params.initialFactoryAccessControlManager });

        // `proxyAdminAddress` is the proxy admin for the proxy contracts generated with this factory
        _getPointerToFactoryStorage().proxyAdminAddress = _params.initialStableSwapProxyAdminAddress;

        // We temporarily set the manager role to the sender to set the defaultValues on initialization
        _assignRole({ _role: ACCESS_CONTROL_MANAGER_ROLE, _newAddress: msg.sender, _addRole: true });

        // We temporarily set the implementation setter role to the sender to set the pair implementation address
        _assignRole({ _role: IMPLEMENTATION_SETTER_ROLE, _newAddress: msg.sender, _addRole: true });

        // Effects: set the pair implementation address
        setStableSwapImplementation(_params.initialStableSwapImplementation);

        // Remove privileges from deployer
        _assignRole({ _role: IMPLEMENTATION_SETTER_ROLE, _newAddress: msg.sender, _addRole: false });

        // We set the `initialApprovedDeployers` as approved deployers
        setApprovedDeployers(_params.initialApprovedDeployers, true);

        // We set the pair implementation setter role
        _assignRole({
            _role: IMPLEMENTATION_SETTER_ROLE,
            _newAddress: _params.initialImplementationSetter,
            _addRole: true
        });

        // We set the default roles for the AgoraStableSwapPair Proxy initialization
        setDefaultRoles({
            _initialAdminAddress: _params.initialDefaultAdminAddress,
            _initialWhitelister: _params.initialDefaultWhitelister,
            _initialFeeSetter: _params.initialDefaultFeeSetter,
            _initialTokenRemover: _params.initialDefaultTokenRemover,
            _initialPauser: _params.initialDefaultPauser,
            _initialPriceSetter: _params.initialDefaultPriceSetter,
            _initialTokenReceiver: _params.initialDefaultTokenReceiver,
            _initialFeeReceiver: _params.initialDefaultFeeReceiver
        });

        // Remove privileges from deployer
        if (_params.initialFactoryAccessControlManager != msg.sender) {
            _assignRole({ _role: ACCESS_CONTROL_MANAGER_ROLE, _newAddress: msg.sender, _addRole: false });
        }
    }

    //==============================================================================
    // Erc 7201: UnstructuredNamespace Storage Functions
    //==============================================================================

    /// @notice The ```AGORA_STABLE_SWAP_FACTORY_STORAGE_SLOT``` is the storage slot for the AgoraStableSwapFactoryStorage struct
    /// @dev keccak256(abi.encode(uint256(keccak256("AgoraStableSwapFactoryStorage")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 public constant AGORA_STABLE_SWAP_FACTORY_STORAGE_SLOT =
        0x024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000;

    /// @notice The ```_getPointerToStorage``` function returns a pointer to the AgoraStableSwapFactoryStorage struct
    /// @return $ A pointer to the AgoraStableSwapFactoryStorage struct
    function _getPointerToFactoryStorage() internal pure returns (AgoraStableSwapFactoryStorage storage $) {
        /// @solidity memory-safe-assembly
        assembly {
            $.slot := AGORA_STABLE_SWAP_FACTORY_STORAGE_SLOT
        }
    }

    //==============================================================================
    // Privileged Configuration Functions
    //==============================================================================

    /// @notice The ```setDefaultRoles``` function is used to store the default roles to initialize the AgoraStableSwapPair
    /// @dev Only the manager can set the default roles
    /// @param _initialAdminAddress The address of the initial admin
    /// @param _initialWhitelister The address of the initial whitelister
    /// @param _initialFeeSetter The address of the initial fee setter
    /// @param _initialTokenRemover The address of the initial token remover
    /// @param _initialPauser The address of the initial pauser
    /// @param _initialPriceSetter The address of the initial price setter
    /// @param _initialTokenReceiver The address of the initial token receiver
    /// @param _initialFeeReceiver The address of the initial fee receiver
    function setDefaultRoles(
        address _initialAdminAddress,
        address _initialWhitelister,
        address _initialFeeSetter,
        address _initialTokenRemover,
        address _initialPauser,
        address _initialPriceSetter,
        address _initialTokenReceiver,
        address _initialFeeReceiver
    ) public {
        // Checks: Only the manager can set the default roles
        _requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });

        AgoraStableSwapDefaultParamsStorage storage storageStruct = _getPointerToFactoryStorage()
            .pairDefaultParamsStorage;
        storageStruct.initialDefaultAdminAddress = _initialAdminAddress;
        storageStruct.initialDefaultWhitelister = _initialWhitelister;
        storageStruct.initialDefaultFeeSetter = _initialFeeSetter;
        storageStruct.initialDefaultTokenRemover = _initialTokenRemover;
        storageStruct.initialDefaultPauser = _initialPauser;
        storageStruct.initialDefaultPriceSetter = _initialPriceSetter;
        storageStruct.initialDefaultTokenReceiver = _initialTokenReceiver;
        storageStruct.initialDefaultFeeReceiver = _initialFeeReceiver;

        // Emit event for default roles being set
        emit SetDefaultRoles({
            initialAdminAddress: _initialAdminAddress,
            initialWhitelister: _initialWhitelister,
            initialFeeSetter: _initialFeeSetter,
            initialTokenRemover: _initialTokenRemover,
            initialPauser: _initialPauser,
            initialPriceSetter: _initialPriceSetter,
            initialTokenReceiver: _initialTokenReceiver,
            initialFeeReceiver: _initialFeeReceiver
        });
    }

    /// @notice The ```setApprovedDeployer``` function sets the approved deployers
    /// @dev Only the manager can set the approved deployers
    /// @param _approvedDeployers The addresses of the approved deployers
    /// @param _setApproved The boolean value indicating whether the deployers are approved
    function setApprovedDeployers(address[] memory _approvedDeployers, bool _setApproved) public {
        // Checks: Only the manager can set the approved deployers
        _requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });

        for (uint256 i = 0; i < _approvedDeployers.length; i++) {
            // Effects: Set the isApproved state
            _assignRole({ _role: APPROVED_DEPLOYER, _newAddress: _approvedDeployers[i], _addRole: _setApproved });

            // emit event
            emit SetApprovedDeployer({ approvedDeployer: _approvedDeployers[i], isApproved: _setApproved });
        }
    }

    /// @notice The ```setStableSwapImplementation``` function updates the pair implementation address
    /// @dev Only the implementation setter can update the pair implementation address
    /// @param _newImplementation The address of the new pair implementation
    function setStableSwapImplementation(address _newImplementation) public {
        // Checks: Only the implementation setter can set the implementation
        _requireSenderIsRole({ _role: IMPLEMENTATION_SETTER_ROLE });

        // Effects: Set the new implementation
        _getPointerToFactoryStorage().stableSwapImplementation = _newImplementation;

        // emit event
        emit SetStableSwapImplementation({ newImplementation: _newImplementation });
    }

    /// @notice The ```setPair``` function updates the storage of a token pair
    /// @dev Only the manager can update the storage of a token pair
    /// @param _tokenA the first token in the pair
    /// @param _tokenB the second token in the pair
    /// @param _pairAddress the address that the pair storage will be assigned to
    function setPair(address _tokenA, address _tokenB, address _pairAddress) external {
        // Checks: Only the manager can modify the pairs
        _requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });

        // Checks: tokens in swap should be different
        if (_tokenA == _tokenB) revert IdenticalAddresses();
        // Sort the tokens
        (address _token0, address _token1) = sortTokens(_tokenA, _tokenB);

        // Access the storage
        AgoraStableSwapFactoryStorage storage factoryStorage = _getPointerToFactoryStorage();

        // Effects: Modify storage from `allPairs`
        if (_pairAddress == address(0)) {
            address _pairToRemove = factoryStorage.getPair[_token0][_token1];
            factoryStorage.allPairs.remove(_pairToRemove);
        } else {
            factoryStorage.allPairs.add(_pairAddress);
        }

        // Effects: Modify storage from `getPair` on both directions
        factoryStorage.getPair[_token0][_token1] = _pairAddress;
        factoryStorage.getPair[_token1][_token0] = _pairAddress;

        // Emits the SetPair event
        emit SetPair(_token0, _token1, _pairAddress);
    }

    //==============================================================================
    //  FactoryStorage View Functions
    //==============================================================================

    /// @notice returns the storage of the factory default parameters
    function getAgoraStableSwapDefaultParamsStorage() public view returns (AgoraStableSwapDefaultParamsStorage memory) {
        return _getPointerToFactoryStorage().pairDefaultParamsStorage;
    }

    /// @notice returns the implementation address for the `AgoraStableSwapPair` proxies
    function stableSwapImplementation() public view returns (address) {
        return _getPointerToFactoryStorage().stableSwapImplementation;
    }

    /// @notice returns the ProxyAdmin contract address for the `AgoraStableSwapPair` proxies deployed by the factory
    function stableSwapProxyAdmin() public view returns (address) {
        return _getPointerToFactoryStorage().proxyAdminAddress;
    }

    /// @notice returns all pairs deployed by the factory
    function allPairs() public view returns (address[] memory _pairs) {
        return _getPointerToFactoryStorage().allPairs.values();
    }

    /// @notice The ```TokenInfo``` struct holds basic information about a token
    /// @param tokenAddress The smart contract address of the token
    /// @param name The name of the token
    /// @param symbol The symbol of the token
    /// @param decimals The number of decimals used by the token
    struct TokenInfo {
        address tokenAddress;
        string name;
        string symbol;
        uint256 decimals;
    }

    /// @notice The ```PairData``` struct is used to store addresses of a pair and its constituent tokens
    /// @param pairAddress The address of the pair contract
    /// @param token0 Information about the first token
    /// @param token1 Information about the second token
    struct PairData {
        address pairAddress;
        TokenInfo token0;
        TokenInfo token1;
    }

    function getAllPairData() public view returns (PairData[] memory) {
        address[] memory deployedPairs = allPairs();
        PairData[] memory pairData = new PairData[](deployedPairs.length);
        for (uint256 i = 0; i < deployedPairs.length; i++) {
            AgoraStableSwapPair pairAddress = AgoraStableSwapPair(deployedPairs[i]);
            IERC20Metadata token0 = IERC20Metadata(pairAddress.token0());
            IERC20Metadata token1 = IERC20Metadata(pairAddress.token1());

            pairData[i] = PairData({
                pairAddress: address(pairAddress),
                token0: TokenInfo({
                    tokenAddress: address(token0),
                    name: token0.name(),
                    decimals: token0.decimals(),
                    symbol: token0.symbol()
                }),
                token1: TokenInfo({
                    tokenAddress: address(token1),
                    name: token1.name(),
                    decimals: token1.decimals(),
                    symbol: token1.symbol()
                })
            });
        }
        return pairData;
    }

    /// @notice returns the pair address for the given tokens
    /// @param _token0 the address of the first token in the pair
    /// @param _token1 the address of the second token in the pair
    function getPairFromTokens(address _token0, address _token1) public view returns (address) {
        // The pairs are stored in both (_token0, _token1) and (_token1, _token0) so no need to sort the tokens.
        return _getPointerToFactoryStorage().getPair[_token0][_token1];
    }

    //==============================================================================
    // Pure Helper Functions
    //==============================================================================

    /// @notice The ```name``` function returns the name of the pairFactory
    /// @return _name The name of the pairFactory
    function name() public pure returns (string memory) {
        return "AgoraStableSwapFactory";
    }

    /// @notice returns the sorted tokens in ascending order based on their addresses
    /// @param _tokenA the first token in the pair
    /// @param _tokenB the second token in the pair
    function sortTokens(address _tokenA, address _tokenB) public pure returns (address _token0, address _token1) {
        (_token0, _token1) = _tokenA < _tokenB ? (_tokenA, _tokenB) : (_tokenB, _tokenA);
    }

    //==============================================================================
    // View Functions
    //==============================================================================

    /// @notice sorts and computes the pair deployment address based on the input tokens
    /// @param _tokenA the first token in the pair
    /// @param _tokenB the second token in the pair
    function computePairDeploymentAddress(
        address _tokenA,
        address _tokenB
    ) public view returns (address _pairDeploymentAddress) {
        // Checks: tokens in swap should be different
        if (_tokenA == _tokenB) revert IdenticalAddresses();
        // Sort the tokens
        (address _token0, address _token1) = sortTokens(_tokenA, _tokenB);

        // Checks: None of the tokens should be zero address
        if (_token0 == address(0)) revert ZeroAddress();

        bytes32 _salt = _generateSalt(_token0, _token1);
        // `this` is the factory proxy
        bytes32 _guardedSalt = keccak256(abi.encodePacked(bytes32(uint256(uint160(address(this)))), _salt));
        _pairDeploymentAddress = ICreateX(CREATEX_DEPLOYER).computeCreate3Address({ salt: _guardedSalt });
    }

    /// @notice computes the salt for the pair deployment address based on the input tokens
    /// @param _token0 the address of the first token in the pair
    /// @param _token1 the address of the second token in the pair
    function _generateSalt(address _token0, address _token1) internal view returns (bytes32 _salt) {
        _salt = bytes32(
            abi.encodePacked(
                address(this),
                hex"00", // no cross-chain redeploy protection
                bytes11(keccak256(abi.encodePacked(_token0, _token1)))
            )
        );
    }

    /// @notice generates the `AgoraStableSwapPairParams` struct for a new pair with the given parameters
    /// @param _pairArgs The parameters for creating a new pair
    function _generateStableSwapPairParams(
        CreatePairArgs memory _pairArgs
    ) internal view returns (AgoraStableSwapPairParams memory _pairParams) {
        AgoraStableSwapDefaultParamsStorage memory _defaultParamsStorage = _getPointerToFactoryStorage()
            .pairDefaultParamsStorage;
        // Gets the constructor arguments for the pair.
        _pairParams = AgoraStableSwapPairParams({
            token0: _pairArgs.token0,
            token0Decimals: _pairArgs.token0Decimals.toUint8(),
            token1: _pairArgs.token1,
            token1Decimals: _pairArgs.token1Decimals.toUint8(),
            minToken0PurchaseFee: _pairArgs.minToken0PurchaseFee,
            maxToken0PurchaseFee: _pairArgs.maxToken0PurchaseFee,
            minToken1PurchaseFee: _pairArgs.minToken1PurchaseFee,
            maxToken1PurchaseFee: _pairArgs.maxToken1PurchaseFee,
            token0PurchaseFee: _pairArgs.token0PurchaseFee,
            token1PurchaseFee: _pairArgs.token1PurchaseFee,
            initialAdminAddress: _defaultParamsStorage.initialDefaultAdminAddress,
            initialWhitelister: _defaultParamsStorage.initialDefaultWhitelister,
            initialFeeSetter: _defaultParamsStorage.initialDefaultFeeSetter,
            initialTokenRemover: _defaultParamsStorage.initialDefaultTokenRemover,
            initialPauser: _defaultParamsStorage.initialDefaultPauser,
            initialPriceSetter: _defaultParamsStorage.initialDefaultPriceSetter,
            initialTokenReceiver: _defaultParamsStorage.initialDefaultTokenReceiver,
            initialFeeReceiver: _defaultParamsStorage.initialDefaultFeeReceiver,
            minBasePrice: _pairArgs.minBasePrice,
            maxBasePrice: _pairArgs.maxBasePrice,
            minAnnualizedInterestRate: _pairArgs.minAnnualizedInterestRate,
            maxAnnualizedInterestRate: _pairArgs.maxAnnualizedInterestRate,
            basePrice: _pairArgs.basePrice,
            annualizedInterestRate: _pairArgs.annualizedInterestRate
        });
    }

    //==============================================================================
    // External Stateful Functions
    //==============================================================================

    /// @notice The `CreatePairArgs` struct is used for creating a new stable swap pair
    /// @param token0 The address of the first token in the pair
    /// @param token0Decimals The number of decimals for token0
    /// @param minToken0PurchaseFee The minimum purchase fee for token0, 18 decimals precision, max value 1
    /// @param maxToken0PurchaseFee The maximum purchase fee for token0, 18 decimals precision, max value 1
    /// @param token0PurchaseFee The purchase fee for token0, 18 decimals precision, max value 1
    /// @param token1 The address of the second token in the pair
    /// @param token1Decimals The number of decimals for token1
    /// @param minToken1PurchaseFee The minimum purchase fee for token1, 18 decimals precision, max value 1
    /// @param maxToken1PurchaseFee The maximum purchase fee for token1, 18 decimals precision, max value 1
    /// @param token1PurchaseFee The purchase fee for token1, 18 decimals precision, max value 1
    /// @param minBasePrice The minimum base price for the pair, 18 decimals precision, min/max value determined by difference between decimals of token0 and token1
    /// @param maxBasePrice The maximum base price for the pair, 18 decimals precision, min/max value determined by difference between decimals of token0 and token1
    /// @param basePrice The base price for the pair, 18 decimals precision, limited by token0 and token1 decimals
    /// @param minAnnualizedInterestRate The minimum annualized interest rate for the pair, 18 decimals precision, given as number i.e. 1e16 = 1%
    /// @param maxAnnualizedInterestRate The maximum annualized interest rate for the pair, 18 decimals precision, given as number i.e. 1e16 = 1%
    /// @param annualizedInterestRate The annualized interest rate for the pair, 18 decimals precision, given as number i.e. 1e16 = 1%
    struct CreatePairArgs {
        address token0;
        uint256 token0Decimals;
        uint256 minToken0PurchaseFee;
        uint256 maxToken0PurchaseFee;
        uint256 token0PurchaseFee;
        address token1;
        uint256 token1Decimals;
        uint256 minToken1PurchaseFee;
        uint256 maxToken1PurchaseFee;
        uint256 token1PurchaseFee;
        uint256 minBasePrice;
        uint256 maxBasePrice;
        uint256 basePrice;
        int256 minAnnualizedInterestRate;
        int256 maxAnnualizedInterestRate;
        int256 annualizedInterestRate;
    }

    /// @notice creates a new pair with the given parameters
    /// @param _pairArgs The parameters for creating a new pair
    function createPair(CreatePairArgs memory _pairArgs) external returns (address pair) {
        // Checks: Only the deployer can create a new pair
        _requireSenderIsRole({ _role: APPROVED_DEPLOYER });

        // Checks: tokens in swap should be different
        if (_pairArgs.token0 == _pairArgs.token1) revert IdenticalAddresses();

        // Sorts the variables according to their token address order
        (address _expectedToken0, ) = sortTokens(_pairArgs.token0, _pairArgs.token1);

        //Checks: The tokens should be ordered correctly
        if (_expectedToken0 != _pairArgs.token0) revert InvalidTokenOrder();

        // Checks: None of the tokens should be zero address
        if (_expectedToken0 == address(0)) revert ZeroAddress();

        // Checks: The pair must not already exist
        if (getPairFromTokens(_pairArgs.token0, _pairArgs.token1) != address(0)) revert PairExists();

        // Checks: The delta between the decimals must not be more than 12
        if (
            _pairArgs.token0Decimals > _pairArgs.token1Decimals + 12 ||
            _pairArgs.token1Decimals > _pairArgs.token0Decimals + 12
        ) revert DecimalDeltaTooLarge();

        // Gets the default parameters for the stable swap pair
        AgoraStableSwapPairParams memory _pairParams = _generateStableSwapPairParams({ _pairArgs: _pairArgs });

        // Gets the initialization data for the pair
        bytes memory _pairInitializationData = abi.encodeWithSelector(
            AgoraStableSwapPair.initialize.selector,
            _pairParams
        );

        // Sets the parameters for the proxy
        bytes memory _constructorArgs = abi.encode(
            AgoraTransparentUpgradeableProxyParams({
                logic: _getPointerToFactoryStorage().stableSwapImplementation,
                proxyAdminAddress: _getPointerToFactoryStorage().proxyAdminAddress,
                data: _pairInitializationData
            })
        );

        // Gets the creation code
        bytes memory bytecode = abi.encodePacked(type(AgoraTransparentUpgradeableProxy).creationCode, _constructorArgs);

        bytes32 _salt = _generateSalt(_pairArgs.token0, _pairArgs.token1);

        // Deploys the proxy admin with create3 (deployer-agnostic)
        pair = ICreateX(CREATEX_DEPLOYER).deployCreate3({ salt: _salt, initCode: bytecode });

        // Sets the pair address in the registry
        _getPointerToFactoryStorage().getPair[_pairArgs.token0][_pairArgs.token1] = pair;
        _getPointerToFactoryStorage().getPair[_pairArgs.token1][_pairArgs.token0] = pair;

        _getPointerToFactoryStorage().allPairs.add(pair);

        // Emits the PairCreated event
        emit PairCreated(_pairArgs.token0, _pairArgs.token1, pair);
        return pair;
    }

    /// @notice The ```Version``` struct is used to represent the version of the AgoraStableSwapFactory
    /// @param major The major version number
    /// @param minor The minor version number
    /// @param patch The patch version number
    struct Version {
        uint256 major;
        uint256 minor;
        uint256 patch;
    }

    /// @notice The ```version``` function returns the version of the AgoraStableSwapFactory
    /// @return _version The version of the AgoraStableSwapPair
    function version() public pure returns (Version memory _version) {
        _version = Version({ major: 2, minor: 2, patch: 0 });
    }

    //==============================================================================
    // Events
    //==============================================================================

    /// @notice PairCreated is emitted when a new pair is created
    /// @param token0 The address of the first token in the pair
    /// @param token1 The address of the second token in the pair
    /// @param pair The address of the newly created pair
    event PairCreated(address indexed token0, address indexed token1, address pair);

    /// @notice SetPair is emitted when pair storage is updated
    /// @param token0 The address of the first token in the pair
    /// @param token1 The address of the second token in the pair
    /// @param pair The address to which the pair is updated
    event SetPair(address indexed token0, address indexed token1, address pair);

    /// @param initialAdminAddress The default initial admin address for the proxies created by the factory
    /// @param initialWhitelister The default initial whitelister address for the proxies created by the factory
    /// @param initialFeeSetter The default initial fee setter address for the proxies created by the factory
    /// @param initialTokenRemover The default initial token remover address for the proxies created by the factory
    /// @param initialPauser The default initial pauser address for the proxies created by the factory
    /// @param initialPriceSetter The default initial price setter address for the proxies created by the factory
    /// @param initialTokenReceiver The default initial token receiver address for the proxies created by the factory
    /// @param initialFeeReceiver The default initial fee receiver address for the proxies created by the factory
    event SetDefaultRoles(
        address initialAdminAddress,
        address initialWhitelister,
        address initialFeeSetter,
        address initialTokenRemover,
        address initialPauser,
        address initialPriceSetter,
        address initialTokenReceiver,
        address initialFeeReceiver
    );

    /// @notice SetApprovedDeployer is emitted when the approved deployer is set.
    /// @param approvedDeployer The address of the approved deployer.
    /// @param isApproved Whether the deployer is approved or not.
    event SetApprovedDeployer(address indexed approvedDeployer, bool isApproved);

    /// @notice SetStableSwapImplementation is emitted when the implementation is set
    /// @param newImplementation The address of the new implementation
    event SetStableSwapImplementation(address indexed newImplementation);

    // ============================================================================================
    // Errors
    // ============================================================================================

    /// @notice IdenticalAddresses is thrown when the token0 and token1 are the same address.
    error IdenticalAddresses();

    /// @notice ZeroAddress is thrown when the address is zero.
    error ZeroAddress();

    /// @notice PairExists is thrown when the pair already exists.
    error PairExists();

    /// @notice DecimalDeltaTooLarge is thrown when the delta between the decimals of the tokens is invalid.
    error DecimalDeltaTooLarge();

    /// @notice InvalidTokenOrder is thrown when the token order is invalid.
    error InvalidTokenOrder();
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {

    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE =
        0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) revert InvalidInitialization();
        $._initialized = 1;
        if (isTopLevelCall) $._initializing = true;
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(
        uint64 version
    ) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) revert InvalidInitialization();
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) revert NotInitializing();
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) revert InvalidInitialization();
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import { IERC20 } from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {

    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

import { Math } from "./math/Math.sol";
import { SafeCast } from "./math/SafeCast.sol";
import { SignedMath } from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {

    using SafeCast for *;

    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(
        uint256 value
    ) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(
        int256 value
    ) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(
        uint256 value
    ) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) revert StringsInsufficientHexLength(value, length);
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(
        address addr
    ) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(
        address addr
    ) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(
        string memory input
    ) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input
    ) internal pure returns (bool success, uint256 value) {
        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseUint} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        uint256 result = 0;
        for (uint256 i = begin; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 9) return (false, 0);
            result *= 10;
            result += chr;
        }
        return (true, result);
    }

    /**
     * @dev Parse a decimal string and returns the value as a `int256`.
     *
     * Requirements:
     * - The string must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(
        string memory input
    ) internal pure returns (int256) {
        return parseInt(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (int256) {
        (bool success, int256 value) = tryParseInt(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
     * the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input
    ) internal pure returns (bool success, int256 value) {
        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
    }

    uint256 private constant ABS_MIN_INT256 = 2 ** 255;

    /**
     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character or if the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, int256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseIntUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseInt} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseIntUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, int256 value) {
        bytes memory buffer = bytes(input);

        // Check presence of a negative sign.
        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        bool positiveSign = sign == bytes1("+");
        bool negativeSign = sign == bytes1("-");
        uint256 offset = (positiveSign || negativeSign).toUint();

        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);

        if (absSuccess && absValue < ABS_MIN_INT256) {
            return (true, negativeSign ? -int256(absValue) : int256(absValue));
        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
            return (true, type(int256).min);
        } else {
            return (false, 0);
        }
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(
        string memory input
    ) internal pure returns (uint256) {
        return parseHexUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseHexUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input
    ) internal pure returns (bool success, uint256 value) {
        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
     * invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseHexUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseHexUint} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseHexUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        // skip 0x prefix if present
        bool hasPrefix =
            (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 offset = hasPrefix.toUint() * 2;

        uint256 result = 0;
        for (uint256 i = begin + offset; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 15) return (false, 0);
            result *= 16;
            unchecked {
                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
                // This guaratees that adding a value < 16 will not cause an overflow, hence the unchecked.
                result += chr;
            }
        }
        return (true, result);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(
        string memory input
    ) internal pure returns (address) {
        return parseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (address) {
        (bool success, address value) = tryParseAddress(input, begin, end);
        if (!success) revert StringsInvalidAddressFormat();
        return value;
    }

    /**
     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
     * formatted address. See {parseAddress} requirements.
     */
    function tryParseAddress(
        string memory input
    ) internal pure returns (bool success, address value) {
        return tryParseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
     * formatted address. See {parseAddress} requirements.
     */
    function tryParseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, address value) {
        if (end > bytes(input).length || begin > end) return (false, address(0));

        bool hasPrefix =
            (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;

        // check that input is the correct length
        if (end - begin == expectedLength) {
            // length guarantees that this does not overflow, and value is at most type(uint160).max
            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
            return (s, address(uint160(v)));
        } else {
            return (false, address(0));
        }
    }

    function _tryParseChr(
        bytes1 chr
    ) private pure returns (uint8) {
        uint8 value = uint8(chr);

        // Try to parse `chr`:
        // - Case 1: [0-9]
        // - Case 2: [a-f]
        // - Case 3: [A-F]
        // - otherwise not supported
        unchecked {
            if (value > 47 && value < 58) value -= 48;
            else if (value > 96 && value < 103) value -= 87;
            else if (value > 64 && value < 71) value -= 55;
            else return type(uint8).max;
        }

        return value;
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(
        bytes memory buffer,
        uint256 offset
    ) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(buffer, add(0x20, offset)))
        }
    }

}

File 6 of 38 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {

    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(
        uint256 value
    ) internal pure returns (uint248) {
        if (value > type(uint248).max) revert SafeCastOverflowedUintDowncast(248, value);
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(
        uint256 value
    ) internal pure returns (uint240) {
        if (value > type(uint240).max) revert SafeCastOverflowedUintDowncast(240, value);
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(
        uint256 value
    ) internal pure returns (uint232) {
        if (value > type(uint232).max) revert SafeCastOverflowedUintDowncast(232, value);
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(
        uint256 value
    ) internal pure returns (uint224) {
        if (value > type(uint224).max) revert SafeCastOverflowedUintDowncast(224, value);
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(
        uint256 value
    ) internal pure returns (uint216) {
        if (value > type(uint216).max) revert SafeCastOverflowedUintDowncast(216, value);
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(
        uint256 value
    ) internal pure returns (uint208) {
        if (value > type(uint208).max) revert SafeCastOverflowedUintDowncast(208, value);
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(
        uint256 value
    ) internal pure returns (uint200) {
        if (value > type(uint200).max) revert SafeCastOverflowedUintDowncast(200, value);
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(
        uint256 value
    ) internal pure returns (uint192) {
        if (value > type(uint192).max) revert SafeCastOverflowedUintDowncast(192, value);
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(
        uint256 value
    ) internal pure returns (uint184) {
        if (value > type(uint184).max) revert SafeCastOverflowedUintDowncast(184, value);
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(
        uint256 value
    ) internal pure returns (uint176) {
        if (value > type(uint176).max) revert SafeCastOverflowedUintDowncast(176, value);
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(
        uint256 value
    ) internal pure returns (uint168) {
        if (value > type(uint168).max) revert SafeCastOverflowedUintDowncast(168, value);
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(
        uint256 value
    ) internal pure returns (uint160) {
        if (value > type(uint160).max) revert SafeCastOverflowedUintDowncast(160, value);
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(
        uint256 value
    ) internal pure returns (uint152) {
        if (value > type(uint152).max) revert SafeCastOverflowedUintDowncast(152, value);
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(
        uint256 value
    ) internal pure returns (uint144) {
        if (value > type(uint144).max) revert SafeCastOverflowedUintDowncast(144, value);
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(
        uint256 value
    ) internal pure returns (uint136) {
        if (value > type(uint136).max) revert SafeCastOverflowedUintDowncast(136, value);
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(
        uint256 value
    ) internal pure returns (uint128) {
        if (value > type(uint128).max) revert SafeCastOverflowedUintDowncast(128, value);
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(
        uint256 value
    ) internal pure returns (uint120) {
        if (value > type(uint120).max) revert SafeCastOverflowedUintDowncast(120, value);
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(
        uint256 value
    ) internal pure returns (uint112) {
        if (value > type(uint112).max) revert SafeCastOverflowedUintDowncast(112, value);
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(
        uint256 value
    ) internal pure returns (uint104) {
        if (value > type(uint104).max) revert SafeCastOverflowedUintDowncast(104, value);
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(
        uint256 value
    ) internal pure returns (uint96) {
        if (value > type(uint96).max) revert SafeCastOverflowedUintDowncast(96, value);
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(
        uint256 value
    ) internal pure returns (uint88) {
        if (value > type(uint88).max) revert SafeCastOverflowedUintDowncast(88, value);
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(
        uint256 value
    ) internal pure returns (uint80) {
        if (value > type(uint80).max) revert SafeCastOverflowedUintDowncast(80, value);
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(
        uint256 value
    ) internal pure returns (uint72) {
        if (value > type(uint72).max) revert SafeCastOverflowedUintDowncast(72, value);
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(
        uint256 value
    ) internal pure returns (uint64) {
        if (value > type(uint64).max) revert SafeCastOverflowedUintDowncast(64, value);
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(
        uint256 value
    ) internal pure returns (uint56) {
        if (value > type(uint56).max) revert SafeCastOverflowedUintDowncast(56, value);
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(
        uint256 value
    ) internal pure returns (uint48) {
        if (value > type(uint48).max) revert SafeCastOverflowedUintDowncast(48, value);
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(
        uint256 value
    ) internal pure returns (uint40) {
        if (value > type(uint40).max) revert SafeCastOverflowedUintDowncast(40, value);
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(
        uint256 value
    ) internal pure returns (uint32) {
        if (value > type(uint32).max) revert SafeCastOverflowedUintDowncast(32, value);
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(
        uint256 value
    ) internal pure returns (uint24) {
        if (value > type(uint24).max) revert SafeCastOverflowedUintDowncast(24, value);
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(
        uint256 value
    ) internal pure returns (uint16) {
        if (value > type(uint16).max) revert SafeCastOverflowedUintDowncast(16, value);
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(
        uint256 value
    ) internal pure returns (uint8) {
        if (value > type(uint8).max) revert SafeCastOverflowedUintDowncast(8, value);
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(
        int256 value
    ) internal pure returns (uint256) {
        if (value < 0) revert SafeCastOverflowedIntToUint(value);
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(
        int256 value
    ) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(248, value);
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(
        int256 value
    ) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(240, value);
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(
        int256 value
    ) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(232, value);
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(
        int256 value
    ) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(224, value);
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(
        int256 value
    ) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(216, value);
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(
        int256 value
    ) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(208, value);
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(
        int256 value
    ) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(200, value);
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(
        int256 value
    ) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(192, value);
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(
        int256 value
    ) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(184, value);
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(
        int256 value
    ) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(176, value);
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(
        int256 value
    ) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(168, value);
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(
        int256 value
    ) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(160, value);
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(
        int256 value
    ) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(152, value);
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(
        int256 value
    ) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(144, value);
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(
        int256 value
    ) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(136, value);
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(
        int256 value
    ) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(128, value);
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(
        int256 value
    ) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(120, value);
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(
        int256 value
    ) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(112, value);
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(
        int256 value
    ) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(104, value);
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(
        int256 value
    ) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(96, value);
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(
        int256 value
    ) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(88, value);
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(
        int256 value
    ) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(80, value);
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(
        int256 value
    ) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(72, value);
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(
        int256 value
    ) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(64, value);
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(
        int256 value
    ) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(56, value);
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(
        int256 value
    ) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(48, value);
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(
        int256 value
    ) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(40, value);
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(
        int256 value
    ) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(32, value);
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(
        int256 value
    ) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(24, value);
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(
        int256 value
    ) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(16, value);
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(
        int256 value
    ) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) revert SafeCastOverflowedIntDowncast(8, value);
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(
        uint256 value
    ) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) revert SafeCastOverflowedUintToInt(value);
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(
        bool b
    ) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {

    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(
        Set storage set
    ) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(
        Set storage set
    ) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(
        Bytes32Set storage set
    ) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(
        Bytes32Set storage set
    ) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(
        AddressSet storage set
    ) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(
        AddressSet storage set
    ) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(
        UintSet storage set
    ) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(
        UintSet storage set
    ) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.0;

// ====================================================================
//             _        ______     ___   _______          _
//            / \     .' ___  |  .'   `.|_   __ \        / \
//           / _ \   / .'   \_| /  .-.  \ | |__) |      / _ \
//          / ___ \  | |   ____ | |   | | |  __ /      / ___ \
//        _/ /   \ \_\ `.___]  |\  `-'  /_| |  \ \_  _/ /   \ \_
//       |____| |____|`._____.'  `.___.'|____| |___||____| |____|
// ====================================================================
// ======================== AgoraAccessControl ========================
// ====================================================================

import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

/// @title AgoraAccessControl
/// @notice An abstract contract which contains role-ba
abstract contract AgoraAccessControl {

    using EnumerableSet for EnumerableSet.AddressSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;

    string public constant ACCESS_CONTROL_MANAGER_ROLE = "ACCESS_CONTROL_MANAGER_ROLE";

    /// @notice The AgoraAccessControlStorage struct
    /// @param roleData A mapping of role identifier to AgoraAccessControlRoleData to store role data
    /// @custom:storage-location erc7201:AgoraAccessControl.AgoraAccessControlStorage
    struct AgoraAccessControlStorage {
        EnumerableSet.Bytes32Set roles;
        mapping(string _role => EnumerableSet.AddressSet membership) roleMembership;
    }

    //==============================================================================
    // Initialization Functions
    //==============================================================================

    function _initializeAgoraAccessControl(
        address _initialAdminAddress
    ) internal {
        _addRoleToSet({ _role: ACCESS_CONTROL_MANAGER_ROLE });
        _setRoleMembership({
            _role: ACCESS_CONTROL_MANAGER_ROLE,
            _address: _initialAdminAddress,
            _insert: true
        });
        emit RoleAssigned({ role: ACCESS_CONTROL_MANAGER_ROLE, address_: _initialAdminAddress });
    }

    // ============================================================================================
    // Procedural Functions
    // ============================================================================================

    /// @notice The ```assignRole``` function assigns the designated role to an address
    /// @dev Must be called by the Admin
    /// @param _newAddress The address to be assigned the role
    function assignRole(string memory _role, address _newAddress, bool _addRole) public virtual {
        // Checks: Only Admin can transfer role
        _requireIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE, _address: msg.sender });

        _assignRole({ _role: _role, _newAddress: _newAddress, _addRole: _addRole });
        if (
            bytes(_role).length == bytes(ACCESS_CONTROL_MANAGER_ROLE).length
                && keccak256(bytes(_role)) == keccak256(bytes(ACCESS_CONTROL_MANAGER_ROLE))
                && _getPointerToAgoraAccessControlStorage().roleMembership[_role].length() == 0
        ) revert CannotRemoveLastManager();
    }

    function _assignRole(string memory _role, address _newAddress, bool _addRole) internal {
        // Effects: Add role to set, no-op if role already exists
        _addRoleToSet({ _role: _role });

        // Effects: Set the roleMembership to the new address
        _setRoleMembership({ _role: _role, _address: _newAddress, _insert: _addRole });

        // Emit event
        if (_addRole) emit RoleAssigned({ role: _role, address_: _newAddress });
        else emit RoleRevoked({ role: _role, address_: _newAddress });
    }

    // ============================================================================================
    // Internal Effects Functions
    // ============================================================================================

    function _addRoleToSet(
        string memory _role
    ) internal {
        // Checks: Role name must be shorter than 32 bytes
        if (bytes(_role).length > 32) revert RoleNameTooLong();
        _getPointerToAgoraAccessControlStorage().roles.add(bytes32(bytes(_role)));
    }

    function _removeRoleFromSet(
        string memory _role
    ) internal {
        _getPointerToAgoraAccessControlStorage().roles.remove(bytes32(bytes(_role)));
    }

    /// @notice The ```_setRole``` function sets the role address
    /// @dev This function is to be implemented by a public function
    /// @param _role The role identifier to transfer
    /// @param _address The address of the new role
    /// @param _insert Whether to add or remove the address from the role
    function _setRoleMembership(string memory _role, address _address, bool _insert) internal {
        if (_insert) _getPointerToAgoraAccessControlStorage().roleMembership[_role].add(_address);
        else _getPointerToAgoraAccessControlStorage().roleMembership[_role].remove(_address);
    }

    // ============================================================================================
    // Internal Checks Functions
    // ============================================================================================

    /// @notice The ```_isRole``` function checks if _address is current role address
    /// @param _role The role identifier to check
    /// @param _address The address to check against the role
    /// @return Whether or not msg.sender is current role address
    function _isRole(string memory _role, address _address) internal view returns (bool) {
        return _getPointerToAgoraAccessControlStorage().roleMembership[_role].contains(_address);
    }

    /// @notice The ```_requireIsRole``` function reverts if _address is not current role address
    /// @param _role The role identifier to check
    /// @param _address The address to check against the role
    function _requireIsRole(string memory _role, address _address) internal view {
        if (!_isRole({ _role: _role, _address: _address })) {
            revert AddressIsNotRole({ role: _role });
        }
    }

    /// @notice The ```_requireSenderIsRole``` function reverts if msg.sender is not current role address
    /// @dev This function is to be implemented by a public function
    /// @param _role The role identifier to check
    function _requireSenderIsRole(
        string memory _role
    ) internal view {
        _requireIsRole({ _role: _role, _address: msg.sender });
    }

    //==============================================================================
    // External View Functions
    //==============================================================================

    /// @notice The ```hasRole``` function checks if _address has the role
    /// @param _role The role identifier to check
    /// @param _address The address to check against the role
    /// @return Whether or not _address has the role
    function hasRole(string memory _role, address _address) external view returns (bool) {
        return _isRole({ _role: _role, _address: _address });
    }

    /// @notice The ```getRoleMembers``` function returns the members of the role
    /// @param _role The role identifier to check
    /// @return _members The members of the role
    function getRoleMembers(
        string memory _role
    ) external view returns (address[] memory _members) {
        EnumerableSet.AddressSet storage _roleMembership =
            _getPointerToAgoraAccessControlStorage().roleMembership[_role];
        _members = _roleMembership.values();
    }

    /// @notice The ```getAllRoles``` function returns all roles
    /// @return _roles The roles
    function getAllRoles() external view returns (string[] memory _roles) {
        uint256 _length = _getPointerToAgoraAccessControlStorage().roles.length();
        _roles = new string[](_length);
        for (uint256 i = 0; i < _length; i++) {
            _roles[i] =
                string(abi.encodePacked(_getPointerToAgoraAccessControlStorage().roles.at(i)));
        }
    }

    //==============================================================================
    // Erc 7201: UnstructuredNamespace Storage Functions
    //==============================================================================

    /// @notice The ```AGORA_ACCESS_CONTROL_STORAGE_SLOT``` is the storage slot for the AgoraAccessControlStorage struct
    /// @dev keccak256(abi.encode(uint256(keccak256("AgoraAccessControlStorage")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 public constant AGORA_ACCESS_CONTROL_STORAGE_SLOT =
        0x8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b000;

    /// @notice The ```_getPointerToAgoraAccessControlStorage``` function returns a pointer to the AgoraAccessControlStorage struct
    /// @return $ A pointer to the AgoraAccessControlStorage struct
    function _getPointerToAgoraAccessControlStorage()
        internal
        pure
        returns (AgoraAccessControlStorage storage $)
    {
        /// @solidity memory-safe-assembly
        assembly {
            $.slot := AGORA_ACCESS_CONTROL_STORAGE_SLOT
        }
    }

    // ============================================================================================
    // Events
    // ============================================================================================

    /// @notice The ```RoleAssigned``` event is emitted when the role is assigned
    /// @param role The string identifier of the role that was transferred
    /// @param address_ The address of the new role
    event RoleAssigned(string indexed role, address indexed address_);

    /// @notice The ```RoleRevoked``` event is emitted when the role is revoked
    /// @param role The string identifier of the role that was transferred
    event RoleRevoked(string indexed role, address indexed address_);

    // ============================================================================================
    // Errors
    // ============================================================================================

    /// @notice Emitted when role is transferred
    /// @param role The role identifier
    error AddressIsNotRole(string role);

    /// @notice Emitted when role name is too long
    error RoleNameTooLong();

    /// @notice Emitted when the last manager is removed via the public ```assignRole``` function
    /// @dev Manager role can be revoked by using the internal ```_assignRole``` function
    error CannotRemoveLastManager();

}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

// ====================================================================
//             _        ______     ___   _______          _
//            / \     .' ___  |  .'   `.|_   __ \        / \
//           / _ \   / .'   \_| /  .-.  \ | |__) |      / _ \
//          / ___ \  | |   ____ | |   | | |  __ /      / ___ \
//        _/ /   \ \_\ `.___]  |\  `-'  /_| |  \ \_  _/ /   \ \_
//       |____| |____|`._____.'  `.___.'|____| |___||____| |____|
// ====================================================================
// ====================== AgoraStableSwapPair =========================
// ====================================================================

import { AgoraStableSwapPairConfiguration } from "./AgoraStableSwapPairConfiguration.sol";

import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";

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

/// @notice The ```InitializeParams``` struct is used to initialize the AgoraStableSwapPair
/// @param token0 The address of token0
/// @param token0Decimals The number of decimals for token0
/// @param token1 The address of token1
/// @param token1Decimals The number of decimals for token1
/// @param minToken0PurchaseFee The minimum purchase fee for token0, 18 decimals precision, max value 1
/// @param maxToken0PurchaseFee The maximum purchase fee for token0, 18 decimals precision, max value 1
/// @param minToken1PurchaseFee The minimum purchase fee for token1, 18 decimals precision, max value 1
/// @param maxToken1PurchaseFee The maximum purchase fee for token1, 18 decimals precision, max value 1
/// @param token0PurchaseFee The purchase fee for token0, 18 decimals precision, max value 1
/// @param token1PurchaseFee The purchase fee for token1, 18 decimals precision, max value 1
/// @param initialAdminAddress The address of the initial admin
/// @param initialWhitelister The address of the initial whitelister
/// @param initialFeeSetter The address of the initial fee setter
/// @param initialTokenRemover The address of the initial token remover
/// @param initialPauser The address of the initial pauser
/// @param initialPriceSetter The address of the initial price setter
/// @param initialTokenReceiver The address of the initial token receiver
/// @param initialFeeReceiver The address of the initial fee receiver
/// @param minBasePrice The minimum base price for the pair, 18 decimals precision, min/max value determined by difference between decimals of token0 and token1
/// @param maxBasePrice The maximum base price for the pair, 18 decimals precision, min/max value determined by difference between decimals of token0 and token1
/// @param minAnnualizedInterestRate The minimum annualized interest rate for the pair, 18 decimals precision, given as number i.e. 1e16 = 1%
/// @param maxAnnualizedInterestRate The maximum annualized interest rate for the pair, 18 decimals precision, given as number i.e. 1e16 = 1%
/// @param basePrice The base price for the pair, 18 decimals precision, limited by token0 and token1 decimals
/// @param annualizedInterestRate The annualized interest rate for the pair, 18 decimals precision, given as number i.e. 1e16 = 1%
struct InitializeParams {
    address token0;
    uint8 token0Decimals;
    address token1;
    uint8 token1Decimals;
    uint256 minToken0PurchaseFee;
    uint256 maxToken0PurchaseFee;
    uint256 minToken1PurchaseFee;
    uint256 maxToken1PurchaseFee;
    uint256 token0PurchaseFee;
    uint256 token1PurchaseFee;
    address initialAdminAddress;
    address initialWhitelister;
    address initialFeeSetter;
    address initialTokenRemover;
    address initialPauser;
    address initialPriceSetter;
    address initialTokenReceiver;
    address initialFeeReceiver;
    uint256 minBasePrice;
    uint256 maxBasePrice;
    int256 minAnnualizedInterestRate;
    int256 maxAnnualizedInterestRate;
    uint256 basePrice;
    int256 annualizedInterestRate;
}

/// @title AgoraStableSwapPair
/// @notice The AgoraStableSwapPair allows whitelisted users to swap between two tokens with a fixed price
/// @author Agora
contract AgoraStableSwapPair is AgoraStableSwapPairConfiguration {
    using SafeCast for uint256;
    using Strings for uint256;

    //==============================================================================
    // Constructor & Initalization Functions
    //==============================================================================

    constructor() {
        _disableInitializers();
    }

    /// @notice The ```initialize``` function initializes the AgoraStableSwapPair contract
    /// @param _params The parameters for the initialization
    function initialize(InitializeParams memory _params) external reinitializer(3) {
        // Check decimals match decimals of token0 and token1
        if (_params.token0Decimals != IERC20Metadata(_params.token0).decimals()) revert IncorrectDecimals();
        if (_params.token1Decimals != IERC20Metadata(_params.token1).decimals()) revert IncorrectDecimals();

        // Set the token0 and token1 and decimals
        _getPointerToStorage().swapStorage.token0 = _params.token0;
        _getPointerToStorage().configStorage.token0Decimals = _params.token0Decimals;
        _getPointerToStorage().swapStorage.token1 = _params.token1;
        _getPointerToStorage().configStorage.token1Decimals = _params.token1Decimals;

        // assign roles to deployer for initialization
        _assignRole({ _role: ACCESS_CONTROL_MANAGER_ROLE, _newAddress: msg.sender, _addRole: true });
        _assignRole({ _role: PRICE_SETTER_ROLE, _newAddress: msg.sender, _addRole: true });
        _assignRole({ _role: FEE_SETTER_ROLE, _newAddress: msg.sender, _addRole: true });

        // Set the tokenReceiverAddress
        setTokenReceiver({ _tokenReceiver: _params.initialTokenReceiver });

        // Set the feeReceiver address
        setFeeReceiver({ _feeReceiver: _params.initialFeeReceiver });

        // Set the fee bounds
        setFeeBounds({
            _minToken0PurchaseFee: _params.minToken0PurchaseFee,
            _maxToken0PurchaseFee: _params.maxToken0PurchaseFee,
            _minToken1PurchaseFee: _params.minToken1PurchaseFee,
            _maxToken1PurchaseFee: _params.maxToken1PurchaseFee
        });

        // Set the token0to1Fee and token1to0Fee
        setTokenPurchaseFees({
            _token0PurchaseFee: _params.token0PurchaseFee,
            _token1PurchaseFee: _params.token1PurchaseFee
        });

        // Configure oracle price bounds
        setOraclePriceBounds({
            _minBasePrice: _params.minBasePrice,
            _maxBasePrice: _params.maxBasePrice,
            _minAnnualizedInterestRate: _params.minAnnualizedInterestRate,
            _maxAnnualizedInterestRate: _params.maxAnnualizedInterestRate
        });

        // Configure the oracle price
        configureOraclePrice({
            _basePrice: _params.basePrice,
            _annualizedInterestRate: _params.annualizedInterestRate,
            _deadline: block.timestamp
        });

        // Remove privileges from deployer
        _assignRole({ _role: PRICE_SETTER_ROLE, _newAddress: msg.sender, _addRole: false });
        _assignRole({ _role: FEE_SETTER_ROLE, _newAddress: msg.sender, _addRole: false });

        // Initialize the access control and oracle
        _initializeAgoraStableSwapAccessControl({
            _initialAdminAddress: _params.initialAdminAddress,
            _initialWhitelister: _params.initialWhitelister,
            _initialFeeSetter: _params.initialFeeSetter,
            _initialTokenRemover: _params.initialTokenRemover,
            _initialPauser: _params.initialPauser,
            _initialPriceSetter: _params.initialPriceSetter
        });

        // Remove privileges from deployer
        if (_params.initialAdminAddress != msg.sender) {
            _assignRole({ _role: ACCESS_CONTROL_MANAGER_ROLE, _newAddress: msg.sender, _addRole: false });
        }
        sync();
    }

    //==============================================================================
    //  SwapStorage View Functions
    //==============================================================================

    /// @notice The ```name``` function returns the name of the pair
    /// @return _name The name of the pair
    function name() public view returns (string memory) {
        address _token0 = token0();
        address _token1 = token1();
        return string(abi.encodePacked(IERC20Metadata(_token0).symbol(), "/", IERC20Metadata(_token1).symbol()));
    }

    /// @notice The ```isPaused``` function returns whether the pair is paused
    /// @return _isPaused Whether the pair is paused
    function isPaused() public view returns (bool) {
        return _getPointerToStorage().swapStorage.isPaused;
    }

    /// @notice The ```token0``` function returns the address of the token0 in the pair
    /// @return _token0 The address of the token0 in the pair
    function token0() public view returns (address) {
        return _getPointerToStorage().swapStorage.token0;
    }

    /// @notice The ```token1``` function returns the address of the token1 in the pair
    /// @return _token1 The address of the token1 in the pair
    function token1() public view returns (address) {
        return _getPointerToStorage().swapStorage.token1;
    }

    /// @notice The ```reserve0``` function returns the reserve of the token0 in the pair
    /// @return _reserve0 The reserve of the token0 in the pair
    function reserve0() public view returns (uint256) {
        return _getPointerToStorage().swapStorage.reserve0;
    }

    /// @notice The ```reserve1``` function returns the reserve of the token1 in the pair
    /// @return _reserve1 The reserve of the token1 in the pair
    function reserve1() public view returns (uint256) {
        return _getPointerToStorage().swapStorage.reserve1;
    }

    /// @notice The ```token0PurchaseFee``` function returns the purchase fee for the token0 in the pair
    /// @return _token0PurchaseFee The purchase fee for the token0 in the pair
    function token0PurchaseFee() public view returns (uint256) {
        return _getPointerToStorage().swapStorage.token0PurchaseFee;
    }

    /// @notice The ```token1PurchaseFee``` function returns the purchase fee for the token1 in the pair
    /// @return _token1PurchaseFee The purchase fee for the token1 in the pair
    function token1PurchaseFee() public view returns (uint256) {
        return _getPointerToStorage().swapStorage.token1PurchaseFee;
    }

    /// @notice The ```priceLastUpdated``` function returns the timestamp when the price was updated
    /// @return _priceLastUpdated The timestamp when the price was updated
    function priceLastUpdated() public view returns (uint256) {
        return _getPointerToStorage().swapStorage.priceLastUpdated;
    }

    /// @notice The ```perSecondInterestRate``` function returns the per second interest rate
    /// @return _perSecondInterestRate The per second interest rate
    function perSecondInterestRate() public view returns (int256) {
        return _getPointerToStorage().swapStorage.perSecondInterestRate;
    }

    /// @notice The ```basePrice``` function returns the base price
    /// @return _basePrice The base price
    function basePrice() public view returns (uint256) {
        return _getPointerToStorage().swapStorage.basePrice;
    }

    /// @notice The ```token0FeesAccumulated``` function returns the accumulated fees for token0
    /// @return _token0FeesAccumulated The accumulated fees for token0
    function token0FeesAccumulated() public view returns (uint256) {
        return _getPointerToStorage().swapStorage.token0FeesAccumulated;
    }

    /// @notice The ```token1FeesAccumulated``` function returns the accumulated fees for token1
    /// @return _token1FeesAccumulated The accumulated fees for token1
    function token1FeesAccumulated() public view returns (uint256) {
        return _getPointerToStorage().swapStorage.token1FeesAccumulated;
    }

    //==============================================================================
    //  ConfigStorage View Functions
    //==============================================================================

    /// @notice The ```minToken0PurchaseFee``` function returns the minimum purchase fee for token0
    /// @return _minToken0PurchaseFee The minimum purchase fee for token0
    function minToken0PurchaseFee() public view returns (uint256) {
        return _getPointerToStorage().configStorage.minToken0PurchaseFee;
    }

    /// @notice The ```maxToken0PurchaseFee``` function returns the maximum purchase fee for token0
    /// @return _maxToken0PurchaseFee The maximum purchase fee for token0
    function maxToken0PurchaseFee() public view returns (uint256) {
        return _getPointerToStorage().configStorage.maxToken0PurchaseFee;
    }

    /// @notice The ```minToken1PurchaseFee``` function returns the minimum purchase fee for token1
    /// @return _minToken1PurchaseFee The minimum purchase fee for token1
    function minToken1PurchaseFee() public view returns (uint256) {
        return _getPointerToStorage().configStorage.minToken1PurchaseFee;
    }

    /// @notice The ```maxToken1PurchaseFee``` function returns the maximum purchase fee for token1
    /// @return _maxToken1PurchaseFee The maximum purchase fee for token1
    function maxToken1PurchaseFee() public view returns (uint256) {
        return _getPointerToStorage().configStorage.maxToken1PurchaseFee;
    }

    /// @notice The ```tokenReceiverAddress``` function returns the address of the token receiver
    /// @return _tokenReceiverAddress The address of the token receiver
    function tokenReceiverAddress() public view returns (address) {
        return _getPointerToStorage().configStorage.tokenReceiverAddress;
    }

    /// @notice The ```feeReceiverAddress``` function returns the address of the fee receiver
    /// @return _feeReceiverAddress The address of the fee receiver
    function feeReceiverAddress() public view returns (address) {
        return _getPointerToStorage().configStorage.feeReceiverAddress;
    }

    /// @notice The ```minBasePrice``` function returns the minimum base price
    /// @return _minBasePrice The minimum base price
    function minBasePrice() public view returns (uint256) {
        return _getPointerToStorage().configStorage.minBasePrice;
    }

    /// @notice The ```maxBasePrice``` function returns the maximum base price
    /// @return _maxBasePrice The maximum base price
    function maxBasePrice() public view returns (uint256) {
        return _getPointerToStorage().configStorage.maxBasePrice;
    }

    /// @notice The ```minAnnualizedInterestRate``` function returns the minimum annualized interest rate
    /// @return _minAnnualizedInterestRate The minimum annualized interest rate
    function minAnnualizedInterestRate() public view returns (int256) {
        return _getPointerToStorage().configStorage.minAnnualizedInterestRate;
    }

    /// @notice The ```maxAnnualizedInterestRate``` function returns the maximum annualized interest rate
    /// @return _maxAnnualizedInterestRate The maximum annualized interest rate
    function maxAnnualizedInterestRate() public view returns (int256) {
        return _getPointerToStorage().configStorage.maxAnnualizedInterestRate;
    }

    /// @notice The ```token0Decimals``` function returns the decimals of the token0 in the pair
    /// @return _token0Decimals The decimals of the token0 in the pair
    function token0Decimals() public view returns (uint8) {
        return _getPointerToStorage().configStorage.token0Decimals;
    }

    /// @notice The ```token1Decimals``` function returns the decimals of the token1 in the pair
    /// @return _token1Decimals The decimals of the token1 in the pair
    function token1Decimals() public view returns (uint8) {
        return _getPointerToStorage().configStorage.token1Decimals;
    }

    //==============================================================================
    // View Functions
    //==============================================================================

    /// @notice The ```getAmountsOut``` function calculates the amount of tokenOut returned from a given amount of tokenIn
    /// @param _amountIn The amount of input tokenIn
    /// @param _path The path of the tokens
    /// @return _amounts The amounts of requested tokenIn and calculated tokenOut
    function getAmountsOut(uint256 _amountIn, address[] memory _path) public view returns (uint256[] memory _amounts) {
        SwapStorage memory _swapStorage = _getPointerToStorage().swapStorage;
        uint256 _token0OverToken1Price = getPrice();

        // Checks: path length is 2 && path must contain token0 and token1 only
        requireValidPath({ _path: _path, _token0: _swapStorage.token0, _token1: _swapStorage.token1 });

        // Checks: amountIn is greater than 0
        if (_amountIn == 0) revert InsufficientInputAmount();

        // instantiate return variables
        _amounts = new uint256[](2);
        _amounts[0] = _amountIn;

        // path[1] represents our tokenOut
        if (_path[1] == _swapStorage.token0) {
            uint256 _token0PurchaseFeeAmount;
            (_amounts[1], _token0PurchaseFeeAmount) = getAmount0Out({
                _amount1In: _amountIn,
                _token0OverToken1Price: _token0OverToken1Price,
                _token0PurchaseFee: _swapStorage.token0PurchaseFee
            });
            if (_amounts[1] + _token0PurchaseFeeAmount > _swapStorage.reserve0) revert InsufficientLiquidity();
        } else {
            uint256 _token1PurchaseFeeAmount;
            (_amounts[1], _token1PurchaseFeeAmount) = getAmount1Out({
                _amount0In: _amountIn,
                _token0OverToken1Price: _token0OverToken1Price,
                _token1PurchaseFee: _swapStorage.token1PurchaseFee
            });
            if (_amounts[1] + _token1PurchaseFeeAmount > _swapStorage.reserve1) revert InsufficientLiquidity();
        }
    }

    /// @notice The ```getAmountsIn``` function calculates the amount of input tokensIn required for a given amount tokensOut
    /// @param _amountOut The amount of output tokenOut
    /// @param _path The path of the tokens
    /// @return _amounts The amounts of calculated tokenIn and requested tokenOut
    function getAmountsIn(uint256 _amountOut, address[] memory _path) public view returns (uint256[] memory _amounts) {
        SwapStorage memory _swapStorage = _getPointerToStorage().swapStorage;
        uint256 _token0OverToken1Price = getPrice();

        // Checks: path length is 2 && path must contain token0 and token1 only
        requireValidPath({ _path: _path, _token0: _swapStorage.token0, _token1: _swapStorage.token1 });

        // Checks: amountOut is greater than 0
        if (_amountOut == 0) revert InsufficientOutputAmount();

        // instantiate return variables
        _amounts = new uint256[](2);
        // set the amountOut
        _amounts[1] = _amountOut;

        // path[0] represents our tokenIn
        if (_path[0] == _swapStorage.token0) {
            uint256 _token1PurchaseFeeAmount;
            (_amounts[0], _token1PurchaseFeeAmount) = getAmount0In({
                _amount1Out: _amountOut,
                _token0OverToken1Price: _token0OverToken1Price,
                _token1PurchaseFee: _swapStorage.token1PurchaseFee
            });
            if (_amountOut + _token1PurchaseFeeAmount > _swapStorage.reserve1) revert InsufficientLiquidity();
        } else {
            uint256 _token0PurchaseFeeAmount;
            (_amounts[0], _token0PurchaseFeeAmount) = getAmount1In({
                _amount0Out: _amountOut,
                _token0OverToken1Price: _token0OverToken1Price,
                _token0PurchaseFee: _swapStorage.token0PurchaseFee
            });
            if (_amountOut + _token0PurchaseFeeAmount > _swapStorage.reserve0) revert InsufficientLiquidity();
        }
    }

    /// @notice The ```getPriceNormalized``` function returns a price in a human-readable format adjusting for differences in precision
    /// @return _normalizedPrice The normalized price with 18 decimals of precision
    function getPriceNormalized() external view returns (uint256 _normalizedPrice) {
        ConfigStorage memory _configStorage = _getPointerToStorage().configStorage;
        return (getPrice() * 10 ** _configStorage.token1Decimals) / 10 ** _configStorage.token0Decimals;
    }

    /// @notice The ```Version``` struct is used to represent the version of the AgoraStableSwapPair
    /// @param major The major version number
    /// @param minor The minor version number
    /// @param patch The patch version number
    struct Version {
        uint256 major;
        uint256 minor;
        uint256 patch;
    }

    /// @notice The ```version``` function returns the version of the AgoraStableSwapPair
    /// @return _version The version of the AgoraStableSwapPair
    function version() public pure returns (Version memory _version) {
        _version = Version({ major: 2, minor: 1, patch: 0 });
    }
}

// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.8.0;

// ====================================================================
//             _        ______     ___   _______          _
//            / \     .' ___  |  .'   `.|_   __ \        / \
//           / _ \   / .'   \_| /  .-.  \ | |__) |      / _ \
//          / ___ \  | |   ____ | |   | | |  __ /      / ___ \
//        _/ /   \ \_\ `.___]  |\  `-'  /_| |  \ \_  _/ /   \ \_
//       |____| |____|`._____.'  `.___.'|____| |___||____| |____|
// ====================================================================
// ================= AgoraTransparentUpgradeableProxy =================
// ====================================================================

import { ERC1967Utils } from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import { Proxy } from "@openzeppelin/contracts/proxy/Proxy.sol";
import { ITransparentUpgradeableProxy } from
    "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";

struct ConstructorParams {
    address logic;
    address proxyAdminAddress;
    bytes data;
}

contract AgoraTransparentUpgradeableProxy is Proxy {

    address private _admin;

    /**
     * @dev The proxy caller is the current admin, and can't fallback to the proxy target.
     */
    error ProxyDeniedAdminAccess();

    /**
     * @dev Initializes an upgradeable proxy managed by an instance of a {AgoraProxyAdmin} with an `initialOwner`,
     * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in
     * {ERC1967Proxy-constructor}.
     */
    constructor(
        ConstructorParams memory _params
    ) payable {
        _admin = _params.proxyAdminAddress;
        // Set the storage value and emit an event for ERC-1967 compatibility
        ERC1967Utils.changeAdmin(_admin);
        if (_params.logic != address(0)) ERC1967Utils.upgradeToAndCall(_params.logic, _params.data);
    }

    /**
     * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.
     */
    function _fallback() internal virtual override {
        if (msg.sender == _admin) {
            if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
                revert ProxyDeniedAdminAccess();
            } else {
                (address newImplementation, bytes memory data) =
                    abi.decode(msg.data[4:], (address, bytes));
                ERC1967Utils.upgradeToAndCall(newImplementation, data);
            }
        } else {
            super._fallback();
        }
    }

    function _implementation() internal view virtual override returns (address) {
        return ERC1967Utils.getImplementation();
    }

}

// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.8.0;

// ====================================================================
//             _        ______     ___   _______          _
//            / \     .' ___  |  .'   `.|_   __ \        / \
//           / _ \   / .'   \_| /  .-.  \ | |__) |      / _ \
//          / ___ \  | |   ____ | |   | | |  __ /      / ___ \
//        _/ /   \ \_\ `.___]  |\  `-'  /_| |  \ \_  _/ /   \ \_
//       |____| |____|`._____.'  `.___.'|____| |___||____| |____|
// ====================================================================
// ====================== Erc1967Implementation =======================
// ====================================================================

/// @title Erc1967Implementation
/// @notice The Erc1967Implementation is a contract that provides visibility into the Erc1967Implementation and its associated storage slots.
/// @author Agora
abstract contract Erc1967Implementation {

    //==============================================================================
    // Erc1967 Admin Slot Items
    //==============================================================================

    /// @notice The Erc1967ProxyAdminStorage struct
    /// @param proxyAdminAddress The address of the proxy admin contract
    /// @custom:storage-location erc1967:eip1967.proxy.admin
    struct Erc1967ProxyAdminStorage {
        address proxyAdminAddress;
    }

    /// @notice The ```ERC1967_PROXY_ADMIN_STORAGE_SLOT_``` is the storage slot for the Erc1967ProxyAdminStorage struct
    /// @dev NOTE: deviates from erc7201 standard because erc1967 defines its own storage slot algorithm
    /// @dev bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)
    bytes32 internal constant ERC1967_PROXY_ADMIN_STORAGE_SLOT_ =
        0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /// @notice The ```getPointerToErc1967ProxyAdminStorage``` function returns a pointer to the Erc1967ProxyAdminStorage struct
    /// @return adminSlot A pointer to the Erc1967ProxyAdminStorage struct
    function getPointerToErc1967ProxyAdminStorage()
        internal
        pure
        returns (Erc1967ProxyAdminStorage storage adminSlot)
    {
        /// @solidity memory-safe-assembly
        assembly {
            adminSlot.slot := ERC1967_PROXY_ADMIN_STORAGE_SLOT_
        }
    }

    /// @notice The ```proxyAdminAddress``` function returns the address of the proxy admin
    /// @return The address of the proxy admin
    function proxyAdminAddress() external view returns (address) {
        return getPointerToErc1967ProxyAdminStorage().proxyAdminAddress;
    }

    //==============================================================================
    // EIP1967 Proxy Implementation Slot Items
    //==============================================================================

    /// @notice The Erc1967ProxyContractStorage struct
    /// @param implementationAddress The address of the implementation contract
    /// @custom:storage-location erc1967:eip1967.proxy.implementation
    struct Erc1967ProxyContractStorage {
        address implementationAddress;
    }

    /// @notice The ```ERC1967_IMPLEMENTATION_CONTRACT_STORAGE_SLOT_``` is the storage slot for the implementation contract
    /// @dev bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)
    bytes32 internal constant ERC1967_IMPLEMENTATION_CONTRACT_STORAGE_SLOT_ =
        0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /// @notice The ```getPointerToImplementationStorage``` function returns a pointer to the Erc1967ProxyContractStorage struct
    /// @return implementationSlot A pointer to the Erc1967ProxyContractStorage struct
    function getPointerToImplementationStorage()
        internal
        pure
        returns (Erc1967ProxyContractStorage storage implementationSlot)
    {
        /// @solidity memory-safe-assembly
        assembly {
            implementationSlot.slot := ERC1967_IMPLEMENTATION_CONTRACT_STORAGE_SLOT_
        }
    }

    /// @notice The ```implementationAddress``` function returns the address of the implementation contract
    /// @return The address of the implementation contract
    function implementationAddress() external view returns (address) {
        return getPointerToImplementationStorage().implementationAddress;
    }

}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.4;

/**
 * @title CreateX Factory Interface Definition
 * @author pcaversaccio (https://web.archive.org/web/20230921103111/https://pcaversaccio.com/)
 * @custom:coauthor Matt Solomon (https://web.archive.org/web/20230921103335/https://mattsolomon.dev/)
 */
interface ICreateX {

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                            TYPES                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    struct Values {
        uint256 constructorAmount;
        uint256 initCallAmount;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    event ContractCreation(address indexed newContract, bytes32 indexed salt);
    event ContractCreation(address indexed newContract);
    event Create3ProxyContractCreation(address indexed newContract, bytes32 indexed salt);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                        CUSTOM ERRORS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    error FailedContractCreation(address emitter);
    error FailedContractInitialisation(address emitter, bytes revertData);
    error InvalidSalt(address emitter);
    error InvalidNonceValue(address emitter);
    error FailedEtherTransfer(address emitter, bytes revertData);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           CREATE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function deployCreate(
        bytes memory initCode
    ) external payable returns (address newContract);

    function deployCreateAndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values,
        address refundAddress
    ) external payable returns (address newContract);

    function deployCreateAndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values
    ) external payable returns (address newContract);

    function deployCreateClone(
        address implementation,
        bytes memory data
    ) external payable returns (address proxy);

    function computeCreateAddress(
        address deployer,
        uint256 nonce
    ) external view returns (address computedAddress);

    function computeCreateAddress(
        uint256 nonce
    ) external view returns (address computedAddress);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           CREATE2                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function deployCreate2(
        bytes32 salt,
        bytes memory initCode
    ) external payable returns (address newContract);

    function deployCreate2(
        bytes memory initCode
    ) external payable returns (address newContract);

    function deployCreate2AndInit(
        bytes32 salt,
        bytes memory initCode,
        bytes memory data,
        Values memory values,
        address refundAddress
    ) external payable returns (address newContract);

    function deployCreate2AndInit(
        bytes32 salt,
        bytes memory initCode,
        bytes memory data,
        Values memory values
    ) external payable returns (address newContract);

    function deployCreate2AndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values,
        address refundAddress
    ) external payable returns (address newContract);

    function deployCreate2AndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values
    ) external payable returns (address newContract);

    function deployCreate2Clone(
        bytes32 salt,
        address implementation,
        bytes memory data
    ) external payable returns (address proxy);

    function deployCreate2Clone(
        address implementation,
        bytes memory data
    ) external payable returns (address proxy);

    function computeCreate2Address(
        bytes32 salt,
        bytes32 initCodeHash,
        address deployer
    ) external pure returns (address computedAddress);

    function computeCreate2Address(
        bytes32 salt,
        bytes32 initCodeHash
    ) external view returns (address computedAddress);

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           CREATE3                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    function deployCreate3(
        bytes32 salt,
        bytes memory initCode
    ) external payable returns (address newContract);

    function deployCreate3(
        bytes memory initCode
    ) external payable returns (address newContract);

    function deployCreate3AndInit(
        bytes32 salt,
        bytes memory initCode,
        bytes memory data,
        Values memory values,
        address refundAddress
    ) external payable returns (address newContract);

    function deployCreate3AndInit(
        bytes32 salt,
        bytes memory initCode,
        bytes memory data,
        Values memory values
    ) external payable returns (address newContract);

    function deployCreate3AndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values,
        address refundAddress
    ) external payable returns (address newContract);

    function deployCreate3AndInit(
        bytes memory initCode,
        bytes memory data,
        Values memory values
    ) external payable returns (address newContract);

    function computeCreate3Address(
        bytes32 salt,
        address deployer
    ) external pure returns (address computedAddress);

    function computeCreate3Address(
        bytes32 salt
    ) external view returns (address computedAddress);

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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.1.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import { Panic } from "../Panic.sol";
import { SafeCast } from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero

    }

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= prod1) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        return mulDiv(x, y, denominator)
            + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) Panic.panic(Panic.DIVISION_BY_ZERO);
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(
        uint256 b,
        uint256 e,
        uint256 m
    ) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) Panic.panic(Panic.DIVISION_BY_ZERO);
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(
        bytes memory byteArray
    ) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) return false;
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(
        uint256 a
    ) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) return a;

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) xn <<= 1;

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(
        uint256 value
    ) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 1);
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(
        uint256 value
    ) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) result += 1;
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(
        uint256 value
    ) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return
                result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(
        Rounding rounding
    ) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

import { SafeCast } from "./SafeCast.sol";

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(
        int256 n
    ) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }

}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

// ====================================================================
//             _        ______     ___   _______          _
//            / \     .' ___  |  .'   `.|_   __ \        / \
//           / _ \   / .'   \_| /  .-.  \ | |__) |      / _ \
//          / ___ \  | |   ____ | |   | | |  __ /      / ___ \
//        _/ /   \ \_\ `.___]  |\  `-'  /_| |  \ \_  _/ /   \ \_
//       |____| |____|`._____.'  `.___.'|____| |___||____| |____|
// ====================================================================
// ================ AgoraStableSwapPairConfiguration ===================
// ====================================================================

import { AgoraStableSwapPairCore } from "./AgoraStableSwapPairCore.sol";

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";

/// @title AgoraStableSwapPairConfiguration
/// @notice The AgoraStableSwapPairConfiguration is a contract that manages the privileged configuration setters for the AgoraStableSwapPair
/// @author Agora
abstract contract AgoraStableSwapPairConfiguration is AgoraStableSwapPairCore {
    using SafeCast for *;
    using SafeERC20 for IERC20;

    //==============================================================================
    // Privileged Configuration Functions
    //==============================================================================

    /// @notice The ```setTokenReceiver``` function sets the token receiver
    /// @dev Only the access control manager can set the token receiver
    /// @param _tokenReceiver The address of the token receiver
    function setTokenReceiver(address _tokenReceiver) public {
        // Checks: Only the access control manager can set the token receiver
        _requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });

        // Effects: Set the token receiver
        _getPointerToStorage().configStorage.tokenReceiverAddress = _tokenReceiver;

        // emit event
        emit SetTokenReceiver({ tokenReceiver: _tokenReceiver });
    }

    /// @notice The ```setFeeReceiver``` function sets the fee receiver
    /// @dev Only the access control manager can set the fee receiver
    /// @param _feeReceiver The address of the fee receiver
    function setFeeReceiver(address _feeReceiver) public {
        // Checks: Only the access control manager can set the fee receiver
        _requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });

        // Effects: Set the fee receiver
        _getPointerToStorage().configStorage.feeReceiverAddress = _feeReceiver;

        // emit event
        emit SetFeeReceiver({ feeReceiver: _feeReceiver });
    }

    /// @notice The ```setApprovedSwapper``` function sets the approved swappers
    /// @dev Only the whitelister can set the approved swappers
    /// @param _approvedSwappers The addresses of the approved swappers
    /// @param _setApproved The boolean value indicating whether the swappers are approved
    function setApprovedSwappers(address[] memory _approvedSwappers, bool _setApproved) public {
        // Checks: Only the whitelister can set the approved swapper
        _requireSenderIsRole({ _role: WHITELISTER_ROLE });

        for (uint256 _i = 0; _i < _approvedSwappers.length; _i++) {
            // Effects: Set the isApproved state
            _assignRole({ _role: APPROVED_SWAPPER, _newAddress: _approvedSwappers[_i], _addRole: _setApproved });

            // emit event
            emit SetApprovedSwapper({ approvedSwapper: _approvedSwappers[_i], isApproved: _setApproved });
        }
    }

    /// @notice The ```setFeeBounds``` function sets the fee bounds
    /// @dev Only the access control manager can set the fee bounds
    /// @param _minToken0PurchaseFee The minimum purchase fee for token0
    /// @param _maxToken0PurchaseFee The maximum purchase fee for token0
    /// @param _minToken1PurchaseFee The minimum purchase fee for token1
    /// @param _maxToken1PurchaseFee The maximum purchase fee for token1
    function setFeeBounds(
        uint256 _minToken0PurchaseFee,
        uint256 _maxToken0PurchaseFee,
        uint256 _minToken1PurchaseFee,
        uint256 _maxToken1PurchaseFee
    ) public {
        // Checks: Only the access control manager can set the fee bounds
        _requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });

        // Checks: Ensure the params are valid
        if (_minToken0PurchaseFee > _maxToken0PurchaseFee) revert MinToken0PurchaseFeeGreaterThanMax();
        if (_minToken1PurchaseFee > _maxToken1PurchaseFee) revert MinToken1PurchaseFeeGreaterThanMax();

        // Effects: Set the fee bounds
        _getPointerToStorage().configStorage.minToken0PurchaseFee = _minToken0PurchaseFee;
        _getPointerToStorage().configStorage.maxToken0PurchaseFee = _maxToken0PurchaseFee;
        _getPointerToStorage().configStorage.minToken1PurchaseFee = _minToken1PurchaseFee;
        _getPointerToStorage().configStorage.maxToken1PurchaseFee = _maxToken1PurchaseFee;

        // emit event
        emit SetFeeBounds({
            minToken0PurchaseFee: _minToken0PurchaseFee,
            maxToken0PurchaseFee: _maxToken0PurchaseFee,
            minToken1PurchaseFee: _minToken1PurchaseFee,
            maxToken1PurchaseFee: _maxToken1PurchaseFee
        });
    }

    /// @notice The ```setTokenPurchaseFees``` function sets the token purchase fees
    /// @dev Only the fee setter can set the fee
    /// @param _token0PurchaseFee The purchase fee for token0
    /// @param _token1PurchaseFee The purchase fee for token1
    function setTokenPurchaseFees(uint256 _token0PurchaseFee, uint256 _token1PurchaseFee) public {
        // Checks: Only the fee setter can set the fee
        _requireSenderIsRole({ _role: FEE_SETTER_ROLE });

        // Checks: Ensure the params are valid and within the bounds
        if (
            _token0PurchaseFee < _getPointerToStorage().configStorage.minToken0PurchaseFee ||
            _token0PurchaseFee > _getPointerToStorage().configStorage.maxToken0PurchaseFee
        ) revert InvalidToken0PurchaseFee();
        if (
            _token1PurchaseFee < _getPointerToStorage().configStorage.minToken1PurchaseFee ||
            _token1PurchaseFee > _getPointerToStorage().configStorage.maxToken1PurchaseFee
        ) revert InvalidToken1PurchaseFee();

        // Effects: Set the token purchase fees
        _getPointerToStorage().swapStorage.token0PurchaseFee = _token0PurchaseFee.toUint64();
        _getPointerToStorage().swapStorage.token1PurchaseFee = _token1PurchaseFee.toUint64();

        // emit event
        emit SetTokenPurchaseFees({ token0PurchaseFee: _token0PurchaseFee, token1PurchaseFee: _token1PurchaseFee });
    }

    /// @notice The ```removeTokens``` function removes tokens from the pair
    /// @dev Only the token remover can remove tokens
    /// @param _tokenAddress The address of the token
    /// @param _amount The amount of tokens to remove
    function removeTokens(address _tokenAddress, uint256 _amount) external {
        // Checks: Only the token remover can remove tokens
        _requireSenderIsRole({ _role: TOKEN_REMOVER_ROLE });

        SwapStorage memory _swapStorage = _getPointerToStorage().swapStorage;
        ConfigStorage memory _configStorage = _getPointerToStorage().configStorage;

        uint256 _token0Balance = IERC20(_swapStorage.token0).balanceOf(address(this));
        uint256 _token1Balance = IERC20(_swapStorage.token1).balanceOf(address(this));

        // Checks: sufficient tokens available (we check the actual balance here instead of reserves)
        if (_tokenAddress == _swapStorage.token0 && _amount > _token0Balance - _swapStorage.token0FeesAccumulated) {
            revert InsufficientTokens();
        }
        if (_tokenAddress == _swapStorage.token1 && _amount > _token1Balance - _swapStorage.token1FeesAccumulated) {
            revert InsufficientTokens();
        }

        // Interactions: transfer tokens from the pair to the token receiver
        IERC20(_tokenAddress).safeTransfer({ to: _configStorage.tokenReceiverAddress, value: _amount });

        // Update reserves + fees accumulated
        _sync({
            _token0Balance: IERC20(_swapStorage.token0).balanceOf(address(this)),
            _token1Balance: IERC20(_swapStorage.token1).balanceOf(address(this)),
            _token0FeesAccumulated: _swapStorage.token0FeesAccumulated,
            _token1FeesAccumulated: _swapStorage.token1FeesAccumulated
        });

        // emit event
        emit RemoveTokens({ tokenAddress: _tokenAddress, amount: _amount });
    }

    /// @notice The ```collectFees``` function removes accumulated fees from the pair
    /// @dev Only the token remover can collect fees
    /// @param _tokenAddress The address of the token
    /// @param _amount The amount of tokens to remove
    function collectFees(address _tokenAddress, uint256 _amount) external {
        // Checks: Only the tokenRemover can remove tokens
        _requireSenderIsRole({ _role: TOKEN_REMOVER_ROLE });

        SwapStorage memory _swapStorage = _getPointerToStorage().swapStorage;
        ConfigStorage memory _configStorage = _getPointerToStorage().configStorage;

        // Checks: sufficient fees accumulated
        if (_tokenAddress == _swapStorage.token0 && _amount > _swapStorage.token0FeesAccumulated) {
            revert InsufficientTokens();
        }
        if (_tokenAddress == _swapStorage.token1 && _amount > _swapStorage.token1FeesAccumulated) {
            revert InsufficientTokens();
        }

        // Calculate fees accumulated based on which token was transferred out
        if (_tokenAddress == _swapStorage.token0) {
            _swapStorage.token0FeesAccumulated -= _amount.toUint128();
        } else if (_tokenAddress == _swapStorage.token1) {
            _swapStorage.token1FeesAccumulated -= _amount.toUint128();
        } else {
            // If trying to remove a token not part of the pair, use the removeTokens function
            revert InvalidTokenAddress();
        }

        // Interactions: transfer fees from the pair to the fee receiver
        IERC20(_tokenAddress).safeTransfer({ to: _configStorage.feeReceiverAddress, value: _amount });

        // Update reserves + fees accumulated
        _sync({
            _token0Balance: IERC20(_swapStorage.token0).balanceOf(address(this)),
            _token1Balance: IERC20(_swapStorage.token1).balanceOf(address(this)),
            _token0FeesAccumulated: _swapStorage.token0FeesAccumulated,
            _token1FeesAccumulated: _swapStorage.token1FeesAccumulated
        });

        // emit event
        emit CollectFees({ tokenAddress: _tokenAddress, amount: _amount });
    }

    /// @notice The ```setPaused``` function sets the paused state of the pair
    /// @dev Only the pauser can pause the pair
    /// @param _setPaused The boolean value indicating whether the pair is paused
    function setPaused(bool _setPaused) public {
        // Checks: Only the pauser can pause the pair
        _requireSenderIsRole({ _role: PAUSER_ROLE });

        // Effects: Set the isPaused state
        _getPointerToStorage().swapStorage.isPaused = _setPaused;

        // emit event
        emit SetPaused({ isPaused: _setPaused });
    }

    /// @notice The ```setOraclePriceBounds``` function sets the price bounds for the pair
    /// @dev Only the access control manager can set the price bounds
    /// @param _minBasePrice The minimum allowed initial base price
    /// @param _maxBasePrice The maximum allowed initial base price
    /// @param _minAnnualizedInterestRate The minimum allowed annualized interest rate
    /// @param _maxAnnualizedInterestRate The maximum allowed annualized interest rate
    function setOraclePriceBounds(
        uint256 _minBasePrice,
        uint256 _maxBasePrice,
        int256 _minAnnualizedInterestRate,
        int256 _maxAnnualizedInterestRate
    ) public {
        // Checks: Only the access control manager can set the price bounds
        _requireSenderIsRole({ _role: ACCESS_CONTROL_MANAGER_ROLE });
        // Checks: parameters are valid
        if (_minBasePrice > _maxBasePrice) revert MinBasePriceGreaterThanMaxBasePrice();
        if (_minAnnualizedInterestRate > _maxAnnualizedInterestRate) revert MinAnnualizedInterestRateGreaterThanMax();

        // Effects: Set the price and annualized interest bounds
        _getPointerToStorage().configStorage.minBasePrice = _minBasePrice;
        _getPointerToStorage().configStorage.maxBasePrice = _maxBasePrice;
        _getPointerToStorage().configStorage.minAnnualizedInterestRate = _minAnnualizedInterestRate;
        _getPointerToStorage().configStorage.maxAnnualizedInterestRate = _maxAnnualizedInterestRate;

        // emit event
        emit SetOraclePriceBounds({
            minBasePrice: _minBasePrice,
            maxBasePrice: _maxBasePrice,
            minAnnualizedInterestRate: _minAnnualizedInterestRate,
            maxAnnualizedInterestRate: _maxAnnualizedInterestRate
        });
    }

    /// @notice The ```configureOraclePrice``` function configures the price of the pair
    /// @dev Only the price setter can configure the price
    /// @param _basePrice The base price of the pair
    /// @param _annualizedInterestRate The annualized interest rate
    /// @param _deadline The deadline for the price configuration
    function configureOraclePrice(uint256 _basePrice, int256 _annualizedInterestRate, uint256 _deadline) public {
        // Checks: Only the price setter can configure the price
        _requireSenderIsRole({ _role: PRICE_SETTER_ROLE });
        // Checks: block.timestamp must be less than deadline
        if (_deadline < block.timestamp) revert PriceExpired();

        ConfigStorage memory _configStorage = _getPointerToStorage().configStorage;

        // Checks: price is within bounds
        if (_basePrice < _configStorage.minBasePrice || _basePrice > _configStorage.maxBasePrice) {
            revert BasePriceOutOfBounds();
        }
        if (
            _annualizedInterestRate < _configStorage.minAnnualizedInterestRate ||
            _annualizedInterestRate > _configStorage.maxAnnualizedInterestRate
        ) revert AnnualizedInterestRateOutOfBounds();

        // Effects: Set the time of the last price update
        _getPointerToStorage().swapStorage.priceLastUpdated = (block.timestamp).toUint40();
        // Effects: Convert yearly APR to per second APR
        _getPointerToStorage().swapStorage.perSecondInterestRate = (_annualizedInterestRate / 365 days).toInt72();
        // Effects: Set the price of the asset
        _getPointerToStorage().swapStorage.basePrice = _basePrice;

        // emit event
        emit ConfigureOraclePrice(_basePrice, _annualizedInterestRate);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.22;

import { IERC1967 } from "../../interfaces/IERC1967.sol";
import { Address } from "../../utils/Address.sol";
import { StorageSlot } from "../../utils/StorageSlot.sol";
import { IBeacon } from "../beacon/IBeacon.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {

    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT =
        0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(
        address newImplementation
    ) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) Address.functionDelegateCall(newImplementation, data);
        else _checkNonPayable();
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT =
        0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(
        address newAdmin
    ) private {
        if (newAdmin == address(0)) revert ERC1967InvalidAdmin(address(0));
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(
        address newAdmin
    ) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT =
        0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(
        address newBeacon
    ) private {
        if (newBeacon.code.length == 0) revert ERC1967InvalidBeacon(newBeacon);

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) revert ERC1967NonPayable();
    }

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)

pragma solidity ^0.8.20;

/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {

    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(
        address implementation
    ) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }

    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback
     * function and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);

    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _delegate(_implementation());
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/transparent/TransparentUpgradeableProxy.sol)

pragma solidity ^0.8.22;

import { IERC1967 } from "../../interfaces/IERC1967.sol";
import { ERC1967Proxy } from "../ERC1967/ERC1967Proxy.sol";
import { ERC1967Utils } from "../ERC1967/ERC1967Utils.sol";

import { ProxyAdmin } from "./ProxyAdmin.sol";

/**
 * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy}
 * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch
 * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not
 * include them in the ABI so this interface must be used to interact with it.
 */
interface ITransparentUpgradeableProxy is IERC1967 {

    /// @dev See {UUPSUpgradeable-upgradeToAndCall}
    function upgradeToAndCall(address newImplementation, bytes calldata data) external payable;

}

/**
 * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance.
 *
 * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
 * clashing], which can potentially be used in an attack, this contract uses the
 * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
 * things that go hand in hand:
 *
 * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
 * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself.
 * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to
 * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating
 * the proxy admin cannot fallback to the target implementation.
 *
 * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a
 * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to
 * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and
 * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative
 * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership.
 *
 * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not
 * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch
 * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to
 * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the
 * implementation.
 *
 * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a
 * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract.
 *
 * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an
 * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be
 * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an
 * undesirable state where the admin slot is different from the actual admin. Relying on the value of the admin slot
 * is generally fine if the implementation is trusted.
 *
 * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the
 * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new
 * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This
 * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency.
 */
contract TransparentUpgradeableProxy is ERC1967Proxy {

    // An immutable address for the admin to avoid unnecessary SLOADs before each call
    // at the expense of removing the ability to change the admin once it's set.
    // This is acceptable if the admin is always a ProxyAdmin instance or similar contract
    // with its own ability to transfer the permissions to another account.
    address private immutable _admin;

    /**
     * @dev The proxy caller is the current admin, and can't fallback to the proxy target.
     */
    error ProxyDeniedAdminAccess();

    /**
     * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`,
     * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in
     * {ERC1967Proxy-constructor}.
     */
    constructor(
        address _logic,
        address initialOwner,
        bytes memory _data
    ) payable ERC1967Proxy(_logic, _data) {
        _admin = address(new ProxyAdmin(initialOwner));
        // Set the storage value and emit an event for ERC-1967 compatibility
        ERC1967Utils.changeAdmin(_proxyAdmin());
    }

    /**
     * @dev Returns the admin of this proxy.
     */
    function _proxyAdmin() internal view virtual returns (address) {
        return _admin;
    }

    /**
     * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior.
     */
    function _fallback() internal virtual override {
        if (msg.sender == _proxyAdmin()) {
            if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) {
                revert ProxyDeniedAdminAccess();
            } else {
                _dispatchUpgradeToAndCall();
            }
        } else {
            super._fallback();
        }
    }

    /**
     * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}.
     *
     * Requirements:
     *
     * - If `data` is empty, `msg.value` must be zero.
     */
    function _dispatchUpgradeToAndCall() private {
        (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes));
        ERC1967Utils.upgradeToAndCall(newImplementation, data);
    }

}

File 20 of 38 : Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {

    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(
        uint256 code
    ) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }

}

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

// ====================================================================
//             _        ______     ___   _______          _
//            / \     .' ___  |  .'   `.|_   __ \        / \
//           / _ \   / .'   \_| /  .-.  \ | |__) |      / _ \
//          / ___ \  | |   ____ | |   | | |  __ /      / ___ \
//        _/ /   \ \_\ `.___]  |\  `-'  /_| |  \ \_  _/ /   \ \_
//       |____| |____|`._____.'  `.___.'|____| |___||____| |____|
// ====================================================================
// ==================== AgoraStableSwapPairCore =======================
// ====================================================================
import { AgoraStableSwapAccessControl } from "./AgoraStableSwapAccessControl.sol";

import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuardTransient } from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Erc1967Implementation } from "agora-contracts/proxy/Erc1967Implementation.sol";

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

/// @title AgoraStableSwapPairCore
/// @notice The AgoraStableSwapPairCore is a contract that manages the core logic for the AgoraStableSwapPair
/// @author Agora
abstract contract AgoraStableSwapPairCore is
    AgoraStableSwapAccessControl,
    Erc1967Implementation,
    Initializable,
    ReentrancyGuardTransient
{
    using SafeERC20 for IERC20;
    using SafeCast for uint256;

    //==============================================================================
    // Storage Structs
    //==============================================================================

    /// @notice The ```ConfigStorage``` struct is used to store the configuration of the AgoraStableSwapPair
    /// @param minToken0PurchaseFee The minimum purchase fee for token0, 18 decimals precision, max value 1
    /// @param maxToken0PurchaseFee The maximum purchase fee for token0, 18 decimals precision, max value 1
    /// @param minToken1PurchaseFee The minimum purchase fee for token1, 18 decimals precision, max value 1
    /// @param maxToken1PurchaseFee The maximum purchase fee for token1, 18 decimals precision, max value 1
    /// @param tokenReceiverAddress The address of the token receiver
    /// @param feeReceiverAddress The address of the fee receiver
    /// @param minBasePrice The minimum base price for the pair, 18 decimals precision, min/max value determined by difference between decimals of token0 and token1
    /// @param maxBasePrice The maximum base price for the pair, 18 decimals precision, min/max value determined by difference between decimals of token0 and token1
    /// @param minAnnualizedInterestRate The minimum annualized interest rate for the pair, 18 decimals precision, given as number i.e. 1e16 = 1%
    /// @param maxAnnualizedInterestRate The maximum annualized interest rate for the pair, 18 decimals precision, given as number i.e. 1e16 = 1%
    /// @param token0Decimals The number of decimals for token0
    /// @param token1Decimals The number of decimals for token1
    struct ConfigStorage {
        uint256 minToken0PurchaseFee; // 18 decimals precision, max value 1
        uint256 maxToken0PurchaseFee; // 18 decimals precision, max value 1
        uint256 minToken1PurchaseFee; // 18 decimals precision, max value 1
        uint256 maxToken1PurchaseFee; // 18 decimals precision, max value 1
        address tokenReceiverAddress;
        address feeReceiverAddress;
        uint256 minBasePrice; // 18 decimals precision, max value determined by difference between decimals of token0 and token1
        uint256 maxBasePrice; // 18 decimals precision, max value determined by difference between decimals of token0 and token1
        int256 minAnnualizedInterestRate; // 18 decimals precision, given as number i.e. 1e16 = 1%
        int256 maxAnnualizedInterestRate; // 18 decimals precision, given as number i.e. 1e16 = 1%
        uint8 token0Decimals;
        uint8 token1Decimals;
    }

    /// @notice The ```SwapStorage``` struct is used to store the state of the AgoraStableSwapPair
    /// @param isPaused The boolean value indicating whether the pair is paused
    /// @param token0 The address of token0
    /// @param token1 The address of token1
    /// @param reserve0 The reserve of token0, given as raw value
    /// @param reserve1 The reserve of token1, given as raw value
    /// @param token0PurchaseFee The purchase fee for token0, 18 decimals precision, max value 1
    /// @param token1PurchaseFee The purchase fee for token1, 18 decimals precision, max value 1
    /// @param priceLastUpdated The last block timestamp when the price was updated
    /// @param perSecondInterestRate The per second interest rate for the pair, 18 decimals precision, given as whole number with 18 decimals of precision i.e. 1e16 = 1%
    /// @param basePrice The base price for the pair, 18 decimals precision, limited by token0 and token1 decimals
    /// @param token0FeesAccumulated The accumulated fees for token0, given as raw value
    /// @param token1FeesAccumulated The accumulated fees for token1, given as raw value
    struct SwapStorage {
        bool isPaused;
        address token0;
        address token1;
        uint112 reserve0;
        uint112 reserve1;
        uint64 token0PurchaseFee; // 18 decimals precision, max value 1
        uint64 token1PurchaseFee; // 18 decimals precision, max value 1
        uint40 priceLastUpdated;
        int72 perSecondInterestRate; // 18 decimals of precision, given as whole number i.e. 1e16 = 1%
        uint256 basePrice; // 18 decimals of precision, limited by token0 and token1 decimals
        uint128 token0FeesAccumulated;
        uint128 token1FeesAccumulated;
    }

    /// @notice The ```AgoraStableSwapStorage``` struct is used to store the state of the AgoraStableSwapPair contract
    /// @param swapStorage The swap storage struct, values used during call to swap()
    /// @param configStorage The config storage struct, values used outside of swap()
    struct AgoraStableSwapStorage {
        SwapStorage swapStorage;
        ConfigStorage configStorage;
    }

    //==============================================================================
    // Erc 7201: UnstructuredNamespace Storage Functions
    //==============================================================================

    /// @notice The ```AGORA_STABLE_SWAP_STORAGE_SLOT``` is the storage slot for the AgoraStableSwapStorage struct
    /// @dev keccak256(abi.encode(uint256(keccak256("AgoraStableSwapPairStorage")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 public constant AGORA_STABLE_SWAP_STORAGE_SLOT =
        0x7bec511bd7f6687e2731c8fe683a8e6468bf371b3ebd503eee87dd5465b4a500;

    /// @notice The ```_getPointerToStorage``` function returns a pointer to the AgoraStableSwapStorage struct
    /// @return $ A pointer to the AgoraStableSwapStorage struct
    function _getPointerToStorage() internal pure returns (AgoraStableSwapStorage storage $) {
        /// @solidity memory-safe-assembly
        assembly {
            $.slot := AGORA_STABLE_SWAP_STORAGE_SLOT
        }
    }

    /// @notice The ```PRICE_PRECISION``` constant is the precision for the price, 18 decimals precision
    uint256 public constant PRICE_PRECISION = 1e18;
    /// @notice The ```FEE_PRECISION``` constant is the precision for the fees, 18 decimals precision
    uint256 public constant FEE_PRECISION = 1e18;

    //==============================================================================
    // Pure Helper Functions
    //==============================================================================

    /// @notice The ```requireValidPath``` function checks that the path is valid
    /// @param _path The path to check
    /// @param _token0 The address of the first token in the pair
    /// @param _token1 The address of the second token in the pair
    function requireValidPath(address[] memory _path, address _token0, address _token1) public pure {
        // Checks: path length is 2
        if (_path.length != 2) revert InvalidPathLength();

        if (!(_path[0] == _token0 && _path[1] == _token1) && !(_path[0] == _token1 && _path[1] == _token0)) {
            revert InvalidPath();
        }
    }

    /// @notice The ```getAmount0In``` function calculates the amount of input token0In required for a given amount token1Out
    /// @param _amount1Out The amount of output token1
    /// @param _token0OverToken1Price The price of the pair expressed as token0 over token1 with 18 decimals of precision
    /// @param _token1PurchaseFee The purchase fee for the token1, given as a percentage with 18 decimals of precision i.e. 1e16 = 1%
    /// @return _amount0In The amount of input token0
    /// @return _token1PurchaseFeeAmount The amount of accumulated fees for the purchase of token1
    function getAmount0In(
        uint256 _amount1Out,
        uint256 _token0OverToken1Price,
        uint256 _token1PurchaseFee
    ) public pure returns (uint256 _amount0In, uint256 _token1PurchaseFeeAmount) {
        _token1PurchaseFeeAmount = (_amount1Out * _token1PurchaseFee) / (FEE_PRECISION - _token1PurchaseFee);

        // Always round up the fee
        if (_token1PurchaseFeeAmount * (FEE_PRECISION - _token1PurchaseFee) < _amount1Out * _token1PurchaseFee) {
            _token1PurchaseFeeAmount += 1;
        }

        _amount0In = ((_amount1Out + _token1PurchaseFeeAmount) * _token0OverToken1Price) / PRICE_PRECISION;

        // Always round up the amount going into the contract
        if (_amount0In * PRICE_PRECISION < (_amount1Out + _token1PurchaseFeeAmount) * _token0OverToken1Price) {
            _amount0In += 1;
        }
    }

    /// @notice The ```getAmount1In``` function calculates the amount of input token1In required for a given amount token0Out
    /// @param _amount0Out The amount of output token0
    /// @param _token0OverToken1Price The price of the pair expressed as token0 over token1 with 18 decimals of precision
    /// @param _token0PurchaseFee The purchase fee for the token0, given as a percentage with 18 decimals of precision i.e. 1e16 = 1%
    /// @return _amount1In The amount of input token1
    /// @return _token0FeeAmount The amount of purchase fees for the token0
    function getAmount1In(
        uint256 _amount0Out,
        uint256 _token0OverToken1Price,
        uint256 _token0PurchaseFee
    ) public pure returns (uint256 _amount1In, uint256 _token0FeeAmount) {
        _token0FeeAmount = (_amount0Out * _token0PurchaseFee) / (FEE_PRECISION - _token0PurchaseFee);

        // Always round up the fee
        if (_token0FeeAmount * (FEE_PRECISION - _token0PurchaseFee) < _amount0Out * _token0PurchaseFee) {
            _token0FeeAmount += 1;
        }

        _amount1In = ((_amount0Out + _token0FeeAmount) * PRICE_PRECISION) / _token0OverToken1Price;

        // Always round up the amount going into the contract
        if (_amount1In * _token0OverToken1Price < (_amount0Out + _token0FeeAmount) * PRICE_PRECISION) _amount1In += 1;
    }

    /// @notice The ```getAmount0Out``` function calculates the amount of output token0Out returned from a given amount of input token1In
    /// @param _amount1In The amount of input token1
    /// @param _token0OverToken1Price The price of the pair expressed as token0 over token1 with 18 decimals of precision
    /// @param _token0PurchaseFee The purchase fee for the token0, given as a percentage with 18 decimals of precision i.e. 1e16 = 1%
    /// @return _amount0Out The amount of output token0
    /// @return _token0PurchaseFeeAmount The amount of purchase fees for the token0
    function getAmount0Out(
        uint256 _amount1In,
        uint256 _token0OverToken1Price,
        uint256 _token0PurchaseFee
    ) public pure returns (uint256 _amount0Out, uint256 _token0PurchaseFeeAmount) {
        // NOTE:  price and fee must be chosen such that we dont get an overflow during the multiplication here
        _token0PurchaseFeeAmount =
            (_amount1In * _token0OverToken1Price * _token0PurchaseFee) /
            (FEE_PRECISION * PRICE_PRECISION);

        // Always round up the fee
        if (
            _token0PurchaseFeeAmount * FEE_PRECISION * PRICE_PRECISION <
            _amount1In * _token0OverToken1Price * _token0PurchaseFee
        ) _token0PurchaseFeeAmount += 1;

        _amount0Out = ((_amount1In * _token0OverToken1Price) / PRICE_PRECISION) - _token0PurchaseFeeAmount;
    }

    /// @notice The ```getAmount1Out``` function calculates the amount of output token1Out returned from a given amount of input token0In
    /// @param _amount0In The amount of input token0
    /// @param _token0OverToken1Price The price of the pair expressed as token0 over token1 with 18 decimals of precision
    /// @param _token1PurchaseFee The purchase fee for the token1, given as a percentage with 18 decimals of precision i.e. 1e16 = 1%
    /// @return _amount1Out The amount of output token1
    /// @return _token1PurchaseFeeAmount The amount of purchase fees for the token1
    function getAmount1Out(
        uint256 _amount0In,
        uint256 _token0OverToken1Price,
        uint256 _token1PurchaseFee
    ) public pure returns (uint256 _amount1Out, uint256 _token1PurchaseFeeAmount) {
        _token1PurchaseFeeAmount =
            (_amount0In * PRICE_PRECISION * _token1PurchaseFee) /
            (FEE_PRECISION * _token0OverToken1Price);

        // Always round up the fee
        if (
            _token1PurchaseFeeAmount * FEE_PRECISION * _token0OverToken1Price <
            _amount0In * PRICE_PRECISION * _token1PurchaseFee
        ) _token1PurchaseFeeAmount += 1;

        _amount1Out = ((_amount0In * PRICE_PRECISION) / _token0OverToken1Price) - _token1PurchaseFeeAmount;
    }

    //==============================================================================
    // External Stateful Functions
    //==============================================================================

    /// @notice The ```swap``` function swaps tokens in the pair
    /// @dev This function is meant to be called by an external contract which performs important safety checks
    /// @param _amount0Out The amount of token0 to send out
    /// @param _amount1Out The amount of token1 to send out
    /// @param _to The address to send the tokens to
    /// @param _data The data to send to the callback
    function swap(uint256 _amount0Out, uint256 _amount1Out, address _to, bytes memory _data) public nonReentrant {
        _requireSenderIsRole({ _role: APPROVED_SWAPPER });

        // Checks: input sanitation, force one amountOut to be 0, and the other to be > 0
        if ((_amount0Out != 0 && _amount1Out != 0) || (_amount0Out == 0 && _amount1Out == 0)) {
            revert InvalidSwapAmounts();
        }

        // Cache information about the pair for gas savings
        SwapStorage memory _swapStorage = _getPointerToStorage().swapStorage;
        uint256 _token0OverToken1Price = calculatePrice({
            _priceLastUpdated: _swapStorage.priceLastUpdated,
            _timestamp: block.timestamp,
            _perSecondInterestRate: _swapStorage.perSecondInterestRate,
            _basePrice: _swapStorage.basePrice
        });

        // Checks: ensure pair not paused
        if (_swapStorage.isPaused) revert PairIsPaused();

        // Send the tokens (you can only send 1)
        if (_amount0Out > 0) IERC20(_swapStorage.token0).safeTransfer({ to: _to, value: _amount0Out });
        else IERC20(_swapStorage.token1).safeTransfer({ to: _to, value: _amount1Out });

        // Execute the callback (if relevant)
        if (_data.length > 0) {
            IUniswapV2Callee(_to).uniswapV2Call({
                sender: msg.sender,
                amount0: _amount0Out,
                amount1: _amount1Out,
                data: _data
            });
        }

        uint256 _token0In;
        uint256 _token1In;
        {
            // Create local scope
            // Take snapshot of balances
            uint256 _finalToken0Balance = IERC20(_swapStorage.token0).balanceOf({ account: address(this) });
            uint256 _finalToken1Balance = IERC20(_swapStorage.token1).balanceOf({ account: address(this) });

            uint256 _previousToken0Balance = _swapStorage.reserve0 + _swapStorage.token0FeesAccumulated;
            uint256 _previousToken1Balance = _swapStorage.reserve1 + _swapStorage.token1FeesAccumulated;

            // Calculate how many tokens were transferred
            _token0In = _finalToken0Balance > (_previousToken0Balance - _amount0Out)
                ? _finalToken0Balance - (_previousToken0Balance - _amount0Out)
                : 0;
            _token1In = _finalToken1Balance > (_previousToken1Balance - _amount1Out)
                ? _finalToken1Balance - (_previousToken1Balance - _amount1Out)
                : 0;
            uint256 _token0PurchaseFee;
            uint256 _token1PurchaseFee;

            // Checks: Final invariant, ensure that we received the correct amount of tokens
            if (_amount0Out > 0) {
                // we are sending token0 out, receiving token1 In
                uint256 _expectedAmount1In;
                (_expectedAmount1In, _token0PurchaseFee) = getAmount1In({
                    _amount0Out: _amount0Out,
                    _token0OverToken1Price: _token0OverToken1Price,
                    _token0PurchaseFee: _swapStorage.token0PurchaseFee
                });
                if (_expectedAmount1In > _token1In) revert InsufficientInputAmount();
            } else {
                // we are sending token1 out, receiving token0 in
                uint256 _expectedAmount0In;
                (_expectedAmount0In, _token1PurchaseFee) = getAmount0In({
                    _amount1Out: _amount1Out,
                    _token0OverToken1Price: _token0OverToken1Price,
                    _token1PurchaseFee: _swapStorage.token1PurchaseFee
                });
                if (_expectedAmount0In > _token0In) revert InsufficientInputAmount();
            }

            // emit event
            emit SwapFees({ token0PurchaseFee: _token0PurchaseFee, token1PurchaseFee: _token1PurchaseFee });

            // Calculate new fees + reserves in memory struct
            _swapStorage.token0FeesAccumulated += _token0PurchaseFee.toUint128();
            _swapStorage.token1FeesAccumulated += _token1PurchaseFee.toUint128();
            _swapStorage.reserve0 = (_finalToken0Balance - _swapStorage.token0FeesAccumulated).toUint112();
            _swapStorage.reserve1 = (_finalToken1Balance - _swapStorage.token1FeesAccumulated).toUint112();
        }

        // Effects: update storage
        _getPointerToStorage().swapStorage = _swapStorage;

        // emit event
        emit Sync({ reserve0: _swapStorage.reserve0, reserve1: _swapStorage.reserve1 });

        // emit event
        emit Swap({
            sender: msg.sender,
            amount0In: _token0In,
            amount1In: _token1In,
            amount0Out: _amount0Out,
            amount1Out: _amount1Out,
            to: _to
        });
    }

    /// @notice The ```swapExactTokensForTokens``` function swaps an exact amount of input tokenIn for an amount of output tokenOut
    /// @param _amountIn The amount of input tokenIn
    /// @param _amountOutMin The minimum amount of output tokenOut
    /// @param _path The path of the tokens
    /// @param _to The address to send the tokens to
    /// @param _deadline The deadline for the swap
    function swapExactTokensForTokens(
        uint256 _amountIn,
        uint256 _amountOutMin,
        address[] memory _path,
        address _to,
        uint256 _deadline
    ) external returns (uint256[] memory _amounts) {
        // Checks: block.timestamp must be less than deadline
        if (_deadline < block.timestamp) revert Expired();

        address _tokenIn = _path[0];
        address _tokenOut = _path[1];
        SwapStorage memory _swapStorage = _getPointerToStorage().swapStorage;
        uint256 _token0OverToken1Price = calculatePrice({
            _priceLastUpdated: _swapStorage.priceLastUpdated,
            _timestamp: block.timestamp,
            _perSecondInterestRate: _swapStorage.perSecondInterestRate,
            _basePrice: _swapStorage.basePrice
        });

        // Checks: path length is 2 && path must contain token0 and token1 only
        requireValidPath({ _path: _path, _token0: _swapStorage.token0, _token1: _swapStorage.token1 });

        // Calculations: determine amounts based on path
        (uint256 _amountOut, ) = _tokenOut == _swapStorage.token0
            ? getAmount0Out({
                _amount1In: _amountIn,
                _token0OverToken1Price: _token0OverToken1Price,
                _token0PurchaseFee: _swapStorage.token0PurchaseFee
            })
            : getAmount1Out({
                _amount0In: _amountIn,
                _token0OverToken1Price: _token0OverToken1Price,
                _token1PurchaseFee: _swapStorage.token1PurchaseFee
            });

        // Checks: amountOut must not be smaller than the amountOutMin
        if (_amountOut < _amountOutMin) revert InsufficientOutputAmount();

        // Interactions: transfer tokens from msg.sender to this contract
        IERC20(_tokenIn).safeTransferFrom({ from: msg.sender, to: address(this), value: _amountIn });

        // Effects: swap tokens
        if (_tokenOut == _swapStorage.token0) {
            swap({ _amount0Out: _amountOut, _amount1Out: 0, _to: _to, _data: new bytes(0) });
        } else {
            swap({ _amount0Out: 0, _amount1Out: _amountOut, _to: _to, _data: new bytes(0) });
        }

        // Set return variables
        _amounts = new uint256[](2);
        _amounts[0] = _amountIn;
        _amounts[1] = _amountOut;
    }

    /// @notice The ```swapTokensForExactTokens``` function swaps an amount of output tokenOut for an exact amount of input tokenIn
    /// @param _amountOut The amount of output tokenOut
    /// @param _amountInMax The maximum amount of input tokenIn
    /// @param _path The path of the tokens
    /// @param _to The address to send the tokens to
    /// @param _deadline The deadline for the swap
    function swapTokensForExactTokens(
        uint256 _amountOut,
        uint256 _amountInMax,
        address[] memory _path,
        address _to,
        uint256 _deadline
    ) external returns (uint256[] memory _amounts) {
        // Checks: block.timestamp must be less than deadline
        if (_deadline < block.timestamp) revert Expired();

        address _tokenIn = _path[0];
        address _tokenOut = _path[1];
        SwapStorage memory _swapStorage = _getPointerToStorage().swapStorage;
        uint256 _token0OverToken1Price = calculatePrice({
            _priceLastUpdated: _swapStorage.priceLastUpdated,
            _timestamp: block.timestamp,
            _perSecondInterestRate: _swapStorage.perSecondInterestRate,
            _basePrice: _swapStorage.basePrice
        });

        // Checks: path length is 2 && path must contain token0 and token1 only
        requireValidPath({ _path: _path, _token0: _swapStorage.token0, _token1: _swapStorage.token1 });

        // Calculations: determine amounts based on path
        (uint256 _amountIn, ) = _tokenIn == _swapStorage.token0
            ? getAmount0In({
                _amount1Out: _amountOut,
                _token0OverToken1Price: _token0OverToken1Price,
                _token1PurchaseFee: _swapStorage.token1PurchaseFee
            })
            : getAmount1In({
                _amount0Out: _amountOut,
                _token0OverToken1Price: _token0OverToken1Price,
                _token0PurchaseFee: _swapStorage.token0PurchaseFee
            });

        // Checks: amountInMax must be larger or equal to than the amountIn
        if (_amountIn > _amountInMax) revert ExcessiveInputAmount();

        // Interactions: transfer tokens from msg.sender to this contract
        IERC20(_tokenIn).safeTransferFrom({ from: msg.sender, to: address(this), value: _amountIn });

        // Effects: swap tokens
        if (_tokenOut == _swapStorage.token0) {
            swap({ _amount0Out: _amountOut, _amount1Out: 0, _to: _to, _data: new bytes(0) });
        } else {
            swap({ _amount0Out: 0, _amount1Out: _amountOut, _to: _to, _data: new bytes(0) });
        }

        // Set return variables
        _amounts = new uint256[](2);
        _amounts[0] = _amountIn;
        _amounts[1] = _amountOut;
    }

    /// @notice The ```sync``` function syncs the reserves of the pair
    /// @dev This function is used to sync the reserves of the pair
    function sync() public {
        SwapStorage memory _storage = _getPointerToStorage().swapStorage;
        _sync({
            _token0Balance: IERC20(_storage.token0).balanceOf(address(this)),
            _token1Balance: IERC20(_storage.token1).balanceOf(address(this)),
            _token0FeesAccumulated: _storage.token0FeesAccumulated,
            _token1FeesAccumulated: _storage.token1FeesAccumulated
        });
    }

    /// @notice The ```_sync``` function syncs the reserves + fees of the pair
    /// @param _token0Balance The balance of token0
    /// @param _token1Balance The balance of token1
    /// @param _token0FeesAccumulated The amount of token0 fees accumulated
    /// @param _token1FeesAccumulated The amount of token1 fees accumulated
    function _sync(
        uint256 _token0Balance,
        uint256 _token1Balance,
        uint256 _token0FeesAccumulated,
        uint256 _token1FeesAccumulated
    ) internal {
        uint112 token0Reserves = (_token0Balance - _token0FeesAccumulated).toUint112();
        uint112 token1Reserves = (_token1Balance - _token1FeesAccumulated).toUint112();

        _getPointerToStorage().swapStorage.reserve0 = token0Reserves;
        _getPointerToStorage().swapStorage.reserve1 = token1Reserves;
        _getPointerToStorage().swapStorage.token0FeesAccumulated = _token0FeesAccumulated.toUint128();
        _getPointerToStorage().swapStorage.token1FeesAccumulated = _token1FeesAccumulated.toUint128();

        // emit event
        emit Sync({ reserve0: token0Reserves, reserve1: token1Reserves });
    }

    /// @notice The ```calculatePrice``` function calculates the price of the pair using a simple interest rate model
    /// @param _priceLastUpdated The timestamp of the last price update
    /// @param _timestamp The timestamp for which we'd like to calculate the price
    /// @param _perSecondInterestRate The per second interest rate
    /// @param _basePrice The base price of the pair
    /// @return _price The price of the pair
    function calculatePrice(
        uint256 _priceLastUpdated,
        uint256 _timestamp,
        int256 _perSecondInterestRate,
        uint256 _basePrice
    ) public pure returns (uint256 _price) {
        // Calculate the time elapsed since the last price update
        uint256 timeElapsed = _timestamp - _priceLastUpdated;

        // Calculate the price
        _price = _perSecondInterestRate >= 0
            ? ((_basePrice * (PRICE_PRECISION + uint256(_perSecondInterestRate) * timeElapsed)) / PRICE_PRECISION)
            : ((_basePrice * (PRICE_PRECISION - (uint256(-_perSecondInterestRate) * timeElapsed))) / PRICE_PRECISION);
    }

    /// @notice The ```getPrice``` function returns the current price of the pair
    /// @return _currentPrice The current price of the pair
    function getPrice() public view virtual returns (uint256 _currentPrice) {
        SwapStorage memory _swapStorage = _getPointerToStorage().swapStorage;
        uint256 _priceLastUpdated = _swapStorage.priceLastUpdated;
        uint256 _currentTimestamp = block.timestamp;
        uint256 _basePrice = _swapStorage.basePrice;
        int256 _perSecondInterestRate = _swapStorage.perSecondInterestRate;
        _currentPrice = calculatePrice({
            _priceLastUpdated: _priceLastUpdated,
            _timestamp: _currentTimestamp,
            _perSecondInterestRate: _perSecondInterestRate,
            _basePrice: _basePrice
        });
    }

    /// @notice The ```getPrice``` function returns the price of the pair at a given timestamp
    /// @param _timestamp The timestamp for which we'd like to get the price
    /// @return _price The price of the pair at the given timestamp
    function getPrice(uint256 _timestamp) public view returns (uint256 _price) {
        SwapStorage memory _swapStorage = _getPointerToStorage().swapStorage;
        uint256 _priceLastUpdated = _swapStorage.priceLastUpdated;
        uint256 _basePrice = _swapStorage.basePrice;
        int256 _perSecondInterestRate = _swapStorage.perSecondInterestRate;
        _price = calculatePrice({
            _priceLastUpdated: _priceLastUpdated,
            _timestamp: _timestamp,
            _perSecondInterestRate: _perSecondInterestRate,
            _basePrice: _basePrice
        });
    }

    //==============================================================================
    // Events
    //==============================================================================

    /// @notice The ```SetTokenReceiver``` event is emitted when the token receiver is set
    /// @param tokenReceiver The address of the token receiver
    event SetTokenReceiver(address indexed tokenReceiver);

    /// @notice The ```SetApprovedSwapper``` event is emitted when the approved swapper is set
    /// @param approvedSwapper The address of the approved swapper
    /// @param isApproved The boolean value indicating whether the swapper is approved
    event SetApprovedSwapper(address indexed approvedSwapper, bool isApproved);

    /// @notice The ```SetFeeBounds``` event is emitted when the fee bounds are set
    /// @param minToken0PurchaseFee The minimum purchase fee for token0
    /// @param maxToken0PurchaseFee The maximum purchase fee for token0
    /// @param minToken1PurchaseFee The minimum purchase fee for token1
    /// @param maxToken1PurchaseFee The maximum purchase fee for token1
    event SetFeeBounds(
        uint256 minToken0PurchaseFee,
        uint256 maxToken0PurchaseFee,
        uint256 minToken1PurchaseFee,
        uint256 maxToken1PurchaseFee
    );

    /// @notice The ```SetTokenPurchaseFees``` event is emitted when the token purchase fees are set
    /// @param token0PurchaseFee The purchase fee for token0
    /// @param token1PurchaseFee The purchase fee for token1
    event SetTokenPurchaseFees(uint256 token0PurchaseFee, uint256 token1PurchaseFee);

    /// @notice The ```RemoveTokens``` event is emitted when tokens are removed
    /// @param tokenAddress The address of the token
    /// @param amount The amount of tokens to remove
    event RemoveTokens(address indexed tokenAddress, uint256 amount);

    /// @notice The ```CollectFees``` event is emitted when fees are collected
    /// @param tokenAddress The address of the token
    /// @param amount The amount of tokens to remove
    event CollectFees(address indexed tokenAddress, uint256 amount);

    /// @notice The ```SetPaused``` event is emitted when the pair is paused
    /// @param isPaused The boolean value indicating whether the pair is paused
    event SetPaused(bool isPaused);

    /// @notice Emitted when the price bounds are set
    /// @param minBasePrice The minimum allowed initial base price
    /// @param maxBasePrice The maximum allowed initial base price
    /// @param minAnnualizedInterestRate The minimum allowed annualized interest rate
    /// @param maxAnnualizedInterestRate The maximum allowed annualized interest rate
    event SetOraclePriceBounds(
        uint256 minBasePrice,
        uint256 maxBasePrice,
        int256 minAnnualizedInterestRate,
        int256 maxAnnualizedInterestRate
    );

    /// @notice Emitted when the price is configured
    /// @param basePrice The base price of the pair
    /// @param annualizedInterestRate The annualized interest rate
    event ConfigureOraclePrice(uint256 basePrice, int256 annualizedInterestRate);

    /// @notice Emitted when a swap is executed
    /// @param sender The address of the sender
    /// @param amount0In The amount of token0 in
    /// @param amount1In The amount of token1 in
    /// @param amount0Out The amount of token0 out
    /// @param amount1Out The amount of token1 out
    /// @param to The address of the recipient
    event Swap(
        address indexed sender,
        uint256 amount0In,
        uint256 amount1In,
        uint256 amount0Out,
        uint256 amount1Out,
        address indexed to
    );

    /// @notice Emitted when fees are accumulated
    /// @param token0PurchaseFee The amount of token0 charged as fees
    /// @param token1PurchaseFee The amount of token1 charged as fees
    event SwapFees(uint256 token0PurchaseFee, uint256 token1PurchaseFee);

    /// @notice Emitted when the reserves are synced
    /// @param reserve0 The reserve of token0
    /// @param reserve1 The reserve of token1
    event Sync(uint256 reserve0, uint256 reserve1);

    /// @notice Emitted when the fee receiver is set
    /// @param feeReceiver The address of the fee receiver
    event SetFeeReceiver(address indexed feeReceiver);

    // ============================================================================================
    // Errors
    // ============================================================================================

    /// @notice Emitted when an invalid token is passed to a function
    error InvalidTokenAddress();

    /// @notice Emitted when an invalid path is passed to a function
    error InvalidPath();

    /// @notice Emitted when an invalid path length is passed to a function
    error InvalidPathLength();

    /// @notice Emitted when both amounts cannot be non-zero
    error InvalidSwapAmounts();

    /// @notice Emitted when the price configuration deadline is passed
    error PriceExpired();

    /// @notice Emitted when the deadline is passed
    error Expired();

    /// @notice Emitted when the reserve is insufficient
    error InsufficientLiquidity();

    /// @notice Emitted when the token purchase fee is invalid
    error InvalidToken0PurchaseFee();

    /// @notice Emitted when the token1 purchase fee is invalid
    error InvalidToken1PurchaseFee();

    /// @notice Emitted when the input amount is excessive
    error ExcessiveInputAmount();

    /// @notice Emitted when the output amount is insufficient
    error InsufficientOutputAmount();

    /// @notice Emitted when the input amount is insufficient
    error InsufficientInputAmount();

    /// @notice Emitted when the pair is paused
    error PairIsPaused();

    /// @notice Emitted when the price is out of bounds
    error BasePriceOutOfBounds();

    /// @notice Emitted when the annualized interest rate is out of bounds
    error AnnualizedInterestRateOutOfBounds();

    /// @notice Emitted when the min base price is greater than the max base price
    error MinBasePriceGreaterThanMaxBasePrice();

    /// @notice Emitted when the min annualized interest rate is greater than the max annualized interest rate
    error MinAnnualizedInterestRateGreaterThanMax();

    /// @notice Emitted when the min token0 purchase fee is greater than the max token0 purchase fee
    error MinToken0PurchaseFeeGreaterThanMax();

    /// @notice Emitted when the min token1 purchase fee is greater than the max token1 purchase fee
    error MinToken1PurchaseFeeGreaterThanMax();

    /// @notice Emitted when there are insufficient tokens available for withrawal
    error InsufficientTokens();

    /// @notice Emitted when the decimals of the tokens are invalid during initialization
    error IncorrectDecimals();
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import { IERC1363 } from "../../../interfaces/IERC1363.sol";
import { IERC20 } from "../IERC20.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {

    /**
     * @dev An operation with an ERC-20 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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(
        IERC1363 token,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(
        IERC1363 token,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }

}

File 23 of 38 : IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)

pragma solidity ^0.8.20;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {

    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Address.sol)

pragma solidity ^0.8.20;

import { Errors } from "./Errors.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @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 Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, bytes memory returndata) = recipient.call{ value: amount }("");
        if (!success) _revert(returndata);
    }

    /**
     * @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
     * {Errors.FailedCall} 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 Errors.InsufficientBalance(address(this).balance, value);
        }
        (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 {Errors.FailedCall}) 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 {Errors.FailedCall} 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 {Errors.FailedCall}.
     */
    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
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {

    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(
        bytes32 slot
    ) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(
        bytes32 slot
    ) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(
        bytes32 slot
    ) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(
        bytes32 slot
    ) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(
        bytes32 slot
    ) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(
        bytes32 slot
    ) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(
        string storage store
    ) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(
        bytes32 slot
    ) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(
        bytes storage store
    ) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {

    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Proxy.sol)

pragma solidity ^0.8.22;

import { Proxy } from "../Proxy.sol";
import { ERC1967Utils } from "./ERC1967Utils.sol";

/**
 * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
 * implementation address that can be changed. This address is stored in storage in the location specified by
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the
 * implementation behind the proxy.
 */
contract ERC1967Proxy is Proxy {

    /**
     * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
     *
     * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
     * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
     *
     * Requirements:
     *
     * - If `data` is empty, `msg.value` must be zero.
     */
    constructor(address implementation, bytes memory _data) payable {
        ERC1967Utils.upgradeToAndCall(implementation, _data);
    }

    /**
     * @dev Returns the current implementation address.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
     */
    function _implementation() internal view virtual override returns (address) {
        return ERC1967Utils.getImplementation();
    }

}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/transparent/ProxyAdmin.sol)

pragma solidity ^0.8.22;

import { Ownable } from "../../access/Ownable.sol";
import { ITransparentUpgradeableProxy } from "./TransparentUpgradeableProxy.sol";

/**
 * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an
 * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.
 */
contract ProxyAdmin is Ownable {

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address,address)`
     * and `upgradeAndCall(address,address,bytes)` are present, and `upgrade` must be used if no function should be called,
     * while `upgradeAndCall` will invoke the `receive` function if the third argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeAndCall(address,address,bytes)` is present, and the third argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev Sets the initial owner who can perform upgrades.
     */
    constructor(
        address initialOwner
    ) Ownable(initialOwner) { }

    /**
     * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation.
     * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}.
     *
     * Requirements:
     *
     * - This contract must be the admin of `proxy`.
     * - If `data` is empty, `msg.value` must be zero.
     */
    function upgradeAndCall(
        ITransparentUpgradeableProxy proxy,
        address implementation,
        bytes memory data
    ) public payable virtual onlyOwner {
        proxy.upgradeToAndCall{ value: msg.value }(implementation, data);
    }

}

File 29 of 38 : AgoraStableSwapAccessControl.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.28;

// ====================================================================
//             _        ______     ___   _______          _
//            / \     .' ___  |  .'   `.|_   __ \        / \
//           / _ \   / .'   \_| /  .-.  \ | |__) |      / _ \
//          / ___ \  | |   ____ | |   | | |  __ /      / ___ \
//        _/ /   \ \_\ `.___]  |\  `-'  /_| |  \ \_  _/ /   \ \_
//       |____| |____|`._____.'  `.___.'|____| |___||____| |____|
// ====================================================================
// ================== AgoraStableSwapAccessControl ====================
// ====================================================================

import { AgoraAccessControl } from "agora-contracts/access-control/AgoraAccessControl.sol";

/// @title AgoraStableSwapAccessControl
/// @notice The AgoraStableSwapAccessControl is a contract that manages the access control for the AgoraStableSwapPair
/// @author Agora
abstract contract AgoraStableSwapAccessControl is AgoraAccessControl {
    /// @notice the WHITELISTER_ROLE identifier
    string public constant WHITELISTER_ROLE = "WHITELISTER_ROLE";

    /// @notice the FEE_SETTER_ROLE identifier
    string public constant FEE_SETTER_ROLE = "FEE_SETTER_ROLE";

    /// @notice the TOKEN_REMOVER_ROLE identifier
    string public constant TOKEN_REMOVER_ROLE = "TOKEN_REMOVER_ROLE";

    /// @notice the PAUSER_ROLE identifier
    string public constant PAUSER_ROLE = "PAUSER_ROLE";

    /// @notice the APPROVED_SWAPPER identifier
    string public constant APPROVED_SWAPPER = "APPROVED_SWAPPER";

    /// @notice the PRICE_SETTER_ROLE identifier
    string public constant PRICE_SETTER_ROLE = "PRICE_SETTER_ROLE";

    /// @notice The ```_initializeAgoraStableSwapAccessControl``` function initializes the AgoraStableSwapAccessControl contract
    /// @dev This function adds the default roles that are required by the AgoraStableSwapPair
    /// @param _initialAdminAddress The address of the initial admin
    /// @param _initialWhitelister The address of the initial whitelister
    /// @param _initialFeeSetter The address of the initial feeSetter
    /// @param _initialTokenRemover The address of the initial tokenRemover
    /// @param _initialPauser The address of the initial pauser
    /// @param _initialPriceSetter The address of the initial priceSetter
    function _initializeAgoraStableSwapAccessControl(
        address _initialAdminAddress,
        address _initialWhitelister,
        address _initialFeeSetter,
        address _initialTokenRemover,
        address _initialPauser,
        address _initialPriceSetter
    ) internal {
        _initializeAgoraAccessControl({ _initialAdminAddress: _initialAdminAddress });

        // Set the whitelister role
        AgoraAccessControl._addRoleToSet({ _role: WHITELISTER_ROLE });
        AgoraAccessControl._assignRole({ _role: WHITELISTER_ROLE, _newAddress: _initialWhitelister, _addRole: true });

        // Set the feeSetter role
        AgoraAccessControl._addRoleToSet({ _role: FEE_SETTER_ROLE });
        AgoraAccessControl._assignRole({ _role: FEE_SETTER_ROLE, _newAddress: _initialFeeSetter, _addRole: true });

        // Set the tokenRemover role
        AgoraAccessControl._addRoleToSet({ _role: TOKEN_REMOVER_ROLE });
        AgoraAccessControl._assignRole({
            _role: TOKEN_REMOVER_ROLE,
            _newAddress: _initialTokenRemover,
            _addRole: true
        });

        // Set the pauser role
        AgoraAccessControl._addRoleToSet({ _role: PAUSER_ROLE });
        AgoraAccessControl._assignRole({ _role: PAUSER_ROLE, _newAddress: _initialPauser, _addRole: true });

        // Set the approvedSwapper role
        AgoraAccessControl._addRoleToSet({ _role: APPROVED_SWAPPER });

        // Set the priceSetter role
        AgoraAccessControl._addRoleToSet({ _role: PRICE_SETTER_ROLE });
        AgoraAccessControl._assignRole({ _role: PRICE_SETTER_ROLE, _newAddress: _initialPriceSetter, _addRole: true });
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuardTransient.sol)

pragma solidity ^0.8.24;

import { TransientSlot } from "./TransientSlot.sol";

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 */
abstract contract ReentrancyGuardTransient {

    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_reentrancyGuardEntered()) revert ReentrancyGuardReentrantCall();

        // Any calls to nonReentrant after this point will fail
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
    }

}

// SPDX-License-Identifier: ISC
pragma solidity >=0.5.0;

interface IUniswapV2Callee {
    function uniswapV2Call(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import { IERC165 } from "./IERC165.sol";
import { IERC20 } from "./IERC20.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {

    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(
        address to,
        uint256 value,
        bytes calldata data
    ) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(
        address from,
        address to,
        uint256 value,
        bytes calldata data
    ) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(
        address spender,
        uint256 value,
        bytes calldata data
    ) external returns (bool);

}

File 33 of 38 : Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {

    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);

}

// 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.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {

    /**
     * @dev UDVT that represent a slot holding a address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(
        bytes32 slot
    ) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(
        bytes32 slot
    ) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(
        bytes32 slot
    ) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(
        bytes32 slot
    ) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(
        bytes32 slot
    ) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(
        AddressSlot slot
    ) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(
        BooleanSlot slot
    ) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(
        Bytes32Slot slot
    ) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(
        Uint256Slot slot
    ) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(
        Int256Slot slot
    ) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

}

File 36 of 38 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import { IERC165 } from "../utils/introspection/IERC165.sol";

File 37 of 38 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

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

// 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.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);

}

Settings
{
  "remappings": [
    "agora-std/=lib/agora-standard-solidity/src/",
    "forge-std/=lib/forge-std/src/",
    "agora-contracts/=node_modules/agora-contracts/src/contracts/",
    "stable-swap/=node_modules/@agora-finance/stable-swap/src/",
    "createx/=node_modules/createx/src/",
    "@interfaces/=src/interfaces/",
    "@utils/=src/utils/",
    "@swap-actions/=src/stable-swap/",
    "@testnet-actions/=src/testnet/",
    "@check-actions/=src/check/",
    "@agora-finance/=node_modules/@agora-finance/",
    "@chainlink/=lib/agora-standard-solidity/node_modules/@chainlink/",
    "@eth-optimism/=lib/agora-standard-solidity/node_modules/@eth-optimism/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "agora-standard-solidity/=lib/agora-standard-solidity/src/",
    "ds-test/=node_modules/ds-test/",
    "openzeppelin/=node_modules/createx/lib/openzeppelin-contracts/contracts/",
    "solady/=node_modules/createx/lib/solady/src/",
    "solidity-bytes-utils/=lib/agora-standard-solidity/node_modules/solidity-bytes-utils/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 100000000
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "none",
    "appendCBOR": false
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "cancun",
  "viaIR": true,
  "libraries": {}
}

Contract Security Audit

Contract ABI

API
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"string","name":"role","type":"string"}],"name":"AddressIsNotRole","type":"error"},{"inputs":[],"name":"CannotRemoveLastManager","type":"error"},{"inputs":[],"name":"DecimalDeltaTooLarge","type":"error"},{"inputs":[],"name":"IdenticalAddresses","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"InvalidTokenOrder","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"PairExists","type":"error"},{"inputs":[],"name":"RoleNameTooLong","type":"error"},{"inputs":[{"internalType":"uint8","name":"bits","type":"uint8"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintDowncast","type":"error"},{"inputs":[],"name":"ZeroAddress","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token0","type":"address"},{"indexed":true,"internalType":"address","name":"token1","type":"address"},{"indexed":false,"internalType":"address","name":"pair","type":"address"}],"name":"PairCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"string","name":"role","type":"string"},{"indexed":true,"internalType":"address","name":"address_","type":"address"}],"name":"RoleAssigned","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"string","name":"role","type":"string"},{"indexed":true,"internalType":"address","name":"address_","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"approvedDeployer","type":"address"},{"indexed":false,"internalType":"bool","name":"isApproved","type":"bool"}],"name":"SetApprovedDeployer","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"initialAdminAddress","type":"address"},{"indexed":false,"internalType":"address","name":"initialWhitelister","type":"address"},{"indexed":false,"internalType":"address","name":"initialFeeSetter","type":"address"},{"indexed":false,"internalType":"address","name":"initialTokenRemover","type":"address"},{"indexed":false,"internalType":"address","name":"initialPauser","type":"address"},{"indexed":false,"internalType":"address","name":"initialPriceSetter","type":"address"},{"indexed":false,"internalType":"address","name":"initialTokenReceiver","type":"address"},{"indexed":false,"internalType":"address","name":"initialFeeReceiver","type":"address"}],"name":"SetDefaultRoles","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token0","type":"address"},{"indexed":true,"internalType":"address","name":"token1","type":"address"},{"indexed":false,"internalType":"address","name":"pair","type":"address"}],"name":"SetPair","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newImplementation","type":"address"}],"name":"SetStableSwapImplementation","type":"event"},{"inputs":[],"name":"ACCESS_CONTROL_MANAGER_ROLE","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AGORA_ACCESS_CONTROL_STORAGE_SLOT","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AGORA_STABLE_SWAP_FACTORY_STORAGE_SLOT","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"APPROVED_DEPLOYER","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"IMPLEMENTATION_SETTER_ROLE","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"allPairs","outputs":[{"internalType":"address[]","name":"_pairs","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_role","type":"string"},{"internalType":"address","name":"_newAddress","type":"address"},{"internalType":"bool","name":"_addRole","type":"bool"}],"name":"assignRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenA","type":"address"},{"internalType":"address","name":"_tokenB","type":"address"}],"name":"computePairDeploymentAddress","outputs":[{"internalType":"address","name":"_pairDeploymentAddress","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"uint256","name":"token0Decimals","type":"uint256"},{"internalType":"uint256","name":"minToken0PurchaseFee","type":"uint256"},{"internalType":"uint256","name":"maxToken0PurchaseFee","type":"uint256"},{"internalType":"uint256","name":"token0PurchaseFee","type":"uint256"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint256","name":"token1Decimals","type":"uint256"},{"internalType":"uint256","name":"minToken1PurchaseFee","type":"uint256"},{"internalType":"uint256","name":"maxToken1PurchaseFee","type":"uint256"},{"internalType":"uint256","name":"token1PurchaseFee","type":"uint256"},{"internalType":"uint256","name":"minBasePrice","type":"uint256"},{"internalType":"uint256","name":"maxBasePrice","type":"uint256"},{"internalType":"uint256","name":"basePrice","type":"uint256"},{"internalType":"int256","name":"minAnnualizedInterestRate","type":"int256"},{"internalType":"int256","name":"maxAnnualizedInterestRate","type":"int256"},{"internalType":"int256","name":"annualizedInterestRate","type":"int256"}],"internalType":"struct AgoraStableSwapFactory.CreatePairArgs","name":"_pairArgs","type":"tuple"}],"name":"createPair","outputs":[{"internalType":"address","name":"pair","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getAgoraStableSwapDefaultParamsStorage","outputs":[{"components":[{"internalType":"address","name":"initialDefaultAdminAddress","type":"address"},{"internalType":"address","name":"initialDefaultWhitelister","type":"address"},{"internalType":"address","name":"initialDefaultFeeSetter","type":"address"},{"internalType":"address","name":"initialDefaultTokenRemover","type":"address"},{"internalType":"address","name":"initialDefaultPauser","type":"address"},{"internalType":"address","name":"initialDefaultPriceSetter","type":"address"},{"internalType":"address","name":"initialDefaultTokenReceiver","type":"address"},{"internalType":"address","name":"initialDefaultFeeReceiver","type":"address"}],"internalType":"struct AgoraStableSwapFactory.AgoraStableSwapDefaultParamsStorage","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAllPairData","outputs":[{"components":[{"internalType":"address","name":"pairAddress","type":"address"},{"components":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"uint256","name":"decimals","type":"uint256"}],"internalType":"struct AgoraStableSwapFactory.TokenInfo","name":"token0","type":"tuple"},{"components":[{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"uint256","name":"decimals","type":"uint256"}],"internalType":"struct AgoraStableSwapFactory.TokenInfo","name":"token1","type":"tuple"}],"internalType":"struct AgoraStableSwapFactory.PairData[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getAllRoles","outputs":[{"internalType":"string[]","name":"_roles","type":"string[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"}],"name":"getPairFromTokens","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_role","type":"string"}],"name":"getRoleMembers","outputs":[{"internalType":"address[]","name":"_members","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_role","type":"string"},{"internalType":"address","name":"_address","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"implementationAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"initialStableSwapImplementation","type":"address"},{"internalType":"address","name":"initialStableSwapProxyAdminAddress","type":"address"},{"internalType":"address","name":"initialFactoryAccessControlManager","type":"address"},{"internalType":"address","name":"initialImplementationSetter","type":"address"},{"internalType":"address[]","name":"initialApprovedDeployers","type":"address[]"},{"internalType":"address","name":"initialDefaultAdminAddress","type":"address"},{"internalType":"address","name":"initialDefaultWhitelister","type":"address"},{"internalType":"address","name":"initialDefaultFeeSetter","type":"address"},{"internalType":"address","name":"initialDefaultTokenRemover","type":"address"},{"internalType":"address","name":"initialDefaultPauser","type":"address"},{"internalType":"address","name":"initialDefaultPriceSetter","type":"address"},{"internalType":"address","name":"initialDefaultTokenReceiver","type":"address"},{"internalType":"address","name":"initialDefaultFeeReceiver","type":"address"}],"internalType":"struct InitializeParams","name":"_params","type":"tuple"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"proxyAdminAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"_approvedDeployers","type":"address[]"},{"internalType":"bool","name":"_setApproved","type":"bool"}],"name":"setApprovedDeployers","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_initialAdminAddress","type":"address"},{"internalType":"address","name":"_initialWhitelister","type":"address"},{"internalType":"address","name":"_initialFeeSetter","type":"address"},{"internalType":"address","name":"_initialTokenRemover","type":"address"},{"internalType":"address","name":"_initialPauser","type":"address"},{"internalType":"address","name":"_initialPriceSetter","type":"address"},{"internalType":"address","name":"_initialTokenReceiver","type":"address"},{"internalType":"address","name":"_initialFeeReceiver","type":"address"}],"name":"setDefaultRoles","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenA","type":"address"},{"internalType":"address","name":"_tokenB","type":"address"},{"internalType":"address","name":"_pairAddress","type":"address"}],"name":"setPair","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newImplementation","type":"address"}],"name":"setStableSwapImplementation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tokenA","type":"address"},{"internalType":"address","name":"_tokenB","type":"address"}],"name":"sortTokens","outputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"stableSwapImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"stableSwapProxyAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"components":[{"internalType":"uint256","name":"major","type":"uint256"},{"internalType":"uint256","name":"minor","type":"uint256"},{"internalType":"uint256","name":"patch","type":"uint256"}],"internalType":"struct AgoraStableSwapFactory.Version","name":"_version","type":"tuple"}],"stateMutability":"pure","type":"function"}]

0x6080806040523460aa575f5160206149925f395f51905f525460ff8160401c16609b576002600160401b03196001600160401b038216016049575b6040516148e390816100af8239f35b6001600160401b0319166001600160401b039081175f5160206149925f395f51905f525581527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a15f80603a565b63f92ee8a960e01b5f5260045ffd5b5f80fdfe6102006040526004361015610012575f80fd5b5f3560e01c806306fdde0314612b17578063084f390014612a505780631fac103414612a175780632c387260146129a75780633a9a676e146128b65780633ca687aa14611b8b578063414c5f5014611b525780634592d72314611abb578063544caa5614611a4b57806354fd4d50146119cd5780635979e7551461195d57806359e98b0f146118ed5780636c9cd0971461185357806371f15594146118065780637bb41012146115c05780637f43cb49146114e45780638ef6fb93146113ec5780639ec28c69146113ab578063ad9132d614610dcc578063b97a231914610d5c578063bc78480c14610772578063bebcab561461071a578063c97682f81461063a578063d86fb4ff14610478578063d86fe00614610420578063e1349f811461033c5763f2bcac3d14610143575f80fd5b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338577f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b0005461019c81612eb3565b906101aa6040519283612cf2565b8082527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe06101d782612eb3565b015f5b8181106103275750507f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b000545f5b82811061029157836040518091602082016020835281518091526040830190602060408260051b8601019301915f905b82821061024657505050500390f35b91936020610281827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc060019597998495030186528851612b90565b9601920192018594939192610237565b818110156102fa576001907f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b0005f528060205f200154604051906020820152602081526102de604082612cf2565b6102e882876133fb565b526102f381866133fb565b5001610207565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b8060606020809387010152016101da565b5f80fd5b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338575f60e060405161037981612cd5565b8281528260208201528260408201528260608201528260808201528260a08201528260c082015201526101006103ad61355f565b73ffffffffffffffffffffffffffffffffffffffff60e0604051928281511684528260208201511660208501528260408201511660408501528260608201511660608501528260808201511660808501528260a08201511660a08501528260c08201511660c085015201511660e0820152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760206040517f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300008152f35b346103385760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338576104af612bd3565b6104b7612bf6565b73ffffffffffffffffffffffffffffffffffffffff811673ffffffffffffffffffffffffffffffffffffffff831614610612576104f391612fef565b73ffffffffffffffffffffffffffffffffffffffff8216156105ea576105189161392b565b6040516020810191308352604082015260408152610537606082612cf2565b519020604051907f6cec2536000000000000000000000000000000000000000000000000000000008252600482015260208160248173ba5ed099633d3b313e4d5f7bdc1305d3c28ba5ed5afa80156105df576020915f916105b2575b5073ffffffffffffffffffffffffffffffffffffffff60405191168152f35b6105d29150823d84116105d8575b6105ca8183612cf2565b810190612fc3565b82610593565b503d6105c0565b6040513d5f823e3d90fd5b7fd92e233d000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fbd969eb0000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338576040518060207f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000549182815201907f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300005f527f4c1034e5f5a5b72625c3d988d8ed606ce3febbe9cf91c5cf145ba7ecb6abb175905f5b81811061070457610700856106f481870382612cf2565b60405191829182612e29565b0390f35b82548452602090930192600192830192016106dd565b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760206040517f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b0008152f35b346103385760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760043567ffffffffffffffff8111610338576101a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8236030112610338576040516101a0810181811067ffffffffffffffff821117610d2f5760405261080a82600401612c5f565b815261081860248301612c5f565b906020810191825261082c60448401612c5f565b6040820190815261083f60648501612c5f565b9260608301938452608485013567ffffffffffffffff81116103385761086b9060043691880101612ecb565b906080840191825261087f60a48701612c5f565b9560a0850196875261089360c48201612c5f565b9260c086019384526108a760e48301612c5f565b60e087019081526108bb6101048401612c5f565b61010088019081526108d06101248501612c5f565b9161012089019283526108e66101448601612c5f565b936101408a019485526109116101846109026101648901612c5f565b976101608d0198895201612c5f565b966101808b019788527ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00549060ff8260401c16159b8c67ffffffffffffffff841680159182610d27575b506001149081610d1d575b159081610d14575b50610cec5773ffffffffffffffffffffffffffffffffffffffff8092818f8f9096610ad49760017fffffffffffffffffffffffffffffffffffffffffffffffff00000000000000008316177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0055610c97575b5051166109f36109ee612dee565b6139cd565b610a0c81610a07610a02612dee565b612f85565b613d15565b50610a1d610a18612dee565b6137c1565b7f1cf4c2f10398d18e27c3336eeadbf9ce9571462b7cb30d5d9a4024580f208d215f80a351167fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300045416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000455610abc610ab5612dee565b33906137dd565b610acd33610ac8612e78565b6137dd565b511661340f565b610ae533610ae0612e78565b61384c565b519a610af833610af3612dee565b613754565b5f5b8c51811015610b77578073ffffffffffffffffffffffffffffffffffffffff610b458f93600194610b4086610b2d612d6d565b86610b3886866133fb565b5116906138a8565b6133fb565b51167f45778bebc2e4105030facdf86798167629ba9a2c604e64bc382465e5cda65cd36020604051858152a201610afa565b5073ffffffffffffffffffffffffffffffffffffffff80808080610bce9d9e9f818097610bb1829383610ba8612e78565b915116906137dd565b51169d51169651169651169651169651169651169651169661302b565b73ffffffffffffffffffffffffffffffffffffffff3391511603610c86575b610bf357005b7fffffffffffffffffffffffffffffffffffffffffffffff00ffffffffffffffff7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054167ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00557fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2602060405160018152a1005b610c9233610ae0612dee565b610bed565b7fffffffffffffffffffffffffffffffffffffffffffffff0000000000000000001668010000000000000001177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00555f6109e0565b7ff92ee8a9000000000000000000000000000000000000000000000000000000005f5260045ffd5b9050155f61096e565b303b159150610966565b91508e61095b565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857602073ffffffffffffffffffffffffffffffffffffffff7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416604051908152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857604051808160207f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300005492838152017f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300005f527f4c1034e5f5a5b72625c3d988d8ed606ce3febbe9cf91c5cf145ba7ecb6abb175925f5b818110611392575050610e8492500382612cf2565b8051907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0610eca610eb484612eb3565b93610ec26040519586612cf2565b808552612eb3565b015f5b81811061135b5750505f5b81518110156112985773ffffffffffffffffffffffffffffffffffffffff610f0082846133fb565b5116906040517f0dfe1681000000000000000000000000000000000000000000000000000000008152602081600481865afa80156105df5773ffffffffffffffffffffffffffffffffffffffff915f9161127a575b5016916040517fd21220a7000000000000000000000000000000000000000000000000000000008152602081600481855afa80156105df5773ffffffffffffffffffffffffffffffffffffffff915f9161125c575b50166040517f06fdde030000000000000000000000000000000000000000000000000000000081525f81600481885afa9081156105df575f91611242575b506040517f313ce567000000000000000000000000000000000000000000000000000000008152602081600481895afa9081156105df575f91611224575b50604051917f95d89b410000000000000000000000000000000000000000000000000000000083525f836004818a5afa9081156105df5760ff935f92611208575b506040519761107589612cb9565b885260208801526040870152166060850152604051937f06fdde030000000000000000000000000000000000000000000000000000000085525f85600481855afa9485156105df575f956111ec575b506040517f313ce567000000000000000000000000000000000000000000000000000000008152602081600481865afa9081156105df575f916111be575b50604051907f95d89b410000000000000000000000000000000000000000000000000000000082525f82600481875afa80156105df5760019760ff935f9261119a575b506040519561115387612cb9565b8652602086015260408501521660608301526040519261117284612c9d565b83526020830152604082015261118882866133fb565b5261119381856133fb565b5001610ed8565b6111b79192503d805f833e6111af8183612cf2565b8101906134e3565b908b611145565b6111df915060203d81116111e5575b6111d78183612cf2565b810190613546565b88611102565b503d6111cd565b6112019195503d805f833e6111af8183612cf2565b93876110c4565b61121d9192503d805f833e6111af8183612cf2565b908a611067565b61123c915060203d81116111e5576111d78183612cf2565b88611026565b61125691503d805f833e6111af8183612cf2565b87610fe8565b611274915060203d81116105d8576105ca8183612cf2565b87610faa565b611292915060203d81116105d8576105ca8183612cf2565b86610f55565b826040518091602082016020835281518091526040830190602060408260051b8601019301915f905b8282106112d057505050500390f35b9193602061134b827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc0600195979984950301865288519073ffffffffffffffffffffffffffffffffffffffff8251168152604061133a858401516060878501526060840190612f30565b920151906040818403910152612f30565b96019201920185949391926112c1565b60209060405161136a81612c9d565b5f81526113756134bf565b838201526113816134bf565b604082015282828701015201610ecd565b8454835260019485019486945060209093019201610e6f565b346103385760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338576113ea6113e5612bd3565b61340f565b005b346103385760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760043567ffffffffffffffff81116103385761143b903690600401612ecb565b6024358015158082036103385761145a611453612dee565b3390613754565b5f5b83518110156113ea5760019061149384611474612d6d565b73ffffffffffffffffffffffffffffffffffffffff610b38858a6133fb565b73ffffffffffffffffffffffffffffffffffffffff6114b282876133fb565b51167f45778bebc2e4105030facdf86798167629ba9a2c604e64bc382465e5cda65cd36020604051868152a20161145c565b34610338576101007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385761151c612bd3565b611524612bf6565b61152c612c3c565b60643573ffffffffffffffffffffffffffffffffffffffff811681036103385760843573ffffffffffffffffffffffffffffffffffffffff8116810361033857611574612c19565b9160c4359373ffffffffffffffffffffffffffffffffffffffff851685036103385760e4359573ffffffffffffffffffffffffffffffffffffffff87168703610338576113ea9761302b565b346103385760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338576115f7612bd3565b6115ff612bf6565b611607612c3c565b91611613611453612dee565b73ffffffffffffffffffffffffffffffffffffffff821673ffffffffffffffffffffffffffffffffffffffff82161461061257602073ffffffffffffffffffffffffffffffffffffffff8061168a81957fddf4d71d71bf025a98b6e669ba890608b8ac62636f9396f3608c5946f6eef6d795612fef565b959096169485155f146117f7576116de8773ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b8282165f5284526116f48260405f205416613d6d565b505b61173d8773ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b8282165f52845260405f20867fffffffffffffffffffffffff00000000000000000000000000000000000000008254161790556117b78173ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b8288165f52845260405f20867fffffffffffffffffffffffff000000000000000000000000000000000000000082541617905560405195865216941692a3005b61180086613abd565b506116f6565b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385761070061183f612e78565b604051918291602083526020830190612b90565b346103385760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760043567ffffffffffffffff8111610338576118e36118a76020923690600401612da8565b73ffffffffffffffffffffffffffffffffffffffff6118cd6118c7612bf6565b92612f85565b9116906001915f520160205260405f2054151590565b6040519015158152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857602073ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300045416604051908152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857602073ffffffffffffffffffffffffffffffffffffffff7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035416604051908152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338575f60408051611a0981612c9d565b82815282602082015201526060604051611a2281612c9d565b600281526040602082019160028352015f81526040519160028352516020830152516040820152f35b346103385760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857604073ffffffffffffffffffffffffffffffffffffffff611aaa611a9c612bd3565b611aa4612bf6565b90612fef565b835191831682529091166020820152f35b346103385760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760043567ffffffffffffffff811161033857610a02611b0d913690600401612da8565b6040519081602082549182815201915f5260205f20905f5b818110611b3c57610700856106f481870382612cf2565b8254845260209093019260019283019201611b25565b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385761070061183f612dee565b34610338576102007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338576040516101e0526102006101e051016101e051811067ffffffffffffffff821117610d2f57604052611beb612bd3565b6101e0515260243560206101e051015260443560406101e051015260643560606101e051015260843560806101e0510152611c24612c19565b60a06101e051015260c43560c06101e051015260e43560e06101e0510152610104356101006101e0510152610124356101206101e0510152610144356101406101e0510152610164356101606101e0510152610184356101806101e05101526101a4356101a06101e05101526101c4356101c06101e05101526101e4356101e080510152611cb3611453612d6d565b73ffffffffffffffffffffffffffffffffffffffff6101e051511673ffffffffffffffffffffffffffffffffffffffff60a06101e051015116146106125773ffffffffffffffffffffffffffffffffffffffff6101e051511673ffffffffffffffffffffffffffffffffffffffff611d348160a06101e05101511683612fef565b501690810361288e57156105ea5773ffffffffffffffffffffffffffffffffffffffff6101e051511673ffffffffffffffffffffffffffffffffffffffff611dc38160a06101e0510151169273ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b91165f5260205273ffffffffffffffffffffffffffffffffffffffff60405f2054166128665760206101e051015160c06101e051015190600c820180921161283957118015612816575b6127ee57604051611e1d81612c80565b5f8152602081015f9052604081015f9052606081015f9052608081015f905260a081015f905260c081015f905260e081015f905261010081015f905261012081015f905261014081015f905261016081015f905261018081015f90526101a081015f90526101c081015f90526101e081015f905261020081015f905261022081015f905261024081015f905261026081015f905261028081015f90526102a081015f90526102c081015f90526102e0015f9052611ed861355f565b806101e0515173ffffffffffffffffffffffffffffffffffffffff166101e05160200151611f0590613a6a565b610100526101e05160a081015173ffffffffffffffffffffffffffffffffffffffff166101405260c00151611f3990613a6a565b6101e051604001516101e051606001516101e05160e001516101e05161010001516101e05160800151906101e051610120015192885173ffffffffffffffffffffffffffffffffffffffff169460208a015173ffffffffffffffffffffffffffffffffffffffff169660408b015173ffffffffffffffffffffffffffffffffffffffff169860608c015173ffffffffffffffffffffffffffffffffffffffff169a60808d015173ffffffffffffffffffffffffffffffffffffffff169c60a0015173ffffffffffffffffffffffffffffffffffffffff169d60c081015173ffffffffffffffffffffffffffffffffffffffff1660805260e0015173ffffffffffffffffffffffffffffffffffffffff1660c0526101e05161014001516101c0526101e05161016001516101a0526101e0516101a00151610180526101e0516101c00151610160526101e0516101800151610120526101e0516101e0015160e05260405160a05260a0516120ab90612c80565b60a051526101005160ff1660a051602001526101405160a0516040015260ff1660a0516060015260a0516080015260a05160a0015260a05160c0015260a05160e0015260a051610100015260a051610120015260a051610140015260a051610160015260a051610180015260a0516101a0015260a0516101c0015260a0516101e0015260805160a051610200015260c05160a05161022001526101c05160a05161024001526101a05160a05161026001526101805160a05161028001526101605160a0516102a001526101205160a0516102c0015260e05160a0516102e00152604051602081017f54ea8e0100000000000000000000000000000000000000000000000000000000905260a0515173ffffffffffffffffffffffffffffffffffffffff16602482015260a0516020015160ff16604482015260a0516040015173ffffffffffffffffffffffffffffffffffffffff16606482015260a0516060015160ff16608482015260a0516080015160a482015260a05160a0015160c482015260a05160c0015160e482015260a05160e0015161010482015260a051610100015161012482015260a051610120015161014482015260a051610140015173ffffffffffffffffffffffffffffffffffffffff1661016482015260a051610160015173ffffffffffffffffffffffffffffffffffffffff1661018482015260a051610180015173ffffffffffffffffffffffffffffffffffffffff166101a482015260a0516101a0015173ffffffffffffffffffffffffffffffffffffffff166101c482015260a0516101c0015173ffffffffffffffffffffffffffffffffffffffff166101e482015260a0516101e0015173ffffffffffffffffffffffffffffffffffffffff1661020482015260a051610200015173ffffffffffffffffffffffffffffffffffffffff1661022482015260a051610220015173ffffffffffffffffffffffffffffffffffffffff1661024482015260a051610240015161026482015260a051610260015161028482015260a05161028001516102a482015260a0516102a001516102c482015260a0516102c001516102e482015260a0516102e0015161030482015261030481526123e661032482612cf2565b7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300035473ffffffffffffffffffffffffffffffffffffffff16907f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300045473ffffffffffffffffffffffffffffffffffffffff166040519261246484612c9d565b835260208301908152604083019182526040519182916020830194602086525173ffffffffffffffffffffffffffffffffffffffff1660408401525173ffffffffffffffffffffffffffffffffffffffff16606083015251608082016060905260a082016124d191612b90565b037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0810182526125019082612cf2565b6107df9160405191602084016125179084612cf2565b83835260208301936141048539604051938493518091602086015e83019060208201905f8252519283915e016020015f8152037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0810182526125799082612cf2565b6101e0515173ffffffffffffffffffffffffffffffffffffffff166101e05160a0015173ffffffffffffffffffffffffffffffffffffffff166125bb9161392b565b60405180809381937f9c36a286000000000000000000000000000000000000000000000000000000008352600483015260248201604090526044820161260091612b90565b035a925f73ba5ed099633d3b313e4d5f7bdc1305d3c28ba5ed602095f19081156105df5760209173ffffffffffffffffffffffffffffffffffffffff915f916127d1575b50612692826101e051511673ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b828060a06101e051015116165f52835260405f208282167fffffffffffffffffffffffff00000000000000000000000000000000000000008254161790556127208260a06101e05101511673ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b82806101e0515116165f52835260405f208282167fffffffffffffffffffffffff00000000000000000000000000000000000000008254161790551661276581613abd565b5073ffffffffffffffffffffffffffffffffffffffff6101e051511673ffffffffffffffffffffffffffffffffffffffff60a06101e051015116907fa92a2b95c8d8436f6ac4c673c61487364f877efb9534d4296fad8ef904546c9484604051858152a3604051908152f35b6127e89150833d85116105d8576105ca8183612cf2565b83612644565b7f402470ee000000000000000000000000000000000000000000000000000000005f5260045ffd5b5060c06101e051015160206101e051015190600c82018092116128395711611e0d565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b7f3d77e891000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f3f06bf81000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103385760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760043567ffffffffffffffff811161033857612905903690600401612da8565b61290d612bf6565b60443580151581036103385761292e91612928611453612dee565b836138a8565b8051612938612dee565b51149081612988575b81612976575b5061294e57005b7f3cba491a000000000000000000000000000000000000000000000000000000005f5260045ffd5b6129809150612f85565b541581612947565b809150516020820120612999612dee565b602081519101201490612941565b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857602073ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300035416604051908152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385761070061183f612d6d565b346103385760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857612a87612bd3565b73ffffffffffffffffffffffffffffffffffffffff612aeb612aa7612bf6565b9273ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b91165f52602052602073ffffffffffffffffffffffffffffffffffffffff60405f205416604051908152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857610700604051612b56604082612cf2565b601681527f41676f7261537461626c6553776170466163746f72790000000000000000000060208201526040519182916020835260208301905b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f602080948051918291828752018686015e5f8582860101520116010190565b6004359073ffffffffffffffffffffffffffffffffffffffff8216820361033857565b6024359073ffffffffffffffffffffffffffffffffffffffff8216820361033857565b60a4359073ffffffffffffffffffffffffffffffffffffffff8216820361033857565b6044359073ffffffffffffffffffffffffffffffffffffffff8216820361033857565b359073ffffffffffffffffffffffffffffffffffffffff8216820361033857565b610300810190811067ffffffffffffffff821117610d2f57604052565b6060810190811067ffffffffffffffff821117610d2f57604052565b6080810190811067ffffffffffffffff821117610d2f57604052565b610100810190811067ffffffffffffffff821117610d2f57604052565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff821117610d2f57604052565b67ffffffffffffffff8111610d2f57601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b60405190612d7c604083612cf2565b601182527f415050524f5645445f4445504c4f5945520000000000000000000000000000006020830152565b81601f8201121561033857803590612dbf82612d33565b92612dcd6040519485612cf2565b8284526020838301011161033857815f926020809301838601378301015290565b60405190612dfd604083612cf2565b601b82527f4143434553535f434f4e54524f4c5f4d414e414745525f524f4c4500000000006020830152565b60206040818301928281528451809452019201905f5b818110612e4c5750505090565b825173ffffffffffffffffffffffffffffffffffffffff16845260209384019390920191600101612e3f565b60405190612e87604083612cf2565b601a82527f494d504c454d454e544154494f4e5f5345545445525f524f4c450000000000006020830152565b67ffffffffffffffff8111610d2f5760051b60200190565b9080601f83011215610338578135612ee281612eb3565b92612ef06040519485612cf2565b81845260208085019260051b82010192831161033857602001905b828210612f185750505090565b60208091612f2584612c5f565b815201910190612f0b565b9073ffffffffffffffffffffffffffffffffffffffff8251168152606080612f7c612f6a6020860151608060208701526080860190612b90565b60408601518582036040870152612b90565b93015191015290565b60208091604051928184925191829101835e81017f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b00281520301902090565b90816020910312610338575173ffffffffffffffffffffffffffffffffffffffff811681036103385790565b73ffffffffffffffffffffffffffffffffffffffff821673ffffffffffffffffffffffffffffffffffffffff8216105f146130275791565b9091565b937f0bbb5d7eaea3e2cfc663c9f1b7e468eff9c394543e1d3abad73b2d6ad08553ba979373ffffffffffffffffffffffffffffffffffffffff808080808080806101009f9b9d9e9a9e61307f611453612dee565b169d8e7fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300055416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000555169b8c7fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300065416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630006551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300075416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630007551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300085416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630008551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300095416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630009551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000a5416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000a551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000b5416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000b551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000c5416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000c55604051978852602088015260408701526060860152608085015260a084015260c083015260e0820152a1565b80518210156102fa5760209160051b010190565b73ffffffffffffffffffffffffffffffffffffffff90613430611453612e78565b16807fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300035416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630003557f132d6ae8f04c23470c6742ffb48b6dbb7ea6e541578deb9ebc5fca598998a14b5f80a2565b604051906134cc82612cb9565b5f6060838281528160208201528160408201520152565b6020818303126103385780519067ffffffffffffffff8211610338570181601f820112156103385780519061351782612d33565b926135256040519485612cf2565b8284526020838301011161033857815f9260208093018386015e8301015290565b90816020910312610338575160ff811681036103385790565b6040519061356c82612cd5565b8173ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300055416815273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300065416602082015273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300075416604082015273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300085416606082015273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300095416608082015273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000a541660a082015273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000b541660c082015260e073ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000c5416910152565b906137779073ffffffffffffffffffffffffffffffffffffffff6118cd84612f85565b1561377f5750565b6137bd906040519182917fc13dd0f3000000000000000000000000000000000000000000000000000000008352602060048401526024830190612b90565b0390fd5b602090604051918183925191829101835e81015f815203902090565b61381a73ffffffffffffffffffffffffffffffffffffffff916137ff816139cd565b61381461380b82612f85565b84861690613d15565b506137c1565b9116907f1cf4c2f10398d18e27c3336eeadbf9ce9571462b7cb30d5d9a4024580f208d215f80a3565b84861690613fd7565b61387373ffffffffffffffffffffffffffffffffffffffff9161386e816139cd565b61389c565b9116907f1e5d48c75f77ab7fd581247d777530d4e8c18432289e14017ba995532f6ca1cf5f80a3565b61381461384382612f85565b73ffffffffffffffffffffffffffffffffffffffff91926138c8826139cd565b6138d3818584613a12565b156138e15761381a906137c1565b613873906137c1565b6020815191015190602081106138fe575090565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9060200360031b1b1690565b7fffffffffffffffffffffff000000000000000000000000000000000000000000906139ca927fffffffffffffffffffffffffffffffffffffffff0000000000000000000000006040519181602084019460601b16845260601b1660348201526028815261399a604882612cf2565b51902016604051903060601b60208301525f60348301526035820152602081526139c5604082612cf2565b6138ea565b90565b60208151116139ea576139e26139e7916138ea565b613c06565b50565b7f37d8d209000000000000000000000000000000000000000000000000000000005f5260045ffd5b9115613a415773ffffffffffffffffffffffffffffffffffffffff613a396139e793612f85565b911690613d15565b73ffffffffffffffffffffffffffffffffffffffff613a626139e793612f85565b911690613fd7565b60ff8111613a785760ff1690565b7f6dfcc650000000000000000000000000000000000000000000000000000000005f52600860045260245260445ffd5b80548210156102fa575f5260205f2001905f90565b805f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000160205260405f2054155f14613c01577f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300005468010000000000000000811015610d2f57613bac613b778260018594017f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000557f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000613aa8565b81939154907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9060031b92831b921b19161790565b90557f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000054905f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000160205260405f2055600190565b505f90565b805f527f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b00160205260405f2054155f14613c01577f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b0005468010000000000000000811015610d2f57613cc0613b778260018594017f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b000557f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b000613aa8565b90557f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b00054905f527f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b00160205260405f2055600190565b5f828152600182016020526040902054613d675780549068010000000000000000821015610d2f5782613d52613b77846001809601855584613aa8565b90558054925f520160205260405f2055600190565b50505f90565b5f8181527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000160205260409020548015613d67577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8101818111612839577f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000054907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820191821161283957818103613f42575b5050507f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000548015613f15577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01613e96817f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000613aa8565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82549160031b1b191690557f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000555f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300016020525f6040812055600190565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603160045260245ffd5b613fa2613f72613b77937f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000613aa8565b90549060031b1c9283927f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000613aa8565b90555f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000160205260405f20555f8080613e1f565b906001820191815f528260205260405f20548015155f146140fb577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8101818111612839578254907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8201918211612839578181036140c6575b50505080548015613f15577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01906140898282613aa8565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82549160031b1b19169055555f526020525f6040812055600190565b6140e66140d6613b779386613aa8565b90549060031b1c92839286613aa8565b90555f528360205260405f20555f8080614051565b505050505f9056fe60806040526107df8038038061001481610279565b928339810190602081830312610261578051906001600160401b03821161026157016060818303126102615760405190606082016001600160401b03811183821017610265576040526100668161029e565b82526100746020820161029e565b60208301908152604082015190916001600160401b038211610261570183601f82011215610261578051906100b06100ab836102b2565b610279565b948286526020838301011161026157815f9260208093018388015e85010152604082810193845290515f80546001600160a01b0319166001600160a01b039283169081179091555f5160206107bf5f395f51905f52548351928116835260208301829052909290917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f9190a1811561024e576001600160a01b031916175f5160206107bf5f395f51905f5255516001600160a01b0316908161017c575b604051610493908161032c8239f35b5190803b1561023c577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b03191682179055807fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115610225575f8083602061021495519101845af43d1561021d573d916102056100ab846102b2565b9283523d5f602085013e6102cd565b505b5f8061016d565b6060916102cd565b505034156102165763b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b633173bdd160e11b5f525f60045260245ffd5b5f80fd5b634e487b7160e01b5f52604160045260245ffd5b6040519190601f01601f191682016001600160401b0381118382101761026557604052565b51906001600160a01b038216820361026157565b6001600160401b03811161026557601f01601f191660200190565b906102f157508051156102e257805190602001fd5b63d6bda27560e01b5f5260045ffd5b81511580610322575b610302575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b156102fa56fe608060405273ffffffffffffffffffffffffffffffffffffffff5f541633145f146100cc575f357fffffffff00000000000000000000000000000000000000000000000000000000167f4f1ef2860000000000000000000000000000000000000000000000000000000014610096577fd2b576ec000000000000000000000000000000000000000000000000000000005f5260045ffd5b6100ca73ffffffffffffffffffffffffffffffffffffffff6100c36100bb3636610120565b81019061020d565b9116610290565b005b5f8073ffffffffffffffffffffffffffffffffffffffff7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416368280378136915af43d5f803e1561011c573d5ff35b3d5ffd5b91909182600411610159578211610159577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc6004920190565b5f80fd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f604051930116820182811067ffffffffffffffff8211176101ce57604052565b61015d565b67ffffffffffffffff81116101ce57601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b919060408382031261015957823573ffffffffffffffffffffffffffffffffffffffff81168103610159579260208101359067ffffffffffffffff8211610159570181601f820112156101595780359061026e610269836101d3565b61018a565b928284526020838301011161015957815f926020809301838601378301015290565b90813b1561037f5773ffffffffffffffffffffffffffffffffffffffff8216807fffffffffffffffffffffffff00000000000000000000000000000000000000007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416177f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a280511561034e5761034b916103c1565b50565b50503461035757565b7fb398979f000000000000000000000000000000000000000000000000000000005f5260045ffd5b73ffffffffffffffffffffffffffffffffffffffff827f4c9c8ce3000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b5f806103f393602081519101845af43d156103f6573d916103e4610269846101d3565b9283523d5f602085013e6103fa565b90565b6060915b90610437575080511561040f57805190602001fd5b7fd6bda275000000000000000000000000000000000000000000000000000000005f5260045ffd5b8151158061048a575b610448575090565b73ffffffffffffffffffffffffffffffffffffffff907f9996b315000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b50803b1561044056b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00

Deployed Bytecode

0x6102006040526004361015610012575f80fd5b5f3560e01c806306fdde0314612b17578063084f390014612a505780631fac103414612a175780632c387260146129a75780633a9a676e146128b65780633ca687aa14611b8b578063414c5f5014611b525780634592d72314611abb578063544caa5614611a4b57806354fd4d50146119cd5780635979e7551461195d57806359e98b0f146118ed5780636c9cd0971461185357806371f15594146118065780637bb41012146115c05780637f43cb49146114e45780638ef6fb93146113ec5780639ec28c69146113ab578063ad9132d614610dcc578063b97a231914610d5c578063bc78480c14610772578063bebcab561461071a578063c97682f81461063a578063d86fb4ff14610478578063d86fe00614610420578063e1349f811461033c5763f2bcac3d14610143575f80fd5b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338577f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b0005461019c81612eb3565b906101aa6040519283612cf2565b8082527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe06101d782612eb3565b015f5b8181106103275750507f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b000545f5b82811061029157836040518091602082016020835281518091526040830190602060408260051b8601019301915f905b82821061024657505050500390f35b91936020610281827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc060019597998495030186528851612b90565b9601920192018594939192610237565b818110156102fa576001907f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b0005f528060205f200154604051906020820152602081526102de604082612cf2565b6102e882876133fb565b526102f381866133fb565b5001610207565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b8060606020809387010152016101da565b5f80fd5b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338575f60e060405161037981612cd5565b8281528260208201528260408201528260608201528260808201528260a08201528260c082015201526101006103ad61355f565b73ffffffffffffffffffffffffffffffffffffffff60e0604051928281511684528260208201511660208501528260408201511660408501528260608201511660608501528260808201511660808501528260a08201511660a08501528260c08201511660c085015201511660e0820152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760206040517f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300008152f35b346103385760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338576104af612bd3565b6104b7612bf6565b73ffffffffffffffffffffffffffffffffffffffff811673ffffffffffffffffffffffffffffffffffffffff831614610612576104f391612fef565b73ffffffffffffffffffffffffffffffffffffffff8216156105ea576105189161392b565b6040516020810191308352604082015260408152610537606082612cf2565b519020604051907f6cec2536000000000000000000000000000000000000000000000000000000008252600482015260208160248173ba5ed099633d3b313e4d5f7bdc1305d3c28ba5ed5afa80156105df576020915f916105b2575b5073ffffffffffffffffffffffffffffffffffffffff60405191168152f35b6105d29150823d84116105d8575b6105ca8183612cf2565b810190612fc3565b82610593565b503d6105c0565b6040513d5f823e3d90fd5b7fd92e233d000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fbd969eb0000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338576040518060207f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000549182815201907f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300005f527f4c1034e5f5a5b72625c3d988d8ed606ce3febbe9cf91c5cf145ba7ecb6abb175905f5b81811061070457610700856106f481870382612cf2565b60405191829182612e29565b0390f35b82548452602090930192600192830192016106dd565b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760206040517f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b0008152f35b346103385760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760043567ffffffffffffffff8111610338576101a07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc8236030112610338576040516101a0810181811067ffffffffffffffff821117610d2f5760405261080a82600401612c5f565b815261081860248301612c5f565b906020810191825261082c60448401612c5f565b6040820190815261083f60648501612c5f565b9260608301938452608485013567ffffffffffffffff81116103385761086b9060043691880101612ecb565b906080840191825261087f60a48701612c5f565b9560a0850196875261089360c48201612c5f565b9260c086019384526108a760e48301612c5f565b60e087019081526108bb6101048401612c5f565b61010088019081526108d06101248501612c5f565b9161012089019283526108e66101448601612c5f565b936101408a019485526109116101846109026101648901612c5f565b976101608d0198895201612c5f565b966101808b019788527ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00549060ff8260401c16159b8c67ffffffffffffffff841680159182610d27575b506001149081610d1d575b159081610d14575b50610cec5773ffffffffffffffffffffffffffffffffffffffff8092818f8f9096610ad49760017fffffffffffffffffffffffffffffffffffffffffffffffff00000000000000008316177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0055610c97575b5051166109f36109ee612dee565b6139cd565b610a0c81610a07610a02612dee565b612f85565b613d15565b50610a1d610a18612dee565b6137c1565b7f1cf4c2f10398d18e27c3336eeadbf9ce9571462b7cb30d5d9a4024580f208d215f80a351167fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300045416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000455610abc610ab5612dee565b33906137dd565b610acd33610ac8612e78565b6137dd565b511661340f565b610ae533610ae0612e78565b61384c565b519a610af833610af3612dee565b613754565b5f5b8c51811015610b77578073ffffffffffffffffffffffffffffffffffffffff610b458f93600194610b4086610b2d612d6d565b86610b3886866133fb565b5116906138a8565b6133fb565b51167f45778bebc2e4105030facdf86798167629ba9a2c604e64bc382465e5cda65cd36020604051858152a201610afa565b5073ffffffffffffffffffffffffffffffffffffffff80808080610bce9d9e9f818097610bb1829383610ba8612e78565b915116906137dd565b51169d51169651169651169651169651169651169651169661302b565b73ffffffffffffffffffffffffffffffffffffffff3391511603610c86575b610bf357005b7fffffffffffffffffffffffffffffffffffffffffffffff00ffffffffffffffff7ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a0054167ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00557fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2602060405160018152a1005b610c9233610ae0612dee565b610bed565b7fffffffffffffffffffffffffffffffffffffffffffffff0000000000000000001668010000000000000001177ff0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00555f6109e0565b7ff92ee8a9000000000000000000000000000000000000000000000000000000005f5260045ffd5b9050155f61096e565b303b159150610966565b91508e61095b565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857602073ffffffffffffffffffffffffffffffffffffffff7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416604051908152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857604051808160207f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300005492838152017f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300005f527f4c1034e5f5a5b72625c3d988d8ed606ce3febbe9cf91c5cf145ba7ecb6abb175925f5b818110611392575050610e8492500382612cf2565b8051907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0610eca610eb484612eb3565b93610ec26040519586612cf2565b808552612eb3565b015f5b81811061135b5750505f5b81518110156112985773ffffffffffffffffffffffffffffffffffffffff610f0082846133fb565b5116906040517f0dfe1681000000000000000000000000000000000000000000000000000000008152602081600481865afa80156105df5773ffffffffffffffffffffffffffffffffffffffff915f9161127a575b5016916040517fd21220a7000000000000000000000000000000000000000000000000000000008152602081600481855afa80156105df5773ffffffffffffffffffffffffffffffffffffffff915f9161125c575b50166040517f06fdde030000000000000000000000000000000000000000000000000000000081525f81600481885afa9081156105df575f91611242575b506040517f313ce567000000000000000000000000000000000000000000000000000000008152602081600481895afa9081156105df575f91611224575b50604051917f95d89b410000000000000000000000000000000000000000000000000000000083525f836004818a5afa9081156105df5760ff935f92611208575b506040519761107589612cb9565b885260208801526040870152166060850152604051937f06fdde030000000000000000000000000000000000000000000000000000000085525f85600481855afa9485156105df575f956111ec575b506040517f313ce567000000000000000000000000000000000000000000000000000000008152602081600481865afa9081156105df575f916111be575b50604051907f95d89b410000000000000000000000000000000000000000000000000000000082525f82600481875afa80156105df5760019760ff935f9261119a575b506040519561115387612cb9565b8652602086015260408501521660608301526040519261117284612c9d565b83526020830152604082015261118882866133fb565b5261119381856133fb565b5001610ed8565b6111b79192503d805f833e6111af8183612cf2565b8101906134e3565b908b611145565b6111df915060203d81116111e5575b6111d78183612cf2565b810190613546565b88611102565b503d6111cd565b6112019195503d805f833e6111af8183612cf2565b93876110c4565b61121d9192503d805f833e6111af8183612cf2565b908a611067565b61123c915060203d81116111e5576111d78183612cf2565b88611026565b61125691503d805f833e6111af8183612cf2565b87610fe8565b611274915060203d81116105d8576105ca8183612cf2565b87610faa565b611292915060203d81116105d8576105ca8183612cf2565b86610f55565b826040518091602082016020835281518091526040830190602060408260051b8601019301915f905b8282106112d057505050500390f35b9193602061134b827fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc0600195979984950301865288519073ffffffffffffffffffffffffffffffffffffffff8251168152604061133a858401516060878501526060840190612f30565b920151906040818403910152612f30565b96019201920185949391926112c1565b60209060405161136a81612c9d565b5f81526113756134bf565b838201526113816134bf565b604082015282828701015201610ecd565b8454835260019485019486945060209093019201610e6f565b346103385760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338576113ea6113e5612bd3565b61340f565b005b346103385760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760043567ffffffffffffffff81116103385761143b903690600401612ecb565b6024358015158082036103385761145a611453612dee565b3390613754565b5f5b83518110156113ea5760019061149384611474612d6d565b73ffffffffffffffffffffffffffffffffffffffff610b38858a6133fb565b73ffffffffffffffffffffffffffffffffffffffff6114b282876133fb565b51167f45778bebc2e4105030facdf86798167629ba9a2c604e64bc382465e5cda65cd36020604051868152a20161145c565b34610338576101007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385761151c612bd3565b611524612bf6565b61152c612c3c565b60643573ffffffffffffffffffffffffffffffffffffffff811681036103385760843573ffffffffffffffffffffffffffffffffffffffff8116810361033857611574612c19565b9160c4359373ffffffffffffffffffffffffffffffffffffffff851685036103385760e4359573ffffffffffffffffffffffffffffffffffffffff87168703610338576113ea9761302b565b346103385760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338576115f7612bd3565b6115ff612bf6565b611607612c3c565b91611613611453612dee565b73ffffffffffffffffffffffffffffffffffffffff821673ffffffffffffffffffffffffffffffffffffffff82161461061257602073ffffffffffffffffffffffffffffffffffffffff8061168a81957fddf4d71d71bf025a98b6e669ba890608b8ac62636f9396f3608c5946f6eef6d795612fef565b959096169485155f146117f7576116de8773ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b8282165f5284526116f48260405f205416613d6d565b505b61173d8773ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b8282165f52845260405f20867fffffffffffffffffffffffff00000000000000000000000000000000000000008254161790556117b78173ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b8288165f52845260405f20867fffffffffffffffffffffffff000000000000000000000000000000000000000082541617905560405195865216941692a3005b61180086613abd565b506116f6565b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385761070061183f612e78565b604051918291602083526020830190612b90565b346103385760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760043567ffffffffffffffff8111610338576118e36118a76020923690600401612da8565b73ffffffffffffffffffffffffffffffffffffffff6118cd6118c7612bf6565b92612f85565b9116906001915f520160205260405f2054151590565b6040519015158152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857602073ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300045416604051908152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857602073ffffffffffffffffffffffffffffffffffffffff7fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035416604051908152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338575f60408051611a0981612c9d565b82815282602082015201526060604051611a2281612c9d565b600281526040602082019160028352015f81526040519160028352516020830152516040820152f35b346103385760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857604073ffffffffffffffffffffffffffffffffffffffff611aaa611a9c612bd3565b611aa4612bf6565b90612fef565b835191831682529091166020820152f35b346103385760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760043567ffffffffffffffff811161033857610a02611b0d913690600401612da8565b6040519081602082549182815201915f5260205f20905f5b818110611b3c57610700856106f481870382612cf2565b8254845260209093019260019283019201611b25565b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385761070061183f612dee565b34610338576102007ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610338576040516101e0526102006101e051016101e051811067ffffffffffffffff821117610d2f57604052611beb612bd3565b6101e0515260243560206101e051015260443560406101e051015260643560606101e051015260843560806101e0510152611c24612c19565b60a06101e051015260c43560c06101e051015260e43560e06101e0510152610104356101006101e0510152610124356101206101e0510152610144356101406101e0510152610164356101606101e0510152610184356101806101e05101526101a4356101a06101e05101526101c4356101c06101e05101526101e4356101e080510152611cb3611453612d6d565b73ffffffffffffffffffffffffffffffffffffffff6101e051511673ffffffffffffffffffffffffffffffffffffffff60a06101e051015116146106125773ffffffffffffffffffffffffffffffffffffffff6101e051511673ffffffffffffffffffffffffffffffffffffffff611d348160a06101e05101511683612fef565b501690810361288e57156105ea5773ffffffffffffffffffffffffffffffffffffffff6101e051511673ffffffffffffffffffffffffffffffffffffffff611dc38160a06101e0510151169273ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b91165f5260205273ffffffffffffffffffffffffffffffffffffffff60405f2054166128665760206101e051015160c06101e051015190600c820180921161283957118015612816575b6127ee57604051611e1d81612c80565b5f8152602081015f9052604081015f9052606081015f9052608081015f905260a081015f905260c081015f905260e081015f905261010081015f905261012081015f905261014081015f905261016081015f905261018081015f90526101a081015f90526101c081015f90526101e081015f905261020081015f905261022081015f905261024081015f905261026081015f905261028081015f90526102a081015f90526102c081015f90526102e0015f9052611ed861355f565b806101e0515173ffffffffffffffffffffffffffffffffffffffff166101e05160200151611f0590613a6a565b610100526101e05160a081015173ffffffffffffffffffffffffffffffffffffffff166101405260c00151611f3990613a6a565b6101e051604001516101e051606001516101e05160e001516101e05161010001516101e05160800151906101e051610120015192885173ffffffffffffffffffffffffffffffffffffffff169460208a015173ffffffffffffffffffffffffffffffffffffffff169660408b015173ffffffffffffffffffffffffffffffffffffffff169860608c015173ffffffffffffffffffffffffffffffffffffffff169a60808d015173ffffffffffffffffffffffffffffffffffffffff169c60a0015173ffffffffffffffffffffffffffffffffffffffff169d60c081015173ffffffffffffffffffffffffffffffffffffffff1660805260e0015173ffffffffffffffffffffffffffffffffffffffff1660c0526101e05161014001516101c0526101e05161016001516101a0526101e0516101a00151610180526101e0516101c00151610160526101e0516101800151610120526101e0516101e0015160e05260405160a05260a0516120ab90612c80565b60a051526101005160ff1660a051602001526101405160a0516040015260ff1660a0516060015260a0516080015260a05160a0015260a05160c0015260a05160e0015260a051610100015260a051610120015260a051610140015260a051610160015260a051610180015260a0516101a0015260a0516101c0015260a0516101e0015260805160a051610200015260c05160a05161022001526101c05160a05161024001526101a05160a05161026001526101805160a05161028001526101605160a0516102a001526101205160a0516102c0015260e05160a0516102e00152604051602081017f54ea8e0100000000000000000000000000000000000000000000000000000000905260a0515173ffffffffffffffffffffffffffffffffffffffff16602482015260a0516020015160ff16604482015260a0516040015173ffffffffffffffffffffffffffffffffffffffff16606482015260a0516060015160ff16608482015260a0516080015160a482015260a05160a0015160c482015260a05160c0015160e482015260a05160e0015161010482015260a051610100015161012482015260a051610120015161014482015260a051610140015173ffffffffffffffffffffffffffffffffffffffff1661016482015260a051610160015173ffffffffffffffffffffffffffffffffffffffff1661018482015260a051610180015173ffffffffffffffffffffffffffffffffffffffff166101a482015260a0516101a0015173ffffffffffffffffffffffffffffffffffffffff166101c482015260a0516101c0015173ffffffffffffffffffffffffffffffffffffffff166101e482015260a0516101e0015173ffffffffffffffffffffffffffffffffffffffff1661020482015260a051610200015173ffffffffffffffffffffffffffffffffffffffff1661022482015260a051610220015173ffffffffffffffffffffffffffffffffffffffff1661024482015260a051610240015161026482015260a051610260015161028482015260a05161028001516102a482015260a0516102a001516102c482015260a0516102c001516102e482015260a0516102e0015161030482015261030481526123e661032482612cf2565b7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300035473ffffffffffffffffffffffffffffffffffffffff16907f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300045473ffffffffffffffffffffffffffffffffffffffff166040519261246484612c9d565b835260208301908152604083019182526040519182916020830194602086525173ffffffffffffffffffffffffffffffffffffffff1660408401525173ffffffffffffffffffffffffffffffffffffffff16606083015251608082016060905260a082016124d191612b90565b037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0810182526125019082612cf2565b6107df9160405191602084016125179084612cf2565b83835260208301936141048539604051938493518091602086015e83019060208201905f8252519283915e016020015f8152037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0810182526125799082612cf2565b6101e0515173ffffffffffffffffffffffffffffffffffffffff166101e05160a0015173ffffffffffffffffffffffffffffffffffffffff166125bb9161392b565b60405180809381937f9c36a286000000000000000000000000000000000000000000000000000000008352600483015260248201604090526044820161260091612b90565b035a925f73ba5ed099633d3b313e4d5f7bdc1305d3c28ba5ed602095f19081156105df5760209173ffffffffffffffffffffffffffffffffffffffff915f916127d1575b50612692826101e051511673ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b828060a06101e051015116165f52835260405f208282167fffffffffffffffffffffffff00000000000000000000000000000000000000008254161790556127208260a06101e05101511673ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b82806101e0515116165f52835260405f208282167fffffffffffffffffffffffff00000000000000000000000000000000000000008254161790551661276581613abd565b5073ffffffffffffffffffffffffffffffffffffffff6101e051511673ffffffffffffffffffffffffffffffffffffffff60a06101e051015116907fa92a2b95c8d8436f6ac4c673c61487364f877efb9534d4296fad8ef904546c9484604051858152a3604051908152f35b6127e89150833d85116105d8576105ca8183612cf2565b83612644565b7f402470ee000000000000000000000000000000000000000000000000000000005f5260045ffd5b5060c06101e051015160206101e051015190600c82018092116128395711611e0d565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b7f3d77e891000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f3f06bf81000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103385760607ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385760043567ffffffffffffffff811161033857612905903690600401612da8565b61290d612bf6565b60443580151581036103385761292e91612928611453612dee565b836138a8565b8051612938612dee565b51149081612988575b81612976575b5061294e57005b7f3cba491a000000000000000000000000000000000000000000000000000000005f5260045ffd5b6129809150612f85565b541581612947565b809150516020820120612999612dee565b602081519101201490612941565b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857602073ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300035416604051908152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126103385761070061183f612d6d565b346103385760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857612a87612bd3565b73ffffffffffffffffffffffffffffffffffffffff612aeb612aa7612bf6565b9273ffffffffffffffffffffffffffffffffffffffff165f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000260205260405f2090565b91165f52602052602073ffffffffffffffffffffffffffffffffffffffff60405f205416604051908152f35b34610338575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261033857610700604051612b56604082612cf2565b601681527f41676f7261537461626c6553776170466163746f72790000000000000000000060208201526040519182916020835260208301905b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f602080948051918291828752018686015e5f8582860101520116010190565b6004359073ffffffffffffffffffffffffffffffffffffffff8216820361033857565b6024359073ffffffffffffffffffffffffffffffffffffffff8216820361033857565b60a4359073ffffffffffffffffffffffffffffffffffffffff8216820361033857565b6044359073ffffffffffffffffffffffffffffffffffffffff8216820361033857565b359073ffffffffffffffffffffffffffffffffffffffff8216820361033857565b610300810190811067ffffffffffffffff821117610d2f57604052565b6060810190811067ffffffffffffffff821117610d2f57604052565b6080810190811067ffffffffffffffff821117610d2f57604052565b610100810190811067ffffffffffffffff821117610d2f57604052565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff821117610d2f57604052565b67ffffffffffffffff8111610d2f57601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b60405190612d7c604083612cf2565b601182527f415050524f5645445f4445504c4f5945520000000000000000000000000000006020830152565b81601f8201121561033857803590612dbf82612d33565b92612dcd6040519485612cf2565b8284526020838301011161033857815f926020809301838601378301015290565b60405190612dfd604083612cf2565b601b82527f4143434553535f434f4e54524f4c5f4d414e414745525f524f4c4500000000006020830152565b60206040818301928281528451809452019201905f5b818110612e4c5750505090565b825173ffffffffffffffffffffffffffffffffffffffff16845260209384019390920191600101612e3f565b60405190612e87604083612cf2565b601a82527f494d504c454d454e544154494f4e5f5345545445525f524f4c450000000000006020830152565b67ffffffffffffffff8111610d2f5760051b60200190565b9080601f83011215610338578135612ee281612eb3565b92612ef06040519485612cf2565b81845260208085019260051b82010192831161033857602001905b828210612f185750505090565b60208091612f2584612c5f565b815201910190612f0b565b9073ffffffffffffffffffffffffffffffffffffffff8251168152606080612f7c612f6a6020860151608060208701526080860190612b90565b60408601518582036040870152612b90565b93015191015290565b60208091604051928184925191829101835e81017f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b00281520301902090565b90816020910312610338575173ffffffffffffffffffffffffffffffffffffffff811681036103385790565b73ffffffffffffffffffffffffffffffffffffffff821673ffffffffffffffffffffffffffffffffffffffff8216105f146130275791565b9091565b937f0bbb5d7eaea3e2cfc663c9f1b7e468eff9c394543e1d3abad73b2d6ad08553ba979373ffffffffffffffffffffffffffffffffffffffff808080808080806101009f9b9d9e9a9e61307f611453612dee565b169d8e7fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300055416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000555169b8c7fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300065416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630006551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300075416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630007551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300085416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630008551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300095416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630009551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000a5416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000a551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000b5416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000b551695867fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000c5416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000c55604051978852602088015260408701526060860152608085015260a084015260c083015260e0820152a1565b80518210156102fa5760209160051b010190565b73ffffffffffffffffffffffffffffffffffffffff90613430611453612e78565b16807fffffffffffffffffffffffff00000000000000000000000000000000000000007f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300035416177f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630003557f132d6ae8f04c23470c6742ffb48b6dbb7ea6e541578deb9ebc5fca598998a14b5f80a2565b604051906134cc82612cb9565b5f6060838281528160208201528160408201520152565b6020818303126103385780519067ffffffffffffffff8211610338570181601f820112156103385780519061351782612d33565b926135256040519485612cf2565b8284526020838301011161033857815f9260208093018386015e8301015290565b90816020910312610338575160ff811681036103385790565b6040519061356c82612cd5565b8173ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300055416815273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300065416602082015273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300075416604082015273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300085416606082015273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300095416608082015273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000a541660a082015273ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000b541660c082015260e073ffffffffffffffffffffffffffffffffffffffff7f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000c5416910152565b906137779073ffffffffffffffffffffffffffffffffffffffff6118cd84612f85565b1561377f5750565b6137bd906040519182917fc13dd0f3000000000000000000000000000000000000000000000000000000008352602060048401526024830190612b90565b0390fd5b602090604051918183925191829101835e81015f815203902090565b61381a73ffffffffffffffffffffffffffffffffffffffff916137ff816139cd565b61381461380b82612f85565b84861690613d15565b506137c1565b9116907f1cf4c2f10398d18e27c3336eeadbf9ce9571462b7cb30d5d9a4024580f208d215f80a3565b84861690613fd7565b61387373ffffffffffffffffffffffffffffffffffffffff9161386e816139cd565b61389c565b9116907f1e5d48c75f77ab7fd581247d777530d4e8c18432289e14017ba995532f6ca1cf5f80a3565b61381461384382612f85565b73ffffffffffffffffffffffffffffffffffffffff91926138c8826139cd565b6138d3818584613a12565b156138e15761381a906137c1565b613873906137c1565b6020815191015190602081106138fe575090565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9060200360031b1b1690565b7fffffffffffffffffffffff000000000000000000000000000000000000000000906139ca927fffffffffffffffffffffffffffffffffffffffff0000000000000000000000006040519181602084019460601b16845260601b1660348201526028815261399a604882612cf2565b51902016604051903060601b60208301525f60348301526035820152602081526139c5604082612cf2565b6138ea565b90565b60208151116139ea576139e26139e7916138ea565b613c06565b50565b7f37d8d209000000000000000000000000000000000000000000000000000000005f5260045ffd5b9115613a415773ffffffffffffffffffffffffffffffffffffffff613a396139e793612f85565b911690613d15565b73ffffffffffffffffffffffffffffffffffffffff613a626139e793612f85565b911690613fd7565b60ff8111613a785760ff1690565b7f6dfcc650000000000000000000000000000000000000000000000000000000005f52600860045260245260445ffd5b80548210156102fa575f5260205f2001905f90565b805f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000160205260405f2054155f14613c01577f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300005468010000000000000000811015610d2f57613bac613b778260018594017f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000557f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000613aa8565b81939154907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9060031b92831b921b19161790565b90557f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000054905f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000160205260405f2055600190565b505f90565b805f527f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b00160205260405f2054155f14613c01577f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b0005468010000000000000000811015610d2f57613cc0613b778260018594017f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b000557f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b000613aa8565b90557f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b00054905f527f8f8de9240b3899c03a31968f466af060ab1c78464aa7ae14941c20fe7917b00160205260405f2055600190565b5f828152600182016020526040902054613d675780549068010000000000000000821015610d2f5782613d52613b77846001809601855584613aa8565b90558054925f520160205260405f2055600190565b50505f90565b5f8181527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000160205260409020548015613d67577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8101818111612839577f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000054907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff820191821161283957818103613f42575b5050507f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000548015613f15577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01613e96817f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000613aa8565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82549160031b1b191690557f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000555f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded876300016020525f6040812055600190565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603160045260245ffd5b613fa2613f72613b77937f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000613aa8565b90549060031b1c9283927f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded87630000613aa8565b90555f527f024be988c51836176a4af0f43e497ce34fbb4aad290e797943ba9ded8763000160205260405f20555f8080613e1f565b906001820191815f528260205260405f20548015155f146140fb577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8101818111612839578254907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8201918211612839578181036140c6575b50505080548015613f15577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01906140898282613aa8565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82549160031b1b19169055555f526020525f6040812055600190565b6140e66140d6613b779386613aa8565b90549060031b1c92839286613aa8565b90555f528360205260405f20555f8080614051565b505050505f9056fe60806040526107df8038038061001481610279565b928339810190602081830312610261578051906001600160401b03821161026157016060818303126102615760405190606082016001600160401b03811183821017610265576040526100668161029e565b82526100746020820161029e565b60208301908152604082015190916001600160401b038211610261570183601f82011215610261578051906100b06100ab836102b2565b610279565b948286526020838301011161026157815f9260208093018388015e85010152604082810193845290515f80546001600160a01b0319166001600160a01b039283169081179091555f5160206107bf5f395f51905f52548351928116835260208301829052909290917f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f9190a1811561024e576001600160a01b031916175f5160206107bf5f395f51905f5255516001600160a01b0316908161017c575b604051610493908161032c8239f35b5190803b1561023c577f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b03191682179055807fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115610225575f8083602061021495519101845af43d1561021d573d916102056100ab846102b2565b9283523d5f602085013e6102cd565b505b5f8061016d565b6060916102cd565b505034156102165763b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b633173bdd160e11b5f525f60045260245ffd5b5f80fd5b634e487b7160e01b5f52604160045260245ffd5b6040519190601f01601f191682016001600160401b0381118382101761026557604052565b51906001600160a01b038216820361026157565b6001600160401b03811161026557601f01601f191660200190565b906102f157508051156102e257805190602001fd5b63d6bda27560e01b5f5260045ffd5b81511580610322575b610302575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b156102fa56fe608060405273ffffffffffffffffffffffffffffffffffffffff5f541633145f146100cc575f357fffffffff00000000000000000000000000000000000000000000000000000000167f4f1ef2860000000000000000000000000000000000000000000000000000000014610096577fd2b576ec000000000000000000000000000000000000000000000000000000005f5260045ffd5b6100ca73ffffffffffffffffffffffffffffffffffffffff6100c36100bb3636610120565b81019061020d565b9116610290565b005b5f8073ffffffffffffffffffffffffffffffffffffffff7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416368280378136915af43d5f803e1561011c573d5ff35b3d5ffd5b91909182600411610159578211610159577ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc6004920190565b5f80fd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f604051930116820182811067ffffffffffffffff8211176101ce57604052565b61015d565b67ffffffffffffffff81116101ce57601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01660200190565b919060408382031261015957823573ffffffffffffffffffffffffffffffffffffffff81168103610159579260208101359067ffffffffffffffff8211610159570181601f820112156101595780359061026e610269836101d3565b61018a565b928284526020838301011161015957815f926020809301838601378301015290565b90813b1561037f5773ffffffffffffffffffffffffffffffffffffffff8216807fffffffffffffffffffffffff00000000000000000000000000000000000000007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5416177f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a280511561034e5761034b916103c1565b50565b50503461035757565b7fb398979f000000000000000000000000000000000000000000000000000000005f5260045ffd5b73ffffffffffffffffffffffffffffffffffffffff827f4c9c8ce3000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b5f806103f393602081519101845af43d156103f6573d916103e4610269846101d3565b9283523d5f602085013e6103fa565b90565b6060915b90610437575080511561040f57805190602001fd5b7fd6bda275000000000000000000000000000000000000000000000000000000005f5260045ffd5b8151158061048a575b610448575090565b73ffffffffffffffffffffffffffffffffffffffff907f9996b315000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b50803b1561044056b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
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.