Executor

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": {
    "rainlink-contract-main/token/Executor.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

import "@openzeppelin/contracts@5.0.0/utils/math/Math.sol";
import "@openzeppelin/contracts@5.0.0/utils/Address.sol";
import "@openzeppelin/contracts@5.0.0/utils/Strings.sol";
import {Types} from "../comn/Types.sol";
import {IPool} from "../comn/IPool.sol";
import {IMessager} from "../comn/IMessager.sol";
import {IToken} from "../comn/IToken.sol";
import {ComFunUtil} from "../comn/ComFunUtil.sol";
import {SafeERC20} from "../comn/SafeERC20.sol";
import {BridgeToken} from "./Token.sol";
import {Comn} from "./Comn.sol";

/**
 * @title Executor
 * @dev This contract inherits from the Comn contract and is mainly used to manage cross - chain token relationships,
 * create new tokens, handle cross - chain token bridging, and process messages.
 */
contract Executor is Comn {
    using Strings for uint;
    // Mapping from source chain ID to source token to relationship information.
    // It stores the relationship information between tokens on different source chains and tokens on the destination chain.
    mapping(uint => mapping(bytes32 => Types.RelationShipInfo))
        public tokenRelationshipMap;

    // Mapping from source chain ID to source token to source token information.
    // It stores relevant information about tokens on different source chains.
    mapping(uint => mapping(bytes32 => Types.SourceTokenInfo))
        public sourceTokenInfoMap;

    // Array that stores cross - chain relationship information.
    // It contains all the relevant information about cross - chain tokens.
    Types.CrossRelation[] public crossArr;

    // Mapping from the address of a new ERC20 token to its status.
    // It records newly created tokens and their status.
    mapping(address => uint) public newMintMap;

    // Mapping from chain ID to contract address.
    // It stores the contract addresses corresponding to different chains.
    mapping(uint => bytes32) public chainContractMap;

    // Mapping from chain ID to fee token address.
    // It stores the fee token addresses corresponding to different chains.
    mapping(uint => bytes32) public chainFeeTokenMap;

    event TokenRelationshipSet(
        uint indexed source_chain_id,
        bytes32 indexed source_token,
        uint8 source_token_decimals,
        address dest_token,
        uint8 dest_token_type
    );

    event TokenRelationshipRemoved(
        uint indexed source_chain_id,
        bytes32 indexed source_token
    );

    event LogBizData(uint128 indexed amount, bytes biz_data);

    /**
     * @dev Sets the contract address for a specified chain. This function can only be called by the administrator.
     * @param source_chain_id The ID of the source chain.
     * @param contract_addr The address of the contract.
     */
    function setChainContract(
        uint source_chain_id,
        bytes32 contract_addr
    ) public onlyAdmin {
        chainContractMap[source_chain_id] = contract_addr;
    }

    /**
     * @dev Sets the fee token address for a specified chain. This function can only be called by the administrator.
     * @param source_chain_id The ID of the source chain.
     * @param fee_token_addr The address of the fee token.
     */
    function setChainFeeToken(
        uint source_chain_id,
        bytes32 fee_token_addr
    ) public onlyAdmin {
        chainFeeTokenMap[source_chain_id] = fee_token_addr;
    }

    /**
     * @dev Sets the token relationship. Before setting the relationship, the pool or minted token must exist.
     * This function can only be called by the administrator.
     * @param source_chain_id The combined chain type and chain ID of the source chain.
     * @param source_token The source token in bytes32 format.
     * @param source_token_decimals The number of decimals of the source token.
     * @param _dest_token The destination token in bytes32 format.
     * @param dest_token_type The type of the destination token.
     */
    function setTokenRelationship(
        uint source_chain_id, // combain chain_type&chain_id
        bytes32 source_token,
        uint8 source_token_decimals,
        bytes32 _dest_token,
        uint8 dest_token_type
    ) public onlyAdmin {
        address dest_token = ComFunUtil.bytes32ToAddress(_dest_token);
        if (dest_token_type == uint8(Types.TokenType.pool)) {
            // 0 means pool map
            require(
                IPool(PoolAddr).getPoolInfo(dest_token).token != address(0),
                "no token for type 0"
            );
        } else {
            // 1 means mint token.
            require(newMintMap[dest_token] > 0, "no token for type 1");
        }
        require(
            tokenRelationshipMap[source_chain_id][source_token].dest_token ==
                address(0),
            "has been set"
        );

        tokenRelationshipMap[source_chain_id][source_token] = Types
            .RelationShipInfo(dest_token, dest_token_type);

        sourceTokenInfoMap[source_chain_id][source_token] = Types
            .SourceTokenInfo(1, source_token_decimals);

        crossArr.push(
            Types.CrossRelation(
                source_chain_id,
                source_token,
                source_token_decimals,
                dest_token,
                dest_token_type
            )
        );

        emit TokenRelationshipSet(
            source_chain_id,
            source_token,
            source_token_decimals,
            dest_token,
            dest_token_type
        );
    }

    /**
     * @dev Removes the token relationship. This function can only be called by the administrator.
     * @param source_chain_id The ID of the source chain.
     * @param source_token The source token in bytes32 format.
     */
    function removeTokenRelationship(
        uint source_chain_id,
        bytes32 source_token
    ) public onlyAdmin {
        // Types.RelationShipInfo memory data;
        delete tokenRelationshipMap[source_chain_id][source_token];
        delete sourceTokenInfoMap[source_chain_id][source_token];

        for (uint i = 0; i < crossArr.length; i++) {
            Types.CrossRelation memory data = crossArr[i];
            if (
                data.source_chain_id == source_chain_id &&
                data.source_token == source_token
            ) {
                crossArr[i] = crossArr[crossArr.length - 1];
                crossArr.pop();

                emit TokenRelationshipRemoved(source_chain_id, source_token);
                break;
            }
        }
    }

    /**
     * @dev Creates a new token for minting on the local chain. This function can only be called by the administrator.
     * @param name The name of the token.
     * @param symbol The symbol of the token.
     * @param decimals The number of decimals of the token.
     * @return The address of the newly created token.
     */
    function createNewToken(
        string memory name,
        string memory symbol,
        uint8 decimals
    ) public onlyAdmin returns (address) {
        BridgeToken newToken = new BridgeToken{salt: bytes32(0)}(
            name,
            symbol,
            decimals,
            address(this)
        );

        emit Types.Log("newToken", address(newToken));

        if (newMintMap[address(newToken)] != 0) {
            revert("token already in use");
        }
        newMintMap[address(newToken)] = 1;

        return address(newToken);
    }

    /**
     * @dev Bridges a token across chains.
     * @param source_token The source token in bytes32 format.
     * @param to_chain The destination chain information.
     * @param to_who The recipient in bytes32 format on the destination chain.
     * @param receiver The destination bridger in bytes32 format.
     * @param all_amount The total amount of tokens to be bridged.
     * @param upload_gas_fee The gas fee for uploading, converted from the target platform token to the source platform token.
     */
    function bridgeToken(
        bytes32 source_token,
        Types.Chain memory to_chain,
        bytes32 to_who,
        bytes32 receiver, // destination bridger
        uint128 all_amount,
        uint128 upload_gas_fee // convert target platform token to source platform token
    ) public payable {
        bridgeToken(
            source_token,
            to_chain,
            to_who,
            receiver,
            all_amount,
            upload_gas_fee,
            new bytes(0)
        );
    }

    /**
     * @dev Bridges a token across chains.
     * @param source_token The source token in bytes32 format.
     * @param to_chain The destination chain information.
     * @param to_who The recipient in bytes32 format on the destination chain.
     * @param receiver The destination bridger in bytes32 format.
     * @param all_amount The total amount of tokens to be bridged.
     * @param upload_gas_fee The gas fee for uploading, converted from the target platform token to the source platform token.
     */
    function bridgeToken(
        bytes32 source_token,
        Types.Chain memory to_chain,
        bytes32 to_who,
        bytes32 receiver, // destination bridger
        uint128 all_amount,
        uint128 upload_gas_fee, // convert target platform token to source platform token
        bytes memory biz_data
    ) public payable {
        uint all_value = msg.value;
        uint msger_value;

        // transfer gas fee to pool
        require(all_value >= upload_gas_fee, "please send enough gas");
        msger_value = all_value - upload_gas_fee;
        IPool(PoolAddr).sendEthFee{value: upload_gas_fee}(WTOKEN_ADDRESS);

        address source_address = ComFunUtil.bytes32ToAddress(source_token);
        // exist in poolMap
        if (IPool(PoolAddr).getPoolInfo(source_address).token != address(0)) {
            if (isWToken(source_address)) {
                require(
                    all_value >= all_amount + upload_gas_fee,
                    "please send enough value, or adjust amount"
                );
                msger_value = all_value - all_amount - upload_gas_fee;
                IPool(PoolAddr).sendEthFee{value: all_amount}(WTOKEN_ADDRESS);
            } else {
                SafeERC20.safeTransferFrom(
                    IToken(source_address),
                    msg.sender,
                    address(this),
                    all_amount
                );
                uint256 allowance = IToken(source_address).allowance(
                    address(this),
                    PoolAddr
                );
                if (allowance < all_amount) {
                    SafeERC20.safeIncreaseAllowance(
                        IToken(source_address),
                        PoolAddr,
                        type(uint256).max
                    );
                }
                IPool(PoolAddr).sendTokenFee(source_address, all_amount);
            }
        } else if (newMintMap[source_address] > 0) {
            // burn token.
            IToken tokenOp = IToken(source_address);
            tokenOp.burnFor(msg.sender, all_amount);
        } else {
            revert("source token not supported");
        }

        //  all amount = amount + platform_fee + upload_gas_fee * upload_fee_price
        bytes memory messageBody = abi.encodePacked(
            source_token, // source_token
            uint128(all_amount), // all_amount
            // upload_gas_fee, // upload_gas_fee
            ComFunUtil.addressToBytes32(address(msg.sender)), // from_who
            to_who, // to
            biz_data
            // slipage
        );

        IMessager(MessagerAddr).emit_msg{value: msger_value}(
            0,
            to_chain,
            receiver,
            messageBody,
            upload_gas_fee
        );
    }

    /**
     * @dev Processes a received message.
     * @param message The received message.
     * @param signature The array of signatures for the message. Each signature is 65 bytes.
     * @return A boolean indicating whether the message was processed successfully.
     */
    function processMsg(
        Types.Message memory message,
        bytes[] memory signature // 65bytes for one signature
    ) public returns (bool) {
        (
            Types.MessageHeader memory msg_header,
            Types.BridgeMessageBody memory msg_body
        ) = decode_bridge_msg(message);

        uint from_chain = ComFunUtil.combainChain(msg_header.from_chain);
        require(
            address(this) == ComFunUtil.bytes32ToAddress(msg_header.receiver),
            "processMsg receiver error"
        );
        require(
            chainContractMap[from_chain] == msg_header.sender,
            "processMsg sender error"
        );

        bytes32 source_token = msg_body.source_token;
        (
            bool exist,
            Types.RelationShipInfo memory tokenRInfo
        ) = getStrictTokenRelationship(from_chain, source_token);

        if (!exist) {
            revert("no token relation ship");
        }

        bool consume_success = IMessager(MessagerAddr).consume_bridge_msg(
            message,
            signature
        );
        if (
            !consume_success &&
            msg.sender != address(0x0000000000000000000000000000000000000001)
        ) {
            revert("nonce has been uploaded");
        }

        // amount decimal process
        bytes32 to_who = msg_body.to_who;
        uint all_amount = msg_body.all_amount;
        Types.SourceTokenInfo
            memory source_token_info = getStrictSourceTokenInfo(
                from_chain,
                source_token
            );
        IToken tokenOp = IToken(tokenRInfo.dest_token);
        uint8 dest_decimals = tokenOp.decimals();

        if (dest_decimals > source_token_info.decimals) {
            all_amount =
                all_amount *
                10 ** (dest_decimals - source_token_info.decimals);
        } else if (dest_decimals < source_token_info.decimals) {
            all_amount =
                all_amount /
                10 ** (source_token_info.decimals - dest_decimals);
        }

        if (tokenRInfo.dest_token_type == uint8(Types.TokenType.pool)) {
            IPool(PoolAddr).transferFromPool(
                tokenRInfo.dest_token,
                ComFunUtil.bytes32ToAddress(to_who),
                all_amount
            );
        } else {
            // only mint token
            BridgeToken destTokenOp = BridgeToken(tokenRInfo.dest_token);
            destTokenOp.mintFor(
                ComFunUtil.bytes32ToAddress(to_who),
                all_amount
            );
        }

        {
            // mint gas_fee to sender
            uint128 gas_fee = msg_header.upload_gas_fee;
            if (gas_fee > 0) {
                emit Types.Log("send gas fee to sender", gas_fee);
                bytes32 fee_token = chainFeeTokenMap[from_chain];
                (exist, tokenRInfo) = getStrictTokenRelationship(
                    from_chain,
                    fee_token
                );
                if (!exist) {
                    revert("no token relation ship for fee token");
                }
                Types.SourceTokenInfo
                    memory fee_token_info = getStrictSourceTokenInfo(
                        from_chain,
                        fee_token
                    );
                tokenOp = IToken(tokenRInfo.dest_token);
                uint8 fee_dest_decimals = tokenOp.decimals();

                if (fee_dest_decimals > fee_token_info.decimals) {
                    gas_fee = uint128(
                        uint(gas_fee) *
                            10 ** (fee_dest_decimals - fee_token_info.decimals)
                    );
                } else if (fee_dest_decimals < source_token_info.decimals) {
                    gas_fee = uint128(
                        uint(gas_fee) /
                            10 ** (fee_token_info.decimals - fee_dest_decimals)
                    );
                }

                if (tokenRInfo.dest_token_type == uint8(Types.TokenType.pool)) {
                    IPool(PoolAddr).transferFeeToRelay(
                        tokenRInfo.dest_token,
                        msg.sender,
                        gas_fee
                    );
                } else {
                    BridgeToken destTokenOp = BridgeToken(
                        tokenRInfo.dest_token
                    );
                    destTokenOp.mintFor(msg.sender, gas_fee);
                }
            }
        }

        // Check if biz_data has value and call it directly in the contract
        if (msg_body.biz_data.length > 0) {
            emit LogBizData(msg_body.all_amount, msg_body.biz_data);
        }

        return true;
    }

    /**
     * @dev Calculates the LP fee and the final amount after fee deduction.
     * @param source_chain_id The ID of the source chain.
     * @param source_token The source token in bytes32 format.
     * @param all_amount The total amount of tokens.
     * @return lp_fee The LP fee and the final amount after fee deduction.
     */
    function getLpFeeAndFinalAmount(
        uint source_chain_id,
        bytes32 source_token,
        uint all_amount
    ) public view returns (uint lp_fee, uint final_amount) {
        (
            bool exist,
            Types.RelationShipInfo memory tokenRInfo
        ) = getStrictTokenRelationship(source_chain_id, source_token);
        if (!exist) {
            return (0, 0);
        }
        if (tokenRInfo.dest_token_type == uint8(Types.TokenType.pool)) {
            uint pool_fee = IPool(PoolAddr).getLpFee(
                tokenRInfo.dest_token,
                all_amount
            );
            uint amount = all_amount - pool_fee;
            return (pool_fee, amount);
        } else {
            return (0, all_amount);
        }
    }

    /**
     * @dev Decodes a bridge message.
     * @param decMsg The message to be decoded.
     * @return The message header and the bridge message body.
     */
    function decode_bridge_msg(
        Types.Message memory decMsg
    )
        public
        pure
        returns (Types.MessageHeader memory, Types.BridgeMessageBody memory)
    {
        Types.BridgeMessageBody memory bridgeMsgBody = IMessager(MessagerAddr)
            .decode_bridge_msg_body(decMsg.msg_body);

        return (decMsg.msg_header, bridgeMsgBody);
    }

    /**
     * @dev Retrieves all cross - chain relationship information.
     * @return An array containing all cross - chain relationship information.
     */
    function getAllCrossRelation()
        public
        view
        returns (Types.CrossRelation[] memory)
    {
        return crossArr;
    }

    /**
     * @dev Retrieves the token relationship information.
     * @param source_chain_id The ID of the source chain.
     * @param source_token The source token in bytes32 format.
     * @return A boolean indicating whether the relationship exists and the relationship information.
     */
    function getTokenRelationship(
        uint source_chain_id,
        bytes32 source_token
    ) public view returns (bool, Types.RelationShipInfo memory) {
        Types.RelationShipInfo memory data = tokenRelationshipMap[
            source_chain_id
        ][source_token];
        if (data.dest_token == address(0)) {
            return (false, data);
        }
        return (true, data);
    }

    /**
     * @dev Retrieves the strict token relationship information. Checks if the destination token exists in the pool or mint map.
     * @param source_chain_id The ID of the source chain.
     * @param source_token The source token in bytes32 format.
     * @return A boolean indicating whether the relationship exists and the relationship information.
     */
    function getStrictTokenRelationship(
        uint source_chain_id,
        bytes32 source_token
    ) public view returns (bool, Types.RelationShipInfo memory) {
        Types.RelationShipInfo memory data = tokenRelationshipMap[
            source_chain_id
        ][source_token];
        if (data.dest_token == address(0)) {
            return (false, data);
        }

        if (data.dest_token_type == uint8(Types.TokenType.pool)) {
            if (
                IPool(PoolAddr).getPoolInfo(data.dest_token).token == address(0)
            ) {
                return (false, data);
            }
        } else {
            if (newMintMap[data.dest_token] == 0) {
                return (false, data);
            }
        }

        return (true, data);
    }

    /**
     * @dev Retrieves the source token information.
     * @param source_chain_id The ID of the source chain.
     * @param source_token The source token in bytes32 format.
     * @return The source token information.
     */
    function getSourceTokenInfo(
        uint source_chain_id,
        bytes32 source_token
    ) public view returns (Types.SourceTokenInfo memory) {
        return sourceTokenInfoMap[source_chain_id][source_token];
    }

    /**
     * @dev Retrieves the strict source token information. Ensures the source token information is initialized.
     * @param source_chain_id The ID of the source chain.
     * @param source_token The source token in bytes32 format.
     * @return rs The source token information. Reverts if the information is not initialized.
     */
    function getStrictSourceTokenInfo(
        uint source_chain_id,
        bytes32 source_token
    ) public view returns (Types.SourceTokenInfo memory rs) {
        rs = sourceTokenInfoMap[source_chain_id][source_token];
        if (rs.initialized == 0) {
            revert("source token info is empty");
        }
    }

    /**
     * @dev Checks if a given token is the wrapped token.
     * @param token The address of the token to check.
     * @return A boolean indicating whether the token is the wrapped token.
     */
    function isWToken(address token) public pure returns (bool) {
        return token == WTOKEN_ADDRESS;
    }
}
"
    },
    "rainlink-contract-main/token/Comn.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

import "../BaseComn.sol";

/**
 * @title all sol extends from this
 * @dev Extends BaseComn with additional address constants
 */
abstract contract Comn is BaseComn {
    // xone
    address constant WTOKEN_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
    address constant PoolAddr = address(0x4aeDc117527fD270D4d56aA32f2E4e532547c8Dc);
    address constant ExecutorAddr = address(0x5B6C580F2Af1eDD51349716f40A9104Bd918aef7);
    address constant MessagerAddr = address(0xda6869A6435c3bef2Ece47cD1B0B020ffc62E1A3);

    // tbsc
    // address constant WTOKEN_ADDRESS = address(0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd);
    // address constant PoolAddr = address(0x38f9c465128F3139Ca70707eA7232568aC89C42B);
    // address constant ExecutorAddr = address(0xc8C4087c56B47e4658F54b925aF607118D461798);
    // address constant MessagerAddr = address(0xF2B99D50bdb83110aBf94cA7cD98057E95302D83);

    // sepolia
    // address constant WTOKEN_ADDRESS = address(0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14);
    // address constant PoolAddr = address(0x5Dab805f174FA4e66aeE1947978e055C61e16AB2);
    // address constant ExecutorAddr = address(0x3B43c5B5c83b683ecE682e4ed8a75ec81BB55248);
    // address constant MessagerAddr = address(0xb2E08E9840Cd02dE0002189BBd2Bc24333a7c9D2);

    // nile
    // address constant WTOKEN_ADDRESS = address(0xfb3b3134F13CcD2C81F4012E53024e8135d58FeE); //TYsbWxNnyTgsZaTFaue9hqpxkU3Fkco94a
    // address constant PoolAddr = address(0x273Ea2807918A51D7e4D0E47779365391105eFa4); //TDYiPUqKWvFSu3qpgTP4ctNXPQqaxPnJXp
    // address constant ExecutorAddr = address(0x7b6229abeE4D531D7ae82b00f5b8F52D0a5764EB); //TMDbi88CTghZj88NbGKn4NPnzWptrH453B
    // address constant MessagerAddr = address(0x181Ff0aEd1d4a5829936322363D992D570c8f0c3); //TCAmUuRamPsA5m862JQUpDaJkDTGznpV6y
}
"
    },
    "rainlink-contract-main/token/Token.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

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

contract BridgeToken is ERC20 {
    // the minter address
    address private _minter;

    // decimals
    uint8 private _decimals;

    /**
     * @dev Throws if called by any account other than the master.
     */
    modifier onlyMinter() {
        require(msg.sender == _minter, "Must minter");
        _;
    }

    /**
     * @dev construct
     */
    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_,
        address minter_
    ) ERC20(name_, symbol_) {
        _decimals = decimals_;
        _minter = minter_;
    }

    /**
     * @dev set decimals 6, same as usdt
     */
    function decimals() public view virtual override returns (uint8) {
        return _decimals;
    }

    /**
     * @dev Get the address is the minter
     */
    function isMinter(address addr) public view returns (bool) {
        return _minter == addr;
    }

    /**
     * @dev bridge mint token
     */
    function mintFor(address account, uint256 amount) public onlyMinter {
        _mint(account, amount);
    }

    /**
     * @dev bridge burn token
     */
    function burnFor(address account, uint256 amount) public onlyMinter {
        _burn(account, amount);
    }
}
"
    },
    "rainlink-contract-main/comn/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.20;
import "@openzeppelin/contracts@5.0.0/token/ERC20/IERC20.sol";

library SafeERC20 {
    // mainnet:0xa614f803B6FD780986A42c78Ec9c7f77e6DeD13C
    address constant USDTAddr = 0xa614f803B6FD780986A42c78Ec9c7f77e6DeD13C;
    
    function safeIncreaseAllowance(IERC20 token, address to, uint value) internal {
        uint newAllowance = token.allowance(address(this), to) + value;
        safeApprove(token, to, newAllowance);
    }
    
    function safeApprove(IERC20 token, address to, uint value) internal {
        // bytes4(keccak256(bytes('approve(address,uint256)')));
        (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x095ea7b3, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
    }

    function safeTransfer(IERC20 token, address to, uint value) internal {
        // bytes4(keccak256(bytes('transfer(address,uint256)')));
        (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, value));
        if (address(token) == USDTAddr && success) {
            return;
        }
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
    }

    function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
        // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
        (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
    }
}
"
    },
    "rainlink-contract-main/comn/ComFunUtil.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

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

library ComFunUtil {
    function isNotEmpty(address ad, string memory msgs) private pure {
        require(ad != address(0), msgs);
    }

    function isNotEmpty(uint ad, string memory msgs) private pure {
        require(ad != 0, msgs);
    }

    function combainChain(
        Types.Chain memory chain_
    ) internal pure returns (uint72) {
        uint72 c = chain_.chain_id;
        // must use uint72 to avoid u8 overflow
        uint72 chain_type = chain_.chain_type;
        c += chain_type << 64;
        return c;
    }

    function splitChain(uint a1) internal pure returns (Types.Chain memory c) {
        c.chain_id = uint64(a1);
        c.chain_type = uint8(a1 >> 64);
    }

    function addressToBytes32(address a) internal pure returns (bytes32 b) {
        return bytes32(uint(uint160(a)));
    }

    function bytes32ToAddress(bytes32 a) internal pure returns (address b) {
        return address(uint160(uint(a)));
    }

    function hexStr2bytes32(string memory data) internal pure returns (bytes32) {
        return bytes2bytes32(hexStr2bytes(data));
    }

    function bytes2bytes32(bytes memory data) internal pure returns (bytes32) {
        uint len = data.length;
        if (len > 32) {
            revert("data len is overflow 32");
        }

        uint rs = 0;
        for (uint i = 0; i < len; i++) {
            rs = rs << 8;
            rs += uint8(data[i]);
        }

        return bytes32(rs);
    }

    // convert hex string to bytes
    function hexStr2bytes(
        string memory data
    ) internal pure returns (bytes memory) {
        bytes memory a = bytes(data);
        if (a.length % 2 != 0) {
            revert("hex string len is invalid");
        }
        uint8[] memory b = new uint8[](a.length);

        for (uint i = 0; i < a.length; i++) {
            uint8 _a = uint8(a[i]);

            if (_a > 96) {
                b[i] = _a - 97 + 10;
            } else if (_a > 66) {
                b[i] = _a - 65 + 10;
            } else {
                b[i] = _a - 48;
            }
        }

        bytes memory c = new bytes(b.length / 2);
        for (uint _i = 0; _i < b.length; _i += 2) {
            c[_i / 2] = bytes1(b[_i] * 16 + b[_i + 1]);
        }

        return c;
    }

    function stringConcat(
        string memory a,
        string memory b,
        bytes memory d
    ) internal pure returns (string memory) {
        bytes memory a1 = bytes(a);
        bytes memory a2 = bytes(b);
        bytes memory a3;
        a3 = new bytes(a1.length + a2.length + d.length);
        uint k = 0;
        for (uint i = 0; i < a1.length; i++) {
            a3[k++] = a1[i];
        }

        for (uint i = 0; i < d.length; i++) {
            a3[k++] = d[i];
        }

        for (uint i = 0; i < a2.length; i++) {
            a3[k++] = a2[i];
        }

        return string(a3);
    }

    function currentTimestamp() internal view returns (uint256) {
        return block.timestamp;
    }
}
"
    },
    "rainlink-contract-main/comn/IToken.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

import "@openzeppelin/contracts@5.0.0/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts@5.0.0/token/ERC20/extensions/IERC20Metadata.sol";

interface IToken is IERC20, IERC20Metadata {
    function isMinter(address addr) external pure returns (bool);
    function mintFor(address account, uint256 amount) external;
    function burnFor(address account, uint256 amount) external;
}"
    },
    "rainlink-contract-main/comn/IMessager.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;
import "./Types.sol";

interface IMessager {
    event Msg(Types.Message);
    event UploadFee(uint);

    function set_bridge_fee(uint v) external;

    function verify_msg(
        Types.Message memory messageDec,
        // uint16[] memory signer_index,
        bytes[] memory signature
    ) external returns (bool);

    function decode_msg(
        bytes memory message
    ) external pure returns (Types.Message memory);

    function decode_bridge_msg_body(
        bytes memory msg_body
    ) external pure returns (Types.BridgeMessageBody memory);

    // verify and consume it.
    function consume_bridge_msg(
        Types.Message memory messageDec,
        bytes[] memory signature
    ) external returns (bool);

    function emit_msg(
        uint8 msg_type,
        Types.Chain memory to_chain,
        bytes32 receiver,
        bytes memory message,
        uint128 upload_gas_fee // source p token.
    ) external payable;

    function withdrawFee(uint amount) external;
}
"
    },
    "rainlink-contract-main/comn/IPool.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1\r
pragma solidity ^0.8.20;\r
\r
import "./Types.sol";\r
\r
interface IPool {\r
    function createPool(\r
        address token // already exist in chain.\r
    ) external;\r
\r
    // stake into pool and record some information. no lp will be created.\r
    // use msg.sender as staker\r
    function stakeIntoPool(address stakeToken, uint amount) external payable;\r
\r
    // we use msg.sender and get the amount\r
    function withdrawFromPool(address stakeToken, uint amount) external;\r
\r
    // only withdraw the bonus.\r
    function withdrawBonusFromPool(address stakeToken, uint amount) external;\r
\r
    function getPoolInfo(\r
        address stakeToken\r
    ) external view returns (Types.PoolInfo memory);\r
\r
    function getAllPoolsInfo()\r
        external\r
        view\r
        returns (Types.PoolInfo[] memory rs);\r
\r
    function getAllUserStakeInfo(\r
        address user\r
    ) external view returns (Types.UserAmountInfoForViewV2[] memory);\r
\r
    function transferFromPool(\r
        address destToken,\r
        address toWho,\r
        uint allAmount\r
    ) external;\r
\r
    function calBonusFromPool(\r
        address user,\r
        address stakeToken\r
    ) external view returns (uint bonus);\r
\r
    function getLpFee(address token, uint amount) external view returns (uint);\r
\r
    function sendEthFee(address token) external payable;\r
\r
    function sendTokenFee(address token, uint amount) external;\r
\r
    function withdrawFee(address token, uint amount) external;\r
\r
    function transferFeeToRelay(\r
        address token,\r
        address relay,\r
        uint amount\r
    ) external;\r
}\r
"
    },
    "rainlink-contract-main/comn/Types.sol": {
      "content": "// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

// all data in this file we should remain static.
// as this file may be used when create empty StoreHouse. to avoid any data not being initialized. we should keet it static.

library Types {
    event Log(string);
    event Log(string, bytes);
    event Log(uint);
    event Log(string, uint);
    event Log(string, bytes32);
    event Log(string, bytes32, uint);
    event Log(string, address);

    struct PoolInfo {
        address token;
        uint amount; // actual remain amount.
        uint inAmount; // all in token = all in lock amount + all in stake amount.
        uint lockAmount; // actual locked by contract
        uint stakeAmount; // actual user stake into contract.
        uint rewardAmount; // reward for staker, will used in future. now all reward will added to stake amount.
        uint acc; // Q64.64
        uint last_apy; // Q64.64
        uint last_receive_rewards_time;
    }

    enum AmountType {
        locked,
        staked
    }

    enum TokenType {
        pool,
        mint
    }

    struct UserAmountInfo {
        address token;
        uint8 amountType; // 0 locked value. 1 staked value.
        uint amount;
        uint debt;
        uint remainReward;
        // for locked user. all amount = amount
        // for stake user all amount = amount*acc - debt + amount + remainReward
    }

    // for front end.
    struct UserAmountInfoForView {
        address token;
        uint8 amountType; // 0 locked value. 1 staked value.
        uint amount;
        uint debt;
        uint remainReward;
        uint acc;
        uint bonus;
        // for locked user. all amount = amount
        // for stake user all amount = amount*acc - debt + amount + remainReward
    }

    // for front end.
    struct UserAmountInfoForViewV2 {
        address token;
        uint8 amountType; // 0 locked value. 1 staked value.
        uint amount;
        uint debt;
        uint remainReward;
        uint acc;
        uint bonus;
        // for locked user. all amount = amount
        // for stake user all amount = amount*acc - debt + amount + remainReward
        uint earns;
    }

    struct FromSource {
        uint source_chain_id;
        bytes32 source_token;
    }

    struct RelationShipInfo {
        address dest_token;
        uint8 dest_token_type; // 0 for pool, 1 for new mint
    }

    struct SourceTokenInfo {
        uint8 initialized;
        uint8 decimals; // record the decimals for source token
    }

    struct CrossRelation {
        uint source_chain_id;
        bytes32 source_token;
        uint8 source_token_decimals;
        address dest_token;
        uint8 dest_token_type;
    }

    struct MessageMeta {
        // BridgeMessage bridgeMsg;
        // // other fields
        uint8 status; //
        uint[4] reserves;
    }

    struct Chain {
        uint8 chain_type;
        uint64 chain_id;
    }

    enum ChainType {
        ETH,
        TRX,
        SOL
    }

    struct Message {
        MessageHeader msg_header;
        bytes msg_body;
    }

    struct MessageHeader {
        uint8 msg_type; // 0 means bridge message
        uint64 nonce;
        Chain from_chain; //
        bytes32 sender;
        // address messager;
        Chain to_chain; //
        bytes32 receiver;
        uint128 upload_gas_fee;
    }

    struct BridgeMessageBody {
        // body
        bytes32 source_token;
        uint128 all_amount;
        // uint amount;
        // uint platform_fee;

        // uint upload_fee_price; // all amount = amount + platform_fee + upload_gas_fee * upload_fee_price
        bytes32 from_who;
        bytes32 to_who;
        bytes biz_data;
        // uint slipage;
    }

    struct ERC20Permit {
        address owner;
        address spender;
        uint256 value;
        uint256 deadline;
        uint8 v;
        bytes32 r;
        bytes32 s;
    }

    struct UserWithdrawData {
        address token;
        uint amount; // uni decimal.
        // string symbol;
    }

    struct UserWithdrawDataDetail {
        address token;
        string symbol;
        string name;
        uint8 decimal;
        uint amount;
    }

    struct ErrorObj {
        uint key;
        uint error_type;
        string sMsg;
        uint cMsg;
        bytes bMsg;
        string desc; // description
    }
}
"
    },
    "@openzeppelin/contracts@5.0.0/utils/Strings.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;

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

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

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

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

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

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

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}
"
    },
    "@openzeppelin/contracts@5.0.0/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

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

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

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert AddressInsufficientBalance(address(this));
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert FailedInnerCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {FailedInnerCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert AddressInsufficientBalance(address(this));
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
     * unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {FailedInnerCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}
"
    },
    "@openzeppelin/contracts@5.0.0/utils/math/Math.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

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

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

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

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

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

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

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

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

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

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

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

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

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

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

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

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

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

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

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

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

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

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

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

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

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

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

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

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

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

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

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

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

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}
"
    },
    "@openzeppelin/contracts@5.0.0/token/ERC20/ERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *

Tags:
ERC20, Multisig, Upgradeable, Multi-Signature, Factory|addr:0x2874cd920bdb92c757d4094d97033b799c8cdc0a|verified:true|block:23403359|tx:0x800747bfd7ff3af30112c734b73bd31fc3825669fe92cdec1d316a2b78388066|first_check:1758371522

Submitted on: 2025-09-20 14:32:03

Comments

Log in to comment.

No comments yet.