UCS03ZkgmTokenOrderImpl

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "contracts/apps/ucs/03-zkgm/TokenOrder.sol": {
      "content": "pragma solidity ^0.8.27;

import "./Store.sol";

contract UCS03ZkgmTokenOrderImpl is Versioned, TokenBucket, UCS03ZkgmStore {
    using ZkgmLib for *;
    using LibString for *;
    using LibBytes for *;
    using SafeERC20 for *;
    using Address for *;
    using LibCall for *;

    IWETH public immutable WETH;
    ZkgmERC20 public immutable ERC20_IMPL;
    bool public immutable RATE_LIMIT_ENABLED;

    constructor(IWETH _weth, ZkgmERC20 _erc20Impl, bool _rateLimitEnabled) {
        WETH = _weth;
        ERC20_IMPL = _erc20Impl;
        RATE_LIMIT_ENABLED = _rateLimitEnabled;
    }

    function _protocolFillMint(
        uint32 channelId,
        uint256 path,
        address wrappedToken,
        address receiver,
        address relayer,
        uint256 baseAmount,
        uint256 quoteAmount
    ) internal returns (bytes memory) {
        uint256 fee = baseAmount - quoteAmount;
        if (quoteAmount > 0) {
            IZkgmERC20(wrappedToken).mint(receiver, quoteAmount);
        }
        if (fee > 0) {
            IZkgmERC20(wrappedToken).mint(relayer, fee);
        }
        return ZkgmLib.encodeTokenOrderAck(
            TokenOrderAck({
                fillType: ZkgmLib.FILL_TYPE_PROTOCOL,
                marketMaker: ZkgmLib.ACK_EMPTY
            })
        );
    }

    function _protocolFillUnescrowV2(
        uint32 channelId,
        uint256 path,
        bytes calldata baseToken,
        address quoteToken,
        address receiver,
        address relayer,
        uint256 baseAmount,
        uint256 quoteAmount
    ) internal returns (bytes memory) {
        uint256 fee = baseAmount - quoteAmount;
        // If the base token path is being unwrapped, it's escrowed balance will be non zero.
        _decreaseOutstandingV2(
            channelId,
            ZkgmLib.reverseChannelPath(path),
            quoteToken,
            baseToken,
            baseAmount
        );
        // Specific case for native token.
        if (quoteToken == ZkgmLib.NATIVE_TOKEN_ERC_7528_ADDRESS) {
            if (quoteAmount + fee > 0) {
                WETH.withdraw(baseAmount);
            }
            if (quoteAmount > 0) {
                payable(receiver).sendValue(quoteAmount);
            }
            if (fee > 0) {
                if (
                    !SafeTransferLib.trySafeTransferETH(
                        relayer,
                        fee,
                        SafeTransferLib.GAS_STIPEND_NO_STORAGE_WRITES
                    )
                ) {
                    return ZkgmLib.ACK_ERR_ONLYMAKER;
                }
            }
        } else {
            if (quoteAmount > 0) {
                IERC20(quoteToken).safeTransfer(receiver, quoteAmount);
            }
            if (fee > 0) {
                IERC20(quoteToken).safeTransfer(relayer, fee);
            }
        }
        return ZkgmLib.encodeTokenOrderAck(
            TokenOrderAck({
                fillType: ZkgmLib.FILL_TYPE_PROTOCOL,
                marketMaker: ZkgmLib.ACK_EMPTY
            })
        );
    }

    function _marketMakerFill(
        address caller,
        bytes calldata relayerMsg,
        address quoteToken,
        address payable receiver,
        uint256 quoteAmount
    ) internal returns (bytes memory) {
        if (quoteAmount != 0) {
            // We want the top level handler in onRecvPacket to know we need to
            // revert for another MM to get a chance to fill. If we revert now
            // the entire packet would be considered to be "failed" and refunded
            // at origin, which we want to avoid.
            // Hence, in case of transfer failure, we yield the ack to notify the onRecvPacket.

            // Special case for gas station where the user is asking for native
            // gas token. The MM has to provide WETH funds that will be
            // unwrapped, avoiding us from having to manage msg.value accross
            // the stack.
            if (quoteToken == ZkgmLib.NATIVE_TOKEN_ERC_7528_ADDRESS) {
                // Transfert to protocol.
                if (
                    !WETH.trySafeTransferFrom(caller, address(this), quoteAmount)
                ) {
                    return ZkgmLib.ACK_ERR_ONLYMAKER;
                }
                // Unwrap and send.
                WETH.withdraw(quoteAmount);
                // We allow this call to fail because in such case the MM was
                // able to provide the funds. A failure ACK will be written and
                // refund will happen.
                receiver.sendValue(quoteAmount);
            } else if (
                !IERC20(quoteToken).trySafeTransferFrom(
                    caller, receiver, quoteAmount
                )
            ) {
                return ZkgmLib.ACK_ERR_ONLYMAKER;
            }
        }
        return ZkgmLib.encodeTokenOrderAck(
            TokenOrderAck({
                fillType: ZkgmLib.FILL_TYPE_MARKETMAKER,
                // The relayer has to provide it's maker address using the
                // relayerMsg. This address is specific to the counterparty
                // chain and is where the protocol will pay back the base amount
                // on acknowledgement.
                marketMaker: relayerMsg
            })
        );
    }

    function _solverFill(
        IBCPacket calldata packet,
        address caller,
        address relayer,
        bytes calldata relayerMsg,
        uint256 path,
        TokenOrderV2 calldata order,
        bool intent
    ) internal returns (bytes memory) {
        uint256 quoteAmount = order.quoteAmount;

        SolverMetadata calldata metadata =
            ZkgmLib.decodeSolverMetadata(order.metadata);

        address solver = address(bytes20(metadata.solverAddress));

        (bool solverFilled,, bytes memory solverReturnData) = solver.tryCall(
            0,
            gasleft(),
            type(uint16).max,
            abi.encodeCall(
                ISolver.solve,
                (packet, order, path, caller, relayer, relayerMsg, intent)
            )
        );
        if (solverFilled) {
            return ZkgmLib.encodeTokenOrderAck(
                TokenOrderAck({
                    fillType: ZkgmLib.FILL_TYPE_MARKETMAKER,
                    // The solver has to provide it's maker addresss that the
                    // counterparty chain will repay on acknowledgement with the
                    // base token.
                    marketMaker: abi.decode(solverReturnData, (bytes))
                })
            );
        } else {
            return ZkgmLib.ACK_ERR_ONLYMAKER;
        }
    }

    function _marketMakerFillV2(
        IBCPacket calldata packet,
        address caller,
        address relayer,
        bytes calldata relayerMsg,
        uint256 path,
        address quoteToken,
        address payable receiver,
        TokenOrderV2 calldata order,
        bool intent
    ) internal returns (bytes memory) {
        if (order.kind == ZkgmLib.TOKEN_ORDER_KIND_SOLVE) {
            return _solverFill(
                packet, caller, relayer, relayerMsg, path, order, intent
            );
        } else {
            uint256 quoteAmount = order.quoteAmount;

            // We want the top level handler in onRecvPacket to know we need to
            // revert for another MM to get a chance to fill. If we revert now
            // the entire packet would be considered to be "failed" and refunded
            // at origin, which we want to avoid.
            // Hence, in case of transfer failure, we yield the ack to notify the onRecvPacket.

            // Special case for gas station where the user is asking for native
            // gas token. The MM has to provide WETH funds that will be
            // unwrapped, avoiding us from having to manage msg.value accross
            // the stack.
            if (quoteToken == ZkgmLib.NATIVE_TOKEN_ERC_7528_ADDRESS) {
                if (quoteAmount > 0) {
                    // Transfert to protocol.
                    if (
                        !WETH.trySafeTransferFrom(
                            caller, address(this), quoteAmount
                        )
                    ) {
                        return ZkgmLib.ACK_ERR_ONLYMAKER;
                    }
                    // Unwrap and send.
                    WETH.withdraw(quoteAmount);
                    // We allow this call to fail because in such case the MM was
                    // able to provide the funds. A failure ACK will be written and
                    // refund will happen.
                    receiver.sendValue(quoteAmount);
                }
            } else {
                if (quoteAmount > 0) {
                    if (
                        !IERC20(quoteToken).trySafeTransferFrom(
                            caller, receiver, quoteAmount
                        )
                    ) {
                        return ZkgmLib.ACK_ERR_ONLYMAKER;
                    }
                }
            }

            return ZkgmLib.encodeTokenOrderAck(
                TokenOrderAck({
                    fillType: ZkgmLib.FILL_TYPE_MARKETMAKER,
                    // The relayer has to provide it's maker address using the
                    // relayerMsg. This address is specific to the counterparty
                    // chain and is where the protocol will pay back the base amount
                    // on acknowledgement.
                    marketMaker: relayerMsg
                })
            );
        }
    }

    function _deployWrappedTokenV2(
        uint32 channelId,
        uint256 path,
        bytes calldata unwrappedToken,
        address wrappedToken,
        bytes32 wrappedTokenSalt,
        TokenMetadata memory metadata,
        bool canDeploy
    ) internal {
        if (!ZkgmLib.isDeployed(wrappedToken)) {
            if (!canDeploy) {
                revert ZkgmLib.ErrCannotDeploy();
            }
            address implementation = address(bytes20(metadata.implementation));
            CREATE3.deployDeterministic(
                abi.encodePacked(
                    type(ERC1967Proxy).creationCode,
                    abi.encode(implementation, metadata.initializer)
                ),
                wrappedTokenSalt
            );
            tokenOrigin[wrappedToken] =
                ZkgmLib.updateChannelPath(path, channelId);

            bytes memory encodedMetadata = ZkgmLib.encodeTokenMetadata(metadata);
            metadataImageOf[wrappedToken] =
                EfficientHashLib.hash(encodedMetadata);

            uint8 kind = ZkgmLib.WRAPPED_TOKEN_KIND_THIRD_PARTY;
            if (implementation == address(ERC20_IMPL)) {
                try this.decodeZkgmERC20InitializeCall(metadata.initializer)
                returns (
                    address tokenAuthority,
                    address tokenMinter,
                    string memory,
                    string memory,
                    uint8
                ) {
                    if (
                        tokenAuthority == authority()
                            && tokenMinter == address(this)
                    ) {
                        kind = ZkgmLib.WRAPPED_TOKEN_KIND_PROTOCOL;
                    }
                } catch {}
            }

            emit ZkgmLib.CreateWrappedToken(
                path,
                channelId,
                unwrappedToken,
                wrappedToken,
                encodedMetadata,
                kind
            );
        }
    }

    function _makeDefaultTokenMetadata(
        TokenOrderV1 calldata order
    ) internal view returns (TokenMetadata memory) {
        return TokenMetadata({
            implementation: abi.encodePacked(ERC20_IMPL),
            initializer: abi.encodeCall(
                ZkgmERC20.initialize,
                (
                    authority(),
                    address(this),
                    order.baseTokenName,
                    order.baseTokenSymbol,
                    order.baseTokenDecimals
                )
            )
        });
    }

    function _optionalRateLimit(address token, uint256 amount) internal {
        if (RATE_LIMIT_ENABLED) {
            _rateLimit(token, amount);
        }
    }

    function executeTokenOrderV1(
        address caller,
        IBCPacket calldata ibcPacket,
        address relayer,
        bytes calldata relayerMsg,
        uint256 path,
        TokenOrderV1 calldata order,
        bool intent
    ) public returns (bytes memory) {
        address quoteToken = address(bytes20(order.quoteToken));
        address payable receiver = payable(address(bytes20(order.receiver)));

        // For intent packets, the protocol is not allowed to provide any fund
        // as the packet has not been checked for membership poof. Instead, we
        // know the market maker will be repaid on the source chain, if and only
        // if the currently executing packet hash had been registered as sent on
        // the source. In other words, the market maker is unable to lie.
        if (intent) {
            return _marketMakerFill(
                caller, relayerMsg, quoteToken, receiver, order.quoteAmount
            );
        }

        (address wrappedToken, bytes32 wrappedTokenSalt) = _predictWrappedToken(
            path, ibcPacket.destinationChannelId, order.baseToken
        );

        bool baseAmountCoversQuoteAmount = order.baseAmount >= order.quoteAmount;
        if (quoteToken == wrappedToken && baseAmountCoversQuoteAmount) {
            _optionalRateLimit(quoteToken, order.quoteAmount);
            TokenMetadata memory metadata = _makeDefaultTokenMetadata(order);
            _deployWrappedTokenV2(
                ibcPacket.destinationChannelId,
                path,
                order.baseToken,
                wrappedToken,
                wrappedTokenSalt,
                metadata,
                false
            );
            return _protocolFillMint(
                ibcPacket.destinationChannelId,
                path,
                wrappedToken,
                receiver,
                relayer,
                order.baseAmount,
                order.quoteAmount
            );
        } else if (order.baseTokenPath != 0 && baseAmountCoversQuoteAmount) {
            _optionalRateLimit(quoteToken, order.quoteAmount);
            return _protocolFillUnescrowV2(
                ibcPacket.destinationChannelId,
                path,
                order.baseToken,
                quoteToken,
                receiver,
                relayer,
                order.baseAmount,
                order.quoteAmount
            );
        } else {
            // We also allow market makers to fill orders after finality. This
            // allow orders that combines protocol and mm filling (wrapped vs
            // non wrapped assets).
            return _marketMakerFill(
                caller, relayerMsg, quoteToken, receiver, order.quoteAmount
            );
        }
    }

    function executeTokenOrderV2(
        address caller,
        IBCPacket calldata ibcPacket,
        address relayer,
        bytes calldata relayerMsg,
        uint256 path,
        TokenOrderV2 calldata order,
        bool intent
    ) public returns (bytes memory) {
        address quoteToken = address(bytes20(order.quoteToken));
        address payable receiver = payable(address(bytes20(order.receiver)));

        // For intent packets, the protocol is not allowed to provide any fund
        // as the packet has not been checked for membership poof. Instead, we
        // know the market maker will be repaid on the source chain, if and only
        // if the currently executing packet hash had been registered as sent on
        // the source. In other words, the market maker is unable to lie.
        if (intent || order.kind == ZkgmLib.TOKEN_ORDER_KIND_SOLVE) {
            return _marketMakerFillV2(
                ibcPacket,
                caller,
                relayer,
                relayerMsg,
                path,
                quoteToken,
                receiver,
                order,
                intent
            );
        }

        bool baseAmountCoversQuoteAmount = order.baseAmount >= order.quoteAmount;

        if (
            order.kind == ZkgmLib.TOKEN_ORDER_KIND_UNESCROW
                && baseAmountCoversQuoteAmount
        ) {
            _optionalRateLimit(quoteToken, order.quoteAmount);
            return _protocolFillUnescrowV2(
                ibcPacket.destinationChannelId,
                path,
                order.baseToken,
                quoteToken,
                receiver,
                relayer,
                order.baseAmount,
                order.quoteAmount
            );
        } else {
            address wrappedToken;
            bytes32 wrappedTokenSalt;
            if (order.kind == ZkgmLib.TOKEN_ORDER_KIND_ESCROW) {
                bytes32 metadataImage = metadataImageOf[quoteToken];
                if (metadataImage == 0) {
                    // V1
                    (wrappedToken, wrappedTokenSalt) = _predictWrappedToken(
                        path, ibcPacket.destinationChannelId, order.baseToken
                    );
                } else {
                    // V2
                    (wrappedToken, wrappedTokenSalt) =
                    _predictWrappedTokenFromMetadataImageV2(
                        path,
                        ibcPacket.destinationChannelId,
                        order.baseToken,
                        metadataImage
                    );
                }
            } else if (order.kind == ZkgmLib.TOKEN_ORDER_KIND_INITIALIZE) {
                TokenMetadata calldata metadata =
                    ZkgmLib.decodeTokenMetadata(order.metadata);
                (wrappedToken, wrappedTokenSalt) = _predictWrappedTokenV2(
                    path,
                    ibcPacket.destinationChannelId,
                    order.baseToken,
                    metadata
                );
                if (quoteToken != wrappedToken) {
                    revert ZkgmLib.ErrInvalidTokenOrderKind();
                }
                _deployWrappedTokenV2(
                    ibcPacket.destinationChannelId,
                    path,
                    order.baseToken,
                    wrappedToken,
                    wrappedTokenSalt,
                    metadata,
                    true
                );
            }

            if (quoteToken == wrappedToken && baseAmountCoversQuoteAmount) {
                _optionalRateLimit(quoteToken, order.quoteAmount);
                return _protocolFillMint(
                    ibcPacket.destinationChannelId,
                    path,
                    wrappedToken,
                    receiver,
                    relayer,
                    order.baseAmount,
                    order.quoteAmount
                );
            } else {
                // We also allow market makers to fill orders after finality. This
                // allow orders that combines protocol and mm filling (wrapped vs
                // non wrapped assets).
                return _marketMakerFillV2(
                    ibcPacket,
                    caller,
                    relayer,
                    relayerMsg,
                    path,
                    quoteToken,
                    receiver,
                    order,
                    intent
                );
            }
        }
    }

    function _acknowledgeTokenOrderV1(
        IBCPacket calldata ibcPacket,
        address relayer,
        uint256 path,
        bytes32 salt,
        TokenOrderV1 calldata order,
        bool successful,
        bytes calldata ack
    ) internal {
        if (successful) {
            TokenOrderAck calldata assetOrderAck =
                ZkgmLib.decodeTokenOrderAck(ack);
            if (assetOrderAck.fillType == ZkgmLib.FILL_TYPE_PROTOCOL) {
                // The protocol filled, fee was paid to relayer.
            } else if (assetOrderAck.fillType == ZkgmLib.FILL_TYPE_MARKETMAKER)
            {
                // A market maker filled, we pay with the sent asset.
                address marketMaker =
                    address(bytes20(assetOrderAck.marketMaker));
                address baseToken = address(bytes20(order.baseToken));
                if (order.baseTokenPath != 0) {
                    IZkgmERC20(address(baseToken)).mint(
                        marketMaker, order.baseAmount
                    );
                } else {
                    _decreaseOutstandingV2(
                        ibcPacket.sourceChannelId,
                        path,
                        baseToken,
                        order.quoteToken,
                        order.baseAmount
                    );
                    if (baseToken == ZkgmLib.NATIVE_TOKEN_ERC_7528_ADDRESS) {
                        WETH.withdraw(order.baseAmount);
                        payable(marketMaker).sendValue(order.baseAmount);
                    } else {
                        // Check if the counterparty minted and wants us to burn to net.
                        if (marketMaker == address(0)) {
                            IZkgmERC20(baseToken).burn(
                                address(this), order.baseAmount
                            );
                        } else {
                            IERC20(baseToken).safeTransfer(
                                marketMaker, order.baseAmount
                            );
                        }
                    }
                }
            } else {
                revert ZkgmLib.ErrInvalidFillType();
            }
        } else {
            _refund(ibcPacket.sourceChannelId, path, order);
        }
    }

    function acknowledgeTokenOrderV1(
        IBCPacket calldata ibcPacket,
        address relayer,
        uint256 path,
        bytes32 salt,
        TokenOrderV1 calldata order,
        bool successful,
        bytes calldata ack
    ) public {
        _acknowledgeTokenOrderV1(
            ibcPacket, relayer, path, salt, order, successful, ack
        );
    }

    function acknowledgeTokenOrderV2(
        IBCPacket calldata ibcPacket,
        address relayer,
        uint256 path,
        bytes32 salt,
        TokenOrderV2 calldata order,
        bool successful,
        bytes calldata ack
    ) public {
        if (successful) {
            TokenOrderAck calldata assetOrderAck =
                ZkgmLib.decodeTokenOrderAck(ack);
            if (assetOrderAck.fillType == ZkgmLib.FILL_TYPE_PROTOCOL) {
                // The protocol filled, fee was paid to relayer.
            } else if (assetOrderAck.fillType == ZkgmLib.FILL_TYPE_MARKETMAKER)
            {
                // A market maker filled, we pay with the sent asset.
                address marketMaker =
                    address(bytes20(assetOrderAck.marketMaker));
                address baseToken = address(bytes20(order.baseToken));
                if (order.kind == ZkgmLib.TOKEN_ORDER_KIND_UNESCROW) {
                    IZkgmERC20(address(baseToken)).mint(
                        marketMaker, order.baseAmount
                    );
                } else {
                    _decreaseOutstandingV2(
                        ibcPacket.sourceChannelId,
                        path,
                        baseToken,
                        order.quoteToken,
                        order.baseAmount
                    );
                    if (baseToken == ZkgmLib.NATIVE_TOKEN_ERC_7528_ADDRESS) {
                        WETH.withdraw(order.baseAmount);
                        payable(marketMaker).sendValue(order.baseAmount);
                    } else {
                        // Check if the counterparty minted and wants us to burn to net.
                        if (marketMaker == address(0)) {
                            IZkgmERC20(baseToken).burn(
                                address(this), order.baseAmount
                            );
                        } else {
                            IERC20(baseToken).safeTransfer(
                                marketMaker, order.baseAmount
                            );
                        }
                    }
                }
            } else {
                revert ZkgmLib.ErrInvalidFillType();
            }
        } else {
            _refundV2(ibcPacket.sourceChannelId, path, order);
        }
    }

    function timeoutTokenOrderV1(
        IBCPacket calldata ibcPacket,
        uint256 path,
        TokenOrderV1 calldata order
    ) public {
        _refund(ibcPacket.sourceChannelId, path, order);
    }

    function timeoutTokenOrderV2(
        IBCPacket calldata ibcPacket,
        uint256 path,
        TokenOrderV2 calldata order
    ) public {
        _refundV2(ibcPacket.sourceChannelId, path, order);
    }

    function _refund(
        uint32 sourceChannelId,
        uint256 path,
        TokenOrderV1 calldata order
    ) internal {
        address sender = address(bytes20(order.sender));
        address baseToken = address(bytes20(order.baseToken));
        if (order.baseTokenPath != 0) {
            IZkgmERC20(address(baseToken)).mint(sender, order.baseAmount);
        } else {
            _decreaseOutstandingV2(
                sourceChannelId,
                path,
                baseToken,
                order.quoteToken,
                order.baseAmount
            );
            if (baseToken == ZkgmLib.NATIVE_TOKEN_ERC_7528_ADDRESS) {
                WETH.withdraw(order.baseAmount);
                payable(sender).sendValue(order.baseAmount);
            } else {
                IERC20(baseToken).safeTransfer(sender, order.baseAmount);
            }
        }
    }

    function _refundV2(
        uint32 sourceChannelId,
        uint256 path,
        TokenOrderV2 calldata order
    ) internal {
        address sender = address(bytes20(order.sender));
        address baseToken = address(bytes20(order.baseToken));
        if (order.kind == ZkgmLib.TOKEN_ORDER_KIND_UNESCROW) {
            IZkgmERC20(address(baseToken)).mint(sender, order.baseAmount);
        } else {
            _decreaseOutstandingV2(
                sourceChannelId,
                path,
                baseToken,
                order.quoteToken,
                order.baseAmount
            );
            if (baseToken == ZkgmLib.NATIVE_TOKEN_ERC_7528_ADDRESS) {
                WETH.withdraw(order.baseAmount);
                payable(sender).sendValue(order.baseAmount);
            } else {
                IERC20(baseToken).safeTransfer(sender, order.baseAmount);
            }
        }
    }
}
"
    },
    "contracts/apps/ucs/03-zkgm/Store.sol": {
      "content": "pragma solidity ^0.8.27;

import "@openzeppelin-upgradeable/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol";
import
    "@openzeppelin-upgradeable/contracts/access/manager/AccessManagedUpgradeable.sol";
import "@openzeppelin-upgradeable/contracts/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";

import "solady/utils/CREATE3.sol";
import "solady/utils/LibBit.sol";
import "solady/utils/LibString.sol";
import "solady/utils/LibBytes.sol";
import "solady/utils/LibCall.sol";
import "solady/utils/EfficientHashLib.sol";
import "solady/utils/SafeTransferLib.sol";
import "solady/utils/LibTransient.sol";

import "../../Base.sol";
import "../../../core/04-channel/IBCPacket.sol";
import "../../../core/05-port/IIBCModule.sol";
import "../../../core/24-host/IBCCommitment.sol";
import "../../../internal/Versioned.sol";

import "./TokenBucket.sol";
import "./IWETH.sol";
import "./IZkgmable.sol";
import "./IZkgmERC20.sol";
import "./ZkgmERC20.sol";
import "./ZkgmERC721.sol";
import "./IZkgm.sol";
import "./Lib.sol";

abstract contract UCS03ZkgmStore is AccessManagedUpgradeable, IZkgmStore {
    using ZkgmLib for *;
    using LibString for *;
    using LibBytes for *;
    using SafeERC20 for *;
    using Address for *;
    using LibCall for *;

    bytes32 internal constant STAKE_NFT_MANAGER_SALT =
        keccak256("union.salt.zkgm.stakeNFTManager");

    string internal constant STAKE_NFT_NAME = "Zkgm Staking Position";
    string internal constant STAKE_NFT_SYMBOL = "ZKGMSP";

    IIBCModulePacket private _deprecated_ibcHandler;
    mapping(bytes32 => IBCPacket) public inFlightPacket;
    mapping(address => uint256) public tokenOrigin;
    mapping(uint32 => mapping(uint256 => mapping(address => uint256))) public
        _deprecated_channelBalanceV1;
    uint256 public _deprecated_channelGovernanceToken;
    uint256 public _deprecated_stakes;
    mapping(address => bytes32) public metadataImageOf;
    mapping(
        uint32
            => mapping(uint256 => mapping(address => mapping(bytes => uint256)))
    ) public channelBalanceV2;

    function decodeZkgmERC20InitializeCall(
        bytes calldata call
    )
        external
        pure
        returns (address, address, string memory, string memory, uint8)
    {
        bytes4 selector = bytes4(call.slice(0, 4));
        bytes4 expectedSelector = ZkgmERC20.initialize.selector;
        require(selector == expectedSelector);
        return
            abi.decode(call.slice(4), (address, address, string, string, uint8));
    }

    function decodeRelayerMessage(
        bytes calldata relayerMsg
    ) external pure returns (bool, bytes memory) {
        return abi.decode(relayerMsg, (bool, bytes));
    }

    function _increaseOutstandingV2(
        uint32 sourceChannelId,
        uint256 path,
        address baseToken,
        bytes calldata quoteToken,
        uint256 amount
    ) internal {
        channelBalanceV2[sourceChannelId][path][baseToken][quoteToken] += amount;
    }

    function _decreaseOutstandingV2(
        uint32 sourceChannelId,
        uint256 path,
        address baseToken,
        bytes calldata quoteToken,
        uint256 amount
    ) internal {
        channelBalanceV2[sourceChannelId][path][baseToken][quoteToken] -= amount;
    }

    // Predict a wrapped token address given the path/channel and counterparty
    // address of the token. The computed address is fully deterministic w.r.t
    // to (ucs03Address, path, channel, token).
    function _predictWrappedToken(
        uint256 path,
        uint32 channel,
        bytes calldata token
    ) internal view returns (address, bytes32) {
        bytes32 wrappedTokenSalt =
            EfficientHashLib.hash(abi.encode(path, channel, token));
        address wrappedToken =
            CREATE3.predictDeterministicAddress(wrappedTokenSalt);
        return (wrappedToken, wrappedTokenSalt);
    }

    function _predictWrappedTokenFromMetadataImageV2(
        uint256 path,
        uint32 channel,
        bytes memory token,
        bytes32 metadataImage
    ) internal view returns (address, bytes32) {
        bytes32 wrappedTokenSalt = EfficientHashLib.hash(
            abi.encode(path, channel, token, metadataImage)
        );
        address wrappedToken =
            CREATE3.predictDeterministicAddress(wrappedTokenSalt);
        return (wrappedToken, wrappedTokenSalt);
    }

    function _predictWrappedTokenV2(
        uint256 path,
        uint32 channel,
        bytes calldata token,
        TokenMetadata memory metadata
    ) internal returns (address, bytes32) {
        bytes32 metadataImage =
            EfficientHashLib.hash(ZkgmLib.encodeTokenMetadata(metadata));
        return _predictWrappedTokenFromMetadataImageV2(
            path, channel, token, metadataImage
        );
    }

    function _predictProxyAccount(
        uint256 path,
        uint32 channelId,
        bytes calldata sender
    ) internal returns (bytes32, address) {
        bytes32 proxySalt =
            EfficientHashLib.hash(abi.encode(path, channelId, sender));
        return (proxySalt, CREATE3.predictDeterministicAddress(proxySalt));
    }
}
"
    },
    "libs/@openzeppelin-upgradeable/contracts/proxy/utils/Initializable.sol": {
      "content": "// 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
        }
    }
}
"
    },
    "libs/@openzeppelin-upgradeable/contracts/proxy/utils/UUPSUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/utils/UUPSUpgradeable.sol)

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 */
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

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

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    function __UUPSUpgradeable_init() internal onlyInitializing {
    }

    function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view virtual notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     * See {_onlyProxy}.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}
"
    },
    "libs/@openzeppelin-upgradeable/contracts/access/manager/AccessManagedUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/manager/AccessManaged.sol)

pragma solidity ^0.8.20;

import {IAuthority} from "@openzeppelin/contracts/access/manager/IAuthority.sol";
import {AuthorityUtils} from "@openzeppelin/contracts/access/manager/AuthorityUtils.sol";
import {IAccessManager} from "@openzeppelin/contracts/access/manager/IAccessManager.sol";
import {IAccessManaged} from "@openzeppelin/contracts/access/manager/IAccessManaged.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev This contract module makes available a {restricted} modifier. Functions decorated with this modifier will be
 * permissioned according to an "authority": a contract like {AccessManager} that follows the {IAuthority} interface,
 * implementing a policy that allows certain callers to access certain functions.
 *
 * IMPORTANT: The `restricted` modifier should never be used on `internal` functions, judiciously used in `public`
 * functions, and ideally only used in `external` functions. See {restricted}.
 */
abstract contract AccessManagedUpgradeable is Initializable, ContextUpgradeable, IAccessManaged {
    /// @custom:storage-location erc7201:openzeppelin.storage.AccessManaged
    struct AccessManagedStorage {
        address _authority;

        bool _consumingSchedule;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessManaged")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant AccessManagedStorageLocation = 0xf3177357ab46d8af007ab3fdb9af81da189e1068fefdc0073dca88a2cab40a00;

    function _getAccessManagedStorage() private pure returns (AccessManagedStorage storage $) {
        assembly {
            $.slot := AccessManagedStorageLocation
        }
    }

    /**
     * @dev Initializes the contract connected to an initial authority.
     */
    function __AccessManaged_init(address initialAuthority) internal onlyInitializing {
        __AccessManaged_init_unchained(initialAuthority);
    }

    function __AccessManaged_init_unchained(address initialAuthority) internal onlyInitializing {
        _setAuthority(initialAuthority);
    }

    /**
     * @dev Restricts access to a function as defined by the connected Authority for this contract and the
     * caller and selector of the function that entered the contract.
     *
     * [IMPORTANT]
     * ====
     * In general, this modifier should only be used on `external` functions. It is okay to use it on `public`
     * functions that are used as external entry points and are not called internally. Unless you know what you're
     * doing, it should never be used on `internal` functions. Failure to follow these rules can have critical security
     * implications! This is because the permissions are determined by the function that entered the contract, i.e. the
     * function at the bottom of the call stack, and not the function where the modifier is visible in the source code.
     * ====
     *
     * [WARNING]
     * ====
     * Avoid adding this modifier to the https://docs.soliditylang.org/en/v0.8.20/contracts.html#receive-ether-function[`receive()`]
     * function or the https://docs.soliditylang.org/en/v0.8.20/contracts.html#fallback-function[`fallback()`]. These
     * functions are the only execution paths where a function selector cannot be unambiguously determined from the calldata
     * since the selector defaults to `0x00000000` in the `receive()` function and similarly in the `fallback()` function
     * if no calldata is provided. (See {_checkCanCall}).
     *
     * The `receive()` function will always panic whereas the `fallback()` may panic depending on the calldata length.
     * ====
     */
    modifier restricted() {
        _checkCanCall(_msgSender(), _msgData());
        _;
    }

    /// @inheritdoc IAccessManaged
    function authority() public view virtual returns (address) {
        AccessManagedStorage storage $ = _getAccessManagedStorage();
        return $._authority;
    }

    /// @inheritdoc IAccessManaged
    function setAuthority(address newAuthority) public virtual {
        address caller = _msgSender();
        if (caller != authority()) {
            revert AccessManagedUnauthorized(caller);
        }
        if (newAuthority.code.length == 0) {
            revert AccessManagedInvalidAuthority(newAuthority);
        }
        _setAuthority(newAuthority);
    }

    /// @inheritdoc IAccessManaged
    function isConsumingScheduledOp() public view returns (bytes4) {
        AccessManagedStorage storage $ = _getAccessManagedStorage();
        return $._consumingSchedule ? this.isConsumingScheduledOp.selector : bytes4(0);
    }

    /**
     * @dev Transfers control to a new authority. Internal function with no access restriction. Allows bypassing the
     * permissions set by the current authority.
     */
    function _setAuthority(address newAuthority) internal virtual {
        AccessManagedStorage storage $ = _getAccessManagedStorage();
        $._authority = newAuthority;
        emit AuthorityUpdated(newAuthority);
    }

    /**
     * @dev Reverts if the caller is not allowed to call the function identified by a selector. Panics if the calldata
     * is less than 4 bytes long.
     */
    function _checkCanCall(address caller, bytes calldata data) internal virtual {
        AccessManagedStorage storage $ = _getAccessManagedStorage();
        (bool immediate, uint32 delay) = AuthorityUtils.canCallWithDelay(
            authority(),
            caller,
            address(this),
            bytes4(data[0:4])
        );
        if (!immediate) {
            if (delay > 0) {
                $._consumingSchedule = true;
                IAccessManager(authority()).consumeScheduledOp(caller, data);
                $._consumingSchedule = false;
            } else {
                revert AccessManagedUnauthorized(caller);
            }
        }
    }
}
"
    },
    "libs/@openzeppelin-upgradeable/contracts/utils/PausableUpgradeable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        PausableStorage storage $ = _getPausableStorage();
        return $._paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
        emit Unpaused(_msgSender());
    }
}
"
    },
    "libs/@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol": {
      "content": "// 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();
    }
}
"
    },
    "libs/@openzeppelin/contracts/token/ERC20/IERC20.sol": {
      "content": "// 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);
}
"
    },
    "libs/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0-rc.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.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 sa

Tags:
ERC20, ERC721, ERC165, Multisig, Mintable, Burnable, Non-Fungible, Staking, Yield, Voting, Upgradeable, Multi-Signature, Factory|addr:0x92ca187fc3e1d56677191e89a5e565d2dc321d32|verified:true|block:23382687|tx:0x0265fa352b4ef74b03f5bcd4906f1218dca4c3d686d9cf7cca398138c58af6a7|first_check:1758121587

Submitted on: 2025-09-17 17:06:29

Comments

Log in to comment.

No comments yet.