Contract 0x3b53D2C7B44d40BE05Fa5E2309FFeB6eB2492d88

Txn Hash Method
Block
From
To
Value [Txn Fee]
0x785bad3ba8b3f9ae8ea79d5933c0946bb0fbe3f07274fb6589af58fbbae58f91Mint23514062022-12-04 20:51:063 days 15 hrs ago0xd10c833f4305e1053a64bc738c550381f48104ca IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.002120217
0x8d7dcb3e90b9bb8d6f32b3173a34bd7fbd2861ccc46d21010fb4e5211d7954f5Unpause21341102022-11-04 7:22:1234 days 4 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283316
0xcb7ca5251c24d0c6e3fc58f4d2aadcc7a84ba654b4a44db4a46f7281f10fe546Pause21340952022-11-04 7:19:1234 days 4 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283635
0x29c6d618ebc59eae76390674cae9e54a9c3b11e0df10a0fc799202f895adc0ddSet Min Burn21265422022-11-03 5:41:3035 days 6 hrs ago0x1b9dfc56e38b0f92448659c114e2347bd803911c IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000294866
0x60b450dcc586a9dab14e821d28c426c23e388e3acef5ccc4f2f76a002ca9b386Set Min Burn21264292022-11-03 5:18:5435 days 6 hrs ago0x1b9dfc56e38b0f92448659c114e2347bd803911c IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000298298
0x804661f56b85ea39a95871e09df49cd469402c474d7842661c2e8e0c3bdf1fd3Set Min Burn21125062022-11-01 6:09:0637 days 6 hrs ago0x1b9dfc56e38b0f92448659c114e2347bd803911c IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000294866
0x12f8f2066c0241865a4113f16a0c661369291851f20a312ceb535fbd16163b15Set Min Burn21123462022-11-01 5:37:0637 days 6 hrs ago0x1b9dfc56e38b0f92448659c114e2347bd803911c IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000298298
0x01dd21883c8a267b6f37e1a63b637024939560903fbb15480cfb4eb9dd226a10Burn20758922022-10-27 2:25:3642 days 9 hrs ago0x7235927459cfc05520b6a1467b4cd7ebf1b62217 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.00088636
0x36861ab363f7f08cd9858592655972bea4874721242aae850add63049ef93ad4Mint20757212022-10-27 1:50:3042 days 10 hrs ago0xd10c833f4305e1053a64bc738c550381f48104ca IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.00141636
0x5171cf42de0c074abc00ac3376293f573d3b544289a4d00c4b527964968581a3Mint20757082022-10-27 1:47:4242 days 10 hrs ago0xbfa2f68bf9ad60dc3cfb1cef04730eb7fa251424 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.002117214
0xc0347b900a987be91eeccf2fc67daee0ede7d117f5f1944e83a3c42067ca3d12Unpause20316022022-10-20 18:34:0048 days 17 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283316
0xad11cae0477f507db956ddfbf793b2d4511a48fe74487a372f84009b8b464733Pause20315302022-10-20 18:18:3648 days 17 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283635
0x4dc695bff6facfd92d60ed446c302aa32e5e41e024337eb4e8e837ca710c8ad2Unpause19339342022-10-06 23:50:2462 days 12 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283316
0x237b73c4c16fa50860587239e8f66ec9a0c1e735d81a2c805b23249dcaa79de3Pause19336722022-10-06 22:57:3062 days 13 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283635
0xb8855fa4ff84d2954e29563c21a18ea7f86dd465bb763a356cb51fb1436192d8Unpause18639472022-09-27 3:10:3072 days 9 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283316
0x6b22ce253fd0b06cc86976ee9704339d528b396be39a0ede993955aa05dd9eb0Pause18639402022-09-27 3:09:0672 days 9 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283635
0x6a40fe8ab7c5d8885f53a707bfddc0794a9e1ef1403a13eaee506a99689ec7daUnpause18631902022-09-27 0:34:1272 days 11 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283316
0xbdb44607d3e33c16a91654c2051e1b11914d657b12d6ca126121d1d934332f4dPause18631832022-09-27 0:32:4872 days 11 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283635
0x94a3c899d6afea4b8fac348aaec898d248e571c50a0eb6395cf0fdced94295a9Unpause18631772022-09-27 0:31:3672 days 11 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283316
0x27bc3dfc207bfc1bc16298757cdcaf442c17731755bf0288ed3d911c6fcfe99bPause18631422022-09-27 0:24:3672 days 11 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000254771
0x0935c1037bb6cf17f2d124e323b449cebae28fedeabb19e27e3884ab4b4552c0Pause18631412022-09-27 0:24:2472 days 11 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283635
0x35bba1d88cc81f77ac31c1f11155b3fe40c2c70c25305c40bb8251d48f298f09Unpause17804282022-09-15 7:34:1884 days 4 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283316
0x5f01c98352cf1b2f2a15435f63c3cf12a00b4ede68f892afce115e0c740a38a0Pause17789252022-09-15 2:25:4284 days 9 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283635
0xf4d019559941a3b9baa98f3c71961146509264c5bd3c28731af9572f4e7a1001Unpause17789122022-09-15 2:23:0684 days 9 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283316
0xded5fcb0c1889745f13eb985c3bb6d339154e3c463f321e3cde03da961f0a4dcPause17789012022-09-15 2:20:5484 days 9 hrs ago0x1a0aec0fc48f1b5cc538be74a90e340b278189e4 IN  0x3b53d2c7b44d40be05fa5e2309ffeb6eb2492d880 CLV0.000283635
[ Download CSV Export 
Parent Txn Hash Block From To Value
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
PeggedTokenBridgeV2

Compiler Version
v0.8.9+commit.e5eed63a

Optimization Enabled:
Yes with 800 runs

Other Settings:
default evmVersion, GNU GPLv3 license

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 120 : GovernedOwnerProxy.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity ^0.8.9;

import "./proxies/CommonOwnerProxy.sol";
import "./proxies/BridgeOwnerProxy.sol";
import "./proxies/MessageOwnerProxy.sol";
import "./proxies/SgnOwnerProxy.sol";
import "./proxies/UpgradeableOwnerProxy.sol";

contract GovernedOwnerProxy is
    CommonOwnerProxy,
    BridgeOwnerProxy,
    MessageOwnerProxy,
    SgnOwnerProxy,
    UpgradeableOwnerProxy
{
    constructor(address _initializer) OwnerProxyBase(_initializer) {}
}

File 2 of 120 : CommonOwnerProxy.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity ^0.8.9;

import "./OwnerProxyBase.sol";
import "../interfaces/ICommonOwner.sol";
import {SimpleGovernance as sg} from "../SimpleGovernance.sol";
import {OwnerDataTypes as dt} from "./OwnerDataTypes.sol";

abstract contract CommonOwnerProxy is OwnerProxyBase {
    event TransferOwnershipProposalCreated(uint256 proposalId, address target, uint256 newOwner);
    event UpdatePauserProposalCreated(uint256 proposalId, address target, dt.Action action, address account);

    function proposeTransferOwnership(address _target, uint256 _newOwner) external {
        bytes memory data = abi.encodeWithSelector(ICommonOwner.transferOwnership.selector, _newOwner);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit TransferOwnershipProposalCreated(proposalId, _target, _newOwner);
    }

    function proposeUpdatePauser(
        address _target,
        dt.Action _action,
        address _account
    ) external {
        bytes4 selector;
        if (_action == dt.Action.Add) {
            selector = ICommonOwner.addPauser.selector;
        } else if (_action == dt.Action.Remove) {
            selector = ICommonOwner.removePauser.selector;
        } else {
            revert("invalid action");
        }
        bytes memory data = abi.encodeWithSelector(selector, _account);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalFastPass);
        emit UpdatePauserProposalCreated(proposalId, _target, _action, _account);
    }
}

File 3 of 120 : BridgeOwnerProxy.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity ^0.8.9;

import "./OwnerProxyBase.sol";
import "../interfaces/IBridgeOwner.sol";
import {SimpleGovernance as sg} from "../SimpleGovernance.sol";
import {OwnerDataTypes as dt} from "./OwnerDataTypes.sol";

abstract contract BridgeOwnerProxy is OwnerProxyBase {
    // for bridges
    event ResetSignersProposalCreated(uint256 proposalId, address target, address[] signers, uint256[] powers);
    event NotifyResetSignersProposalCreated(uint256 proposalId, address target);
    event IncreaseNoticePeriodProposalCreated(uint256 proposalId, address target, uint256 period);
    event SetNativeWrapProposalCreated(uint256 proposalId, address target, address token);
    event UpdateSupplyProposalCreated(
        uint256 proposalId,
        address target,
        dt.Action action,
        address token,
        uint256 supply
    );
    event UpdateGovernorProposalCreated(uint256 proposalId, address target, dt.Action action, address account);

    // for bridge tokens
    event UpdateBridgeProposalCreated(uint256 proposalId, address target, address bridgeAddr);
    event UpdateBridgeSupplyCapProposalCreated(uint256 proposalId, address target, address bridge, uint256 cap);
    event SetBridgeTokenSwapCapProposalCreated(uint256 proposalId, address target, address bridgeToken, uint256 cap);

    function proposeResetSigners(
        address _target,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external {
        bytes memory data = abi.encodeWithSelector(IBridgeOwner.resetSigners.selector, _signers, _powers);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit ResetSignersProposalCreated(proposalId, _target, _signers, _powers);
    }

    function proposeNotifyResetSigners(address _target) external {
        bytes memory data = abi.encodeWithSelector(IBridgeOwner.notifyResetSigners.selector);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalFastPass);
        emit NotifyResetSignersProposalCreated(proposalId, _target);
    }

    function proposeIncreaseNoticePeriod(address _target, uint256 _period) external {
        bytes memory data = abi.encodeWithSelector(IBridgeOwner.increaseNoticePeriod.selector, _period);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit IncreaseNoticePeriodProposalCreated(proposalId, _target, _period);
    }

    function proposeSetNativeWrap(address _target, address _token) external {
        bytes memory data = abi.encodeWithSelector(IBridgeOwner.setWrap.selector, _token);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit SetNativeWrapProposalCreated(proposalId, _target, _token);
    }

    function proposeUpdateSupply(
        address _target,
        dt.Action _action,
        address _token,
        uint256 _supply
    ) external {
        bytes4 selector;
        if (_action == dt.Action.Set) {
            selector = IBridgeOwner.setSupply.selector;
        } else if (_action == dt.Action.Add) {
            selector = IBridgeOwner.increaseSupply.selector;
        } else if (_action == dt.Action.Remove) {
            selector = IBridgeOwner.decreaseSupply.selector;
        } else {
            revert("invalid action");
        }
        bytes memory data = abi.encodeWithSelector(selector, _token, _supply);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalFastPass);
        emit UpdateSupplyProposalCreated(proposalId, _target, _action, _token, _supply);
    }

    function proposeUpdateGovernor(
        address _target,
        dt.Action _action,
        address _account
    ) external {
        bytes4 selector;
        if (_action == dt.Action.Add) {
            selector = IBridgeOwner.addGovernor.selector;
        } else if (_action == dt.Action.Remove) {
            selector = IBridgeOwner.removeGovernor.selector;
        } else {
            revert("invalid action");
        }
        bytes memory data = abi.encodeWithSelector(selector, _account);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalFastPass);
        emit UpdateGovernorProposalCreated(proposalId, _target, _action, _account);
    }

    function proposeUpdateBridgeSupplyCap(
        address _target,
        address _bridge,
        uint256 _cap
    ) external {
        bytes memory data = abi.encodeWithSelector(IBridgeOwner.updateBridgeSupplyCap.selector, _bridge, _cap);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit UpdateBridgeSupplyCapProposalCreated(proposalId, _target, _bridge, _cap);
    }

    function proposeSetBridgeTokenSwapCap(
        address _target,
        address _bridgeToken,
        uint256 _swapCap
    ) external {
        bytes memory data = abi.encodeWithSelector(IBridgeOwner.setBridgeTokenSwapCap.selector, _bridgeToken, _swapCap);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit SetBridgeTokenSwapCapProposalCreated(proposalId, _target, _bridgeToken, _swapCap);
    }
}

File 4 of 120 : MessageOwnerProxy.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity ^0.8.9;

import "./OwnerProxyBase.sol";
import "../interfaces/IMessageOwner.sol";
import {SimpleGovernance as sg} from "../SimpleGovernance.sol";
import {OwnerDataTypes as dt} from "./OwnerDataTypes.sol";

abstract contract MessageOwnerProxy is OwnerProxyBase {
    event SetMsgFeeProposalCreated(uint256 proposalId, address target, dt.MsgFeeType feeType, uint256 fee);
    event SetBridgeAddressProposalCreated(
        uint256 proposalId,
        address target,
        dt.BridgeType bridgeType,
        address bridgeAddr
    );
    event SetPreExecuteMessageGasUsageProposalCreated(uint256 proposalId, address target, uint256 usage);

    function proposeSetMsgFee(
        address _target,
        dt.MsgFeeType _feeType,
        uint256 _fee
    ) external {
        bytes4 selector;
        if (_feeType == dt.MsgFeeType.PerByte) {
            selector = IMessageOwner.setFeePerByte.selector;
        } else if (_feeType == dt.MsgFeeType.Base) {
            selector = IMessageOwner.setFeeBase.selector;
        } else {
            revert("invalid fee type");
        }
        bytes memory data = abi.encodeWithSelector(selector, _fee);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalFastPass);
        emit SetMsgFeeProposalCreated(proposalId, _target, _feeType, _fee);
    }

    function proposeSetBridgeAddress(
        address _target,
        dt.BridgeType _bridgeType,
        address _bridgeAddr
    ) external {
        bytes4 selector;
        if (_bridgeType == dt.BridgeType.Liquidity) {
            selector = IMessageOwner.setLiquidityBridge.selector;
        } else if (_bridgeType == dt.BridgeType.PegBridge) {
            selector = IMessageOwner.setPegBridge.selector;
        } else if (_bridgeType == dt.BridgeType.PegVault) {
            selector = IMessageOwner.setPegVault.selector;
        } else if (_bridgeType == dt.BridgeType.PegBridgeV2) {
            selector = IMessageOwner.setPegBridgeV2.selector;
        } else if (_bridgeType == dt.BridgeType.PegVaultV2) {
            selector = IMessageOwner.setPegVaultV2.selector;
        } else {
            revert("invalid bridge type");
        }
        bytes memory data = abi.encodeWithSelector(selector, _bridgeAddr);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit SetBridgeAddressProposalCreated(proposalId, _target, _bridgeType, _bridgeAddr);
    }

    function proposeSetPreExecuteMessageGasUsage(address _target, uint256 _usage) external {
        bytes memory data = abi.encodeWithSelector(IMessageOwner.setPreExecuteMessageGasUsage.selector, _usage);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit SetPreExecuteMessageGasUsageProposalCreated(proposalId, _target, _usage);
    }
}

File 5 of 120 : SgnOwnerProxy.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity ^0.8.9;

import "./OwnerProxyBase.sol";
import "../interfaces/ISgnOwner.sol";
import {SimpleGovernance as sg} from "../SimpleGovernance.sol";
import {OwnerDataTypes as dt} from "./OwnerDataTypes.sol";

abstract contract SgnOwnerProxy is OwnerProxyBase {
    event SetWhitelistEnableProposalCreated(uint256 proposalId, address target, bool enabled);
    event UpdateWhitelistedProposalCreated(uint256 proposalId, address target, dt.Action action, address account);
    event SetGovContractProposalCreated(uint256 proposalId, address target, address addr);
    event SetRewardContractProposalCreated(uint256 proposalId, address target, address addr);
    event SetMaxSlashFactorProposalCreated(uint256 proposalId, address target, uint256 maxSlashFactor);
    event DrainTokenProposalCreated(uint256 proposalId, address target, address token, uint256 amount);

    function proposeSetWhitelistEnable(address _target, bool _enable) external {
        bytes memory data = abi.encodeWithSelector(ISgnOwner.setWhitelistEnabled.selector, _enable);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit SetWhitelistEnableProposalCreated(proposalId, _target, _enable);
    }

    function proposeUpdateWhitelisted(
        address _target,
        dt.Action _action,
        address _account
    ) external {
        bytes4 selector;
        if (_action == dt.Action.Add) {
            selector = ISgnOwner.addWhitelisted.selector;
        } else if (_action == dt.Action.Remove) {
            selector = ISgnOwner.removeWhitelisted.selector;
        } else {
            revert("invalid action");
        }
        bytes memory data = abi.encodeWithSelector(selector, _account);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalFastPass);
        emit UpdateWhitelistedProposalCreated(proposalId, _target, _action, _account);
    }

    function proposeSetGovContract(address _target, address _addr) external {
        bytes memory data = abi.encodeWithSelector(ISgnOwner.setGovContract.selector, _addr);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit SetGovContractProposalCreated(proposalId, _target, _addr);
    }

    function proposeSetRewardContract(address _target, address _addr) external {
        bytes memory data = abi.encodeWithSelector(ISgnOwner.setRewardContract.selector, _addr);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit SetRewardContractProposalCreated(proposalId, _target, _addr);
    }

    function proposeSetMaxSlashFactor(address _target, uint256 _maxSlashFactor) external {
        bytes memory data = abi.encodeWithSelector(ISgnOwner.setMaxSlashFactor.selector, _maxSlashFactor);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit SetMaxSlashFactorProposalCreated(proposalId, _target, _maxSlashFactor);
    }

    function proposeDrainToken(
        address _target,
        address _token,
        uint256 _amount
    ) external {
        bytes memory data;
        if (_token == address(0)) {
            data = abi.encodeWithSelector(bytes4(keccak256(bytes("drainToken(uint256"))), _amount);
        } else {
            data = abi.encodeWithSelector(bytes4(keccak256(bytes("drainToken(address,uint256"))), _token, _amount);
        }
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit DrainTokenProposalCreated(proposalId, _target, _token, _amount);
    }
}

File 6 of 120 : UpgradeableOwnerProxy.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity ^0.8.9;

import "./OwnerProxyBase.sol";
import "../interfaces/IUpgradeableOwner.sol";
import {SimpleGovernance as sg} from "../SimpleGovernance.sol";
import {OwnerDataTypes as dt} from "./OwnerDataTypes.sol";

abstract contract UpgradeableOwnerProxy is OwnerProxyBase {
    event ChangeProxyAdminProposalCreated(uint256 proposalId, address target, address proxy, address newAdmin);
    event UpgradeProposalCreated(uint256 proposalId, address target, address proxy, address implementation);
    event UpgradeAndCallProposalCreated(
        uint256 proposalId,
        address target,
        address proxy,
        address implementation,
        bytes data
    );
    event UpgradeToProposalCreated(uint256 proposalId, address target, address implementation);
    event UpgradeToAndCallProposalCreated(uint256 proposalId, address target, address implementation, bytes data);

    function proposeChangeProxyAdmin(
        address _target,
        address _proxy,
        address _newAdmin
    ) external {
        bytes memory data = abi.encodeWithSelector(IUpgradeableOwner.changeProxyAdmin.selector, _proxy, _newAdmin);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit ChangeProxyAdminProposalCreated(proposalId, _target, _proxy, _newAdmin);
    }

    function proposeUpgrade(
        address _target,
        address _proxy,
        address _implementation
    ) external {
        bytes memory data = abi.encodeWithSelector(IUpgradeableOwner.upgrade.selector, _proxy, _implementation);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit UpgradeProposalCreated(proposalId, _target, _proxy, _implementation);
    }

    function proposeUpgradeAndCall(
        address _target,
        address _proxy,
        address _implementation,
        bytes calldata _data
    ) external {
        bytes memory data = abi.encodeWithSelector(
            IUpgradeableOwner.upgradeAndCall.selector,
            _proxy,
            _implementation,
            _data
        );
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit UpgradeAndCallProposalCreated(proposalId, _target, _proxy, _implementation, _data);
    }

    function proposeUpgradeTo(address _target, address _implementation) external {
        bytes memory data = abi.encodeWithSelector(IUpgradeableOwner.upgradeTo.selector, _implementation);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit UpgradeToProposalCreated(proposalId, _target, _implementation);
    }

    function proposeUpgradeToAndCall(
        address _target,
        address _implementation,
        bytes calldata _data
    ) external {
        bytes memory data = abi.encodeWithSelector(IUpgradeableOwner.upgradeToAndCall.selector, _implementation, _data);
        uint256 proposalId = gov.createProposal(msg.sender, _target, data, sg.ProposalType.ExternalDefault);
        emit UpgradeToAndCallProposalCreated(proposalId, _target, _implementation, _data);
    }
}

File 7 of 120 : OwnerProxyBase.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

import "../SimpleGovernance.sol";

abstract contract OwnerProxyBase {
    SimpleGovernance public gov;
    address private initializer;

    constructor(address _initializer) {
        initializer = _initializer;
    }

    function initGov(SimpleGovernance _gov) public {
        require(msg.sender == initializer, "only initializer can init");
        require(address(gov) == address(0), "gov addr already set");
        gov = _gov;
    }
}

File 8 of 120 : ICommonOwner.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface ICommonOwner {
    function transferOwnership(address _newOwner) external;

    function addPauser(address _account) external;

    function removePauser(address _account) external;
}

File 9 of 120 : SimpleGovernance.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity ^0.8.9;

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

// mainly used for governed-owner to do infrequent sgn/cbridge owner operations,
// relatively prefer easy-to-use over gas-efficiency
contract SimpleGovernance {
    uint256 public constant THRESHOLD_DECIMAL = 100;
    uint256 public constant MIN_ACTIVE_PERIOD = 3600; // one hour
    uint256 public constant MAX_ACTIVE_PERIOD = 2419200; // four weeks

    using SafeERC20 for IERC20;

    enum ParamName {
        ActivePeriod,
        QuorumThreshold, // default threshold for votes to pass
        FastPassThreshold // lower threshold for less critical operations
    }

    enum ProposalType {
        ExternalDefault,
        ExternalFastPass,
        InternalParamChange,
        InternalVoterUpdate,
        InternalProxyUpdate,
        InternalTransferToken
    }

    mapping(ParamName => uint256) public params;

    struct Proposal {
        bytes32 dataHash; // hash(proposalType, targetAddress, calldata)
        uint256 deadline;
        mapping(address => bool) votes;
    }

    mapping(uint256 => Proposal) public proposals;
    uint256 public nextProposalId;

    address[] public voters;
    mapping(address => uint256) public voterPowers; // voter addr -> voting power

    // NOTE: proxies must be audited open-source non-upgradable contracts with following requirements:
    // 1. Truthfully pass along tx sender who called the proxy function as the governance proposer.
    // 2. Do not allow arbitrary fastpass proposal with calldata constructed by the proxy callers.
    // See ./proxies/CommonOwnerProxy.sol for example.
    mapping(address => bool) public proposerProxies;

    event Initiated(
        address[] voters,
        uint256[] powers,
        address[] proxies,
        uint256 activePeriod,
        uint256 quorumThreshold,
        uint256 fastPassThreshold
    );

    event ProposalCreated(
        uint256 proposalId,
        ProposalType proposalType,
        address target,
        bytes data,
        uint256 deadline,
        address proposer
    );
    event ProposalVoted(uint256 proposalId, address voter, bool vote);
    event ProposalExecuted(uint256 proposalId);

    event ParamChangeProposalCreated(uint256 proposalId, ParamName name, uint256 value);
    event VoterUpdateProposalCreated(uint256 proposalId, address[] voters, uint256[] powers);
    event ProxyUpdateProposalCreated(uint256 proposalId, address[] addrs, bool[] ops);
    event TransferTokenProposalCreated(uint256 proposalId, address receiver, address token, uint256 amount);

    constructor(
        address[] memory _voters,
        uint256[] memory _powers,
        address[] memory _proxies,
        uint256 _activePeriod,
        uint256 _quorumThreshold,
        uint256 _fastPassThreshold
    ) {
        require(_voters.length > 0 && _voters.length == _powers.length, "invalid init voters");
        require(_activePeriod <= MAX_ACTIVE_PERIOD && _activePeriod >= MIN_ACTIVE_PERIOD, "invalid active period");
        require(
            _quorumThreshold < THRESHOLD_DECIMAL && _fastPassThreshold <= _quorumThreshold,
            "invalid init thresholds"
        );
        for (uint256 i = 0; i < _voters.length; i++) {
            _setVoter(_voters[i], _powers[i]);
        }
        for (uint256 i = 0; i < _proxies.length; i++) {
            proposerProxies[_proxies[i]] = true;
        }
        params[ParamName.ActivePeriod] = _activePeriod;
        params[ParamName.QuorumThreshold] = _quorumThreshold;
        params[ParamName.FastPassThreshold] = _fastPassThreshold;
        emit Initiated(_voters, _powers, _proxies, _activePeriod, _quorumThreshold, _fastPassThreshold);
    }

    /*********************************
     * External and Public Functions *
     *********************************/

    function createProposal(address _target, bytes memory _data) external returns (uint256) {
        return _createProposal(msg.sender, _target, _data, ProposalType.ExternalDefault);
    }

    // create proposal through proxy
    function createProposal(
        address _proposer,
        address _target,
        bytes memory _data,
        ProposalType _type
    ) external returns (uint256) {
        require(proposerProxies[msg.sender], "sender is not a valid proxy");
        require(_type == ProposalType.ExternalDefault || _type == ProposalType.ExternalFastPass, "invalid type");
        return _createProposal(_proposer, _target, _data, _type);
    }

    function createParamChangeProposal(ParamName _name, uint256 _value) external returns (uint256) {
        bytes memory data = abi.encode(_name, _value);
        uint256 proposalId = _createProposal(msg.sender, address(0), data, ProposalType.InternalParamChange);
        emit ParamChangeProposalCreated(proposalId, _name, _value);
        return proposalId;
    }

    function createVoterUpdateProposal(address[] calldata _voters, uint256[] calldata _powers)
        external
        returns (uint256)
    {
        require(_voters.length == _powers.length, "voters and powers length not match");
        bytes memory data = abi.encode(_voters, _powers);
        uint256 proposalId = _createProposal(msg.sender, address(0), data, ProposalType.InternalVoterUpdate);
        emit VoterUpdateProposalCreated(proposalId, _voters, _powers);
        return proposalId;
    }

    function createProxyUpdateProposal(address[] calldata _addrs, bool[] calldata _ops) external returns (uint256) {
        require(_addrs.length == _ops.length, "_addrs and _ops length not match");
        bytes memory data = abi.encode(_addrs, _ops);
        uint256 proposalId = _createProposal(msg.sender, address(0), data, ProposalType.InternalProxyUpdate);
        emit ProxyUpdateProposalCreated(proposalId, _addrs, _ops);
        return proposalId;
    }

    function createTransferTokenProposal(
        address _receiver,
        address _token,
        uint256 _amount
    ) external returns (uint256) {
        bytes memory data = abi.encode(_receiver, _token, _amount);
        uint256 proposalId = _createProposal(msg.sender, address(0), data, ProposalType.InternalTransferToken);
        emit TransferTokenProposalCreated(proposalId, _receiver, _token, _amount);
        return proposalId;
    }

    function voteProposal(uint256 _proposalId, bool _vote) external {
        require(voterPowers[msg.sender] > 0, "invalid voter");
        Proposal storage p = proposals[_proposalId];
        require(block.timestamp < p.deadline, "deadline passed");
        p.votes[msg.sender] = _vote;
        emit ProposalVoted(_proposalId, msg.sender, _vote);
    }

    function executeProposal(
        uint256 _proposalId,
        ProposalType _type,
        address _target,
        bytes calldata _data
    ) external {
        require(voterPowers[msg.sender] > 0, "only voter can execute a proposal");
        Proposal storage p = proposals[_proposalId];
        require(block.timestamp < p.deadline, "deadline passed");
        require(keccak256(abi.encodePacked(_type, _target, _data)) == p.dataHash, "data hash not match");
        p.deadline = 0;

        p.votes[msg.sender] = true;
        (, , bool pass) = countVotes(_proposalId, _type);
        require(pass, "not enough votes");

        if (_type == ProposalType.ExternalDefault || _type == ProposalType.ExternalFastPass) {
            (bool success, bytes memory res) = _target.call(_data);
            require(success, _getRevertMsg(res));
        } else if (_type == ProposalType.InternalParamChange) {
            (ParamName name, uint256 value) = abi.decode((_data), (ParamName, uint256));
            params[name] = value;
            if (name == ParamName.ActivePeriod) {
                require(value <= MAX_ACTIVE_PERIOD && value >= MIN_ACTIVE_PERIOD, "invalid active period");
            } else if (name == ParamName.QuorumThreshold || name == ParamName.FastPassThreshold) {
                require(
                    params[ParamName.QuorumThreshold] >= params[ParamName.FastPassThreshold] &&
                        value < THRESHOLD_DECIMAL &&
                        value > 0,
                    "invalid threshold"
                );
            }
        } else if (_type == ProposalType.InternalVoterUpdate) {
            (address[] memory addrs, uint256[] memory powers) = abi.decode((_data), (address[], uint256[]));
            for (uint256 i = 0; i < addrs.length; i++) {
                if (powers[i] > 0) {
                    _setVoter(addrs[i], powers[i]);
                } else {
                    _removeVoter(addrs[i]);
                }
            }
        } else if (_type == ProposalType.InternalProxyUpdate) {
            (address[] memory addrs, bool[] memory ops) = abi.decode((_data), (address[], bool[]));
            for (uint256 i = 0; i < addrs.length; i++) {
                if (ops[i]) {
                    proposerProxies[addrs[i]] = true;
                } else {
                    delete proposerProxies[addrs[i]];
                }
            }
        } else if (_type == ProposalType.InternalTransferToken) {
            (address receiver, address token, uint256 amount) = abi.decode((_data), (address, address, uint256));
            _transfer(receiver, token, amount);
        }
        emit ProposalExecuted(_proposalId);
    }

    receive() external payable {}

    /**************************
     *  Public View Functions *
     **************************/

    function getVoters() public view returns (address[] memory, uint256[] memory) {
        address[] memory addrs = new address[](voters.length);
        uint256[] memory powers = new uint256[](voters.length);
        for (uint32 i = 0; i < voters.length; i++) {
            addrs[i] = voters[i];
            powers[i] = voterPowers[voters[i]];
        }
        return (addrs, powers);
    }

    function getVote(uint256 _proposalId, address _voter) public view returns (bool) {
        return proposals[_proposalId].votes[_voter];
    }

    function countVotes(uint256 _proposalId, ProposalType _type)
        public
        view
        returns (
            uint256,
            uint256,
            bool
        )
    {
        uint256 yesVotes;
        uint256 totalPower;
        for (uint32 i = 0; i < voters.length; i++) {
            if (getVote(_proposalId, voters[i])) {
                yesVotes += voterPowers[voters[i]];
            }
            totalPower += voterPowers[voters[i]];
        }
        uint256 threshold;
        if (_type == ProposalType.ExternalFastPass) {
            threshold = params[ParamName.FastPassThreshold];
        } else {
            threshold = params[ParamName.QuorumThreshold];
        }
        bool pass = (yesVotes >= (totalPower * threshold) / THRESHOLD_DECIMAL);
        return (totalPower, yesVotes, pass);
    }

    /**********************************
     * Internal and Private Functions *
     **********************************/

    // create a proposal and vote yes
    function _createProposal(
        address _proposer,
        address _target,
        bytes memory _data,
        ProposalType _type
    ) private returns (uint256) {
        require(voterPowers[_proposer] > 0, "only voter can create a proposal");
        uint256 proposalId = nextProposalId;
        nextProposalId += 1;
        Proposal storage p = proposals[proposalId];
        p.dataHash = keccak256(abi.encodePacked(_type, _target, _data));
        p.deadline = block.timestamp + params[ParamName.ActivePeriod];
        p.votes[_proposer] = true;
        emit ProposalCreated(proposalId, _type, _target, _data, p.deadline, _proposer);
        return proposalId;
    }

    function _setVoter(address _voter, uint256 _power) private {
        require(_power > 0, "zero power");
        if (voterPowers[_voter] == 0) {
            // add new voter
            voters.push(_voter);
        }
        voterPowers[_voter] = _power;
    }

    function _removeVoter(address _voter) private {
        require(voterPowers[_voter] > 0, "not a voter");
        uint256 lastIndex = voters.length - 1;
        for (uint256 i = 0; i < voters.length; i++) {
            if (voters[i] == _voter) {
                if (i < lastIndex) {
                    voters[i] = voters[lastIndex];
                }
                voters.pop();
                voterPowers[_voter] = 0;
                return;
            }
        }
        revert("voter not found"); // this should never happen
    }

    function _transfer(
        address _receiver,
        address _token,
        uint256 _amount
    ) private {
        if (_token == address(0)) {
            (bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
            require(sent, "failed to send native token");
        } else {
            IERC20(_token).safeTransfer(_receiver, _amount);
        }
    }

    // https://ethereum.stackexchange.com/a/83577
    // https://github.com/Uniswap/v3-periphery/blob/v1.0.0/contracts/base/Multicall.sol
    function _getRevertMsg(bytes memory _returnData) private pure returns (string memory) {
        // If the _res length is less than 68, then the transaction failed silently (without a revert message)
        if (_returnData.length < 68) return "Transaction reverted silently";
        assembly {
            // Slice the sighash.
            _returnData := add(_returnData, 0x04)
        }
        return abi.decode(_returnData, (string)); // All that remains is the revert string
    }
}

File 10 of 120 : OwnerDataTypes.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

library OwnerDataTypes {
    enum Action {
        Set,
        Add,
        Remove
    }

    enum MsgFeeType {
        PerByte,
        Base
    }

    enum BridgeType {
        Liquidity,
        PegBridge,
        PegVault,
        PegBridgeV2,
        PegVaultV2
    }
}

File 11 of 120 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount
    ) external returns (bool);

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

File 12 of 120 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}

File 13 of 120 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @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, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * 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.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @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`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

File 14 of 120 : IBridgeOwner.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IBridgeOwner {
    // for bridges

    function resetSigners(address[] calldata _signers, uint256[] calldata _powers) external;

    function notifyResetSigners() external;

    function increaseNoticePeriod(uint256 _period) external;

    function setWrap(address _token) external;

    function setSupply(address _token, uint256 _supply) external;

    function increaseSupply(address _token, uint256 _delta) external;

    function decreaseSupply(address _token, uint256 _delta) external;

    function addGovernor(address _account) external;

    function removeGovernor(address _account) external;

    // for bridge tokens

    function updateBridge(address _bridge) external;

    function updateBridgeSupplyCap(address _bridge, uint256 _cap) external;

    function setBridgeTokenSwapCap(address _bridgeToken, uint256 _swapCap) external;
}

File 15 of 120 : IMessageOwner.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IMessageOwner {
    function setFeePerByte(uint256 _fee) external;

    function setFeeBase(uint256 _fee) external;

    function setLiquidityBridge(address _addr) external;

    function setPegBridge(address _addr) external;

    function setPegVault(address _addr) external;

    function setPegBridgeV2(address _addr) external;

    function setPegVaultV2(address _addr) external;

    function setPreExecuteMessageGasUsage(uint256 _usage) external;
}

File 16 of 120 : ISgnOwner.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface ISgnOwner {
    function setWhitelistEnabled(bool _whitelistEnabled) external;

    function addWhitelisted(address _account) external;

    function removeWhitelisted(address _account) external;

    function setGovContract(address _addr) external;

    function setRewardContract(address _addr) external;

    function setMaxSlashFactor(uint256 _maxSlashFactor) external;
}

File 17 of 120 : IUpgradeableOwner.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IUpgradeableOwner {
    function changeProxyAdmin(address _proxy, address _newAdmin) external;

    function upgrade(address _proxy, address _implementation) external;

    function upgradeAndCall(
        address _proxy,
        address _implementation,
        bytes calldata _data
    ) external;

    function upgradeTo(address _implementation) external;

    function upgradeToAndCall(address _implementation, bytes calldata _data) external;
}

File 18 of 120 : DummySwap.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

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

contract DummySwap {
    using SafeERC20 for IERC20;

    uint256 fakeSlippage; // 100% = 100 * 1e4
    uint256 hundredPercent = 100 * 1e4;

    constructor(uint256 _fakeSlippage) {
        fakeSlippage = _fakeSlippage;
    }

    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts) {
        require(deadline != 0 && deadline > block.timestamp, "deadline exceeded");
        require(path.length > 1, "path must have more than 1 token in it");
        IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);
        // fake simulate slippage
        uint256 amountAfterSlippage = (amountIn * (hundredPercent - fakeSlippage)) / hundredPercent;
        require(amountAfterSlippage > amountOutMin, "bad slippage");

        IERC20(path[path.length - 1]).safeTransfer(to, amountAfterSlippage);
        uint256[] memory ret = new uint256[](2);
        ret[0] = amountIn;
        ret[1] = amountAfterSlippage;
        return ret;
    }

    function setFakeSlippage(uint256 _fakeSlippage) public {
        fakeSlippage = _fakeSlippage;
    }
}

File 19 of 120 : StakingReward.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypes as dt} from "./DataTypes.sol";
import "../safeguard/Pauser.sol";
import "./Staking.sol";

/**
 * @title A contract to hold and distribute CELR staking rewards.
 */
contract StakingReward is Pauser {
    using SafeERC20 for IERC20;

    Staking public immutable staking;

    // recipient => CELR reward amount
    mapping(address => uint256) public claimedRewardAmounts;

    event StakingRewardClaimed(address indexed recipient, uint256 reward);
    event StakingRewardContributed(address indexed contributor, uint256 contribution);

    constructor(Staking _staking) {
        staking = _staking;
    }

    /**
     * @notice Claim reward
     * @dev Here we use cumulative reward to make claim process idempotent
     * @param _rewardRequest reward request bytes coded in protobuf
     * @param _sigs list of validator signatures
     */
    function claimReward(bytes calldata _rewardRequest, bytes[] calldata _sigs) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "StakingReward"));
        staking.verifySignatures(abi.encodePacked(domain, _rewardRequest), _sigs);
        PbStaking.StakingReward memory reward = PbStaking.decStakingReward(_rewardRequest);

        uint256 cumulativeRewardAmount = reward.cumulativeRewardAmount;
        uint256 newReward = cumulativeRewardAmount - claimedRewardAmounts[reward.recipient];
        require(newReward > 0, "No new reward");
        claimedRewardAmounts[reward.recipient] = cumulativeRewardAmount;
        staking.CELER_TOKEN().safeTransfer(reward.recipient, newReward);
        emit StakingRewardClaimed(reward.recipient, newReward);
    }

    /**
     * @notice Contribute CELR tokens to the reward pool
     * @param _amount the amount of CELR token to contribute
     */
    function contributeToRewardPool(uint256 _amount) external whenNotPaused {
        address contributor = msg.sender;
        IERC20(staking.CELER_TOKEN()).safeTransferFrom(contributor, address(this), _amount);

        emit StakingRewardContributed(contributor, _amount);
    }

    /**
     * @notice Owner drains CELR tokens when the contract is paused
     * @dev emergency use only
     * @param _amount drained CELR token amount
     */
    function drainToken(uint256 _amount) external whenPaused onlyOwner {
        IERC20(staking.CELER_TOKEN()).safeTransfer(msg.sender, _amount);
    }
}

File 20 of 120 : DataTypes.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

library DataTypes {
    uint256 constant CELR_DECIMAL = 1e18;
    uint256 constant MAX_INT = 2**256 - 1;
    uint256 constant COMMISSION_RATE_BASE = 10000; // 1 commissionRate means 0.01%
    uint256 constant MAX_UNDELEGATION_ENTRIES = 10;
    uint256 constant SLASH_FACTOR_DECIMAL = 1e6;

    enum ValidatorStatus {
        Null,
        Unbonded,
        Unbonding,
        Bonded
    }

    enum ParamName {
        ProposalDeposit,
        VotingPeriod,
        UnbondingPeriod,
        MaxBondedValidators,
        MinValidatorTokens,
        MinSelfDelegation,
        AdvanceNoticePeriod,
        ValidatorBondInterval,
        MaxSlashFactor
    }

    struct Undelegation {
        uint256 shares;
        uint256 creationBlock;
    }

    struct Undelegations {
        mapping(uint256 => Undelegation) queue;
        uint32 head;
        uint32 tail;
    }

    struct Delegator {
        uint256 shares;
        Undelegations undelegations;
    }

    struct Validator {
        ValidatorStatus status;
        address signer;
        uint256 tokens; // sum of all tokens delegated to this validator
        uint256 shares; // sum of all delegation shares
        uint256 undelegationTokens; // tokens being undelegated
        uint256 undelegationShares; // shares of tokens being undelegated
        mapping(address => Delegator) delegators;
        uint256 minSelfDelegation;
        uint64 bondBlock; // cannot become bonded before this block
        uint64 unbondBlock; // cannot become unbonded before this block
        uint64 commissionRate; // equal to real commission rate * COMMISSION_RATE_BASE
    }

    // used for external view output
    struct ValidatorTokens {
        address valAddr;
        uint256 tokens;
    }

    // used for external view output
    struct ValidatorInfo {
        address valAddr;
        ValidatorStatus status;
        address signer;
        uint256 tokens;
        uint256 shares;
        uint256 minSelfDelegation;
        uint64 commissionRate;
    }

    // used for external view output
    struct DelegatorInfo {
        address valAddr;
        uint256 tokens;
        uint256 shares;
        Undelegation[] undelegations;
        uint256 undelegationTokens;
        uint256 withdrawableUndelegationTokens;
    }
}

File 21 of 120 : Pauser.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/security/Pausable.sol";
import "./Ownable.sol";

abstract contract Pauser is Ownable, Pausable {
    mapping(address => bool) public pausers;

    event PauserAdded(address account);
    event PauserRemoved(address account);

    constructor() {
        _addPauser(msg.sender);
    }

    modifier onlyPauser() {
        require(isPauser(msg.sender), "Caller is not pauser");
        _;
    }

    function pause() public onlyPauser {
        _pause();
    }

    function unpause() public onlyPauser {
        _unpause();
    }

    function isPauser(address account) public view returns (bool) {
        return pausers[account];
    }

    function addPauser(address account) public onlyOwner {
        _addPauser(account);
    }

    function removePauser(address account) public onlyOwner {
        _removePauser(account);
    }

    function renouncePauser() public {
        _removePauser(msg.sender);
    }

    function _addPauser(address account) private {
        require(!isPauser(account), "Account is already pauser");
        pausers[account] = true;
        emit PauserAdded(account);
    }

    function _removePauser(address account) private {
        require(isPauser(account), "Account is not pauser");
        pausers[account] = false;
        emit PauserRemoved(account);
    }
}

File 22 of 120 : Staking.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {DataTypes as dt} from "./DataTypes.sol";
import "../interfaces/ISigsVerifier.sol";
import "../libraries/PbStaking.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/Whitelist.sol";

/**
 * @title A Staking contract shared by all external sidechains and apps
 */
contract Staking is ISigsVerifier, Pauser, Whitelist {
    using SafeERC20 for IERC20;
    using ECDSA for bytes32;

    IERC20 public immutable CELER_TOKEN;

    uint256 public bondedTokens;
    uint256 public nextBondBlock;
    address[] public valAddrs;
    address[] public bondedValAddrs;
    mapping(address => dt.Validator) public validators; // key is valAddr
    mapping(address => address) public signerVals; // signerAddr -> valAddr
    mapping(uint256 => bool) public slashNonces;

    mapping(dt.ParamName => uint256) public params;
    address public govContract;
    address public rewardContract;
    uint256 public forfeiture;

    /* Events */
    event ValidatorNotice(address indexed valAddr, string key, bytes data, address from);
    event ValidatorStatusUpdate(address indexed valAddr, dt.ValidatorStatus indexed status);
    event DelegationUpdate(
        address indexed valAddr,
        address indexed delAddr,
        uint256 valTokens,
        uint256 delShares,
        int256 tokenDiff
    );
    event Undelegated(address indexed valAddr, address indexed delAddr, uint256 amount);
    event Slash(address indexed valAddr, uint64 nonce, uint256 slashAmt);
    event SlashAmtCollected(address indexed recipient, uint256 amount);

    /**
     * @notice Staking constructor
     * @param _celerTokenAddress address of Celer Token Contract
     * @param _proposalDeposit required deposit amount for a governance proposal
     * @param _votingPeriod voting timeout for a governance proposal
     * @param _unbondingPeriod the locking time for funds locked before withdrawn
     * @param _maxBondedValidators the maximum number of bonded validators
     * @param _minValidatorTokens the global minimum token amount requirement for bonded validator
     * @param _minSelfDelegation minimal amount of self-delegated tokens
     * @param _advanceNoticePeriod the wait time after the announcement and prior to the effective date of an update
     * @param _validatorBondInterval min interval between bondValidator
     * @param _maxSlashFactor maximal slashing factor (1e6 = 100%)
     */
    constructor(
        address _celerTokenAddress,
        uint256 _proposalDeposit,
        uint256 _votingPeriod,
        uint256 _unbondingPeriod,
        uint256 _maxBondedValidators,
        uint256 _minValidatorTokens,
        uint256 _minSelfDelegation,
        uint256 _advanceNoticePeriod,
        uint256 _validatorBondInterval,
        uint256 _maxSlashFactor
    ) {
        CELER_TOKEN = IERC20(_celerTokenAddress);

        params[dt.ParamName.ProposalDeposit] = _proposalDeposit;
        params[dt.ParamName.VotingPeriod] = _votingPeriod;
        params[dt.ParamName.UnbondingPeriod] = _unbondingPeriod;
        params[dt.ParamName.MaxBondedValidators] = _maxBondedValidators;
        params[dt.ParamName.MinValidatorTokens] = _minValidatorTokens;
        params[dt.ParamName.MinSelfDelegation] = _minSelfDelegation;
        params[dt.ParamName.AdvanceNoticePeriod] = _advanceNoticePeriod;
        params[dt.ParamName.ValidatorBondInterval] = _validatorBondInterval;
        params[dt.ParamName.MaxSlashFactor] = _maxSlashFactor;
    }

    receive() external payable {}

    /*********************************
     * External and Public Functions *
     *********************************/

    /**
     * @notice Initialize a validator candidate
     * @param _signer signer address
     * @param _minSelfDelegation minimal amount of tokens staked by the validator itself
     * @param _commissionRate the self-declaimed commission rate
     */
    function initializeValidator(
        address _signer,
        uint256 _minSelfDelegation,
        uint64 _commissionRate
    ) external whenNotPaused onlyWhitelisted {
        address valAddr = msg.sender;
        dt.Validator storage validator = validators[valAddr];
        require(validator.status == dt.ValidatorStatus.Null, "Validator is initialized");
        require(validators[_signer].status == dt.ValidatorStatus.Null, "Signer is other validator");
        require(signerVals[valAddr] == address(0), "Validator is other signer");
        require(signerVals[_signer] == address(0), "Signer already used");
        require(_commissionRate <= dt.COMMISSION_RATE_BASE, "Invalid commission rate");
        require(_minSelfDelegation >= params[dt.ParamName.MinSelfDelegation], "Insufficient min self delegation");
        validator.signer = _signer;
        validator.status = dt.ValidatorStatus.Unbonded;
        validator.minSelfDelegation = _minSelfDelegation;
        validator.commissionRate = _commissionRate;
        valAddrs.push(valAddr);
        signerVals[_signer] = valAddr;

        delegate(valAddr, _minSelfDelegation);
        emit ValidatorNotice(valAddr, "init", abi.encode(_signer, _minSelfDelegation, _commissionRate), address(0));
    }

    /**
     * @notice Update validator signer address
     * @param _signer signer address
     */
    function updateValidatorSigner(address _signer) external {
        address valAddr = msg.sender;
        dt.Validator storage validator = validators[valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator not initialized");
        require(signerVals[_signer] == address(0), "Signer already used");
        if (_signer != valAddr) {
            require(validators[_signer].status == dt.ValidatorStatus.Null, "Signer is other validator");
        }

        delete signerVals[validator.signer];
        validator.signer = _signer;
        signerVals[_signer] = valAddr;

        emit ValidatorNotice(valAddr, "signer", abi.encode(_signer), address(0));
    }

    /**
     * @notice Candidate claims to become a bonded validator
     * @dev caller can be either validator owner or signer
     */
    function bondValidator() external {
        address valAddr = msg.sender;
        if (signerVals[msg.sender] != address(0)) {
            valAddr = signerVals[msg.sender];
        }
        dt.Validator storage validator = validators[valAddr];
        require(
            validator.status == dt.ValidatorStatus.Unbonded || validator.status == dt.ValidatorStatus.Unbonding,
            "Invalid validator status"
        );
        require(block.number >= validator.bondBlock, "Bond block not reached");
        require(block.number >= nextBondBlock, "Too frequent validator bond");
        nextBondBlock = block.number + params[dt.ParamName.ValidatorBondInterval];
        require(hasMinRequiredTokens(valAddr, true), "Not have min tokens");

        uint256 maxBondedValidators = params[dt.ParamName.MaxBondedValidators];
        // if the number of validators has not reached the max_validator_num,
        // add validator directly
        if (bondedValAddrs.length < maxBondedValidators) {
            _bondValidator(valAddr);
            _decentralizationCheck(validator.tokens);
            return;
        }
        // if the number of validators has already reached the max_validator_num,
        // add validator only if its tokens is more than the current least bonded validator tokens
        uint256 minTokens = dt.MAX_INT;
        uint256 minTokensIndex;
        for (uint256 i = 0; i < maxBondedValidators; i++) {
            if (validators[bondedValAddrs[i]].tokens < minTokens) {
                minTokensIndex = i;
                minTokens = validators[bondedValAddrs[i]].tokens;
                if (minTokens == 0) {
                    break;
                }
            }
        }
        require(validator.tokens > minTokens, "Insufficient tokens");
        _replaceBondedValidator(valAddr, minTokensIndex);
        _decentralizationCheck(validator.tokens);
    }

    /**
     * @notice Confirm validator status from Unbonding to Unbonded
     * @param _valAddr the address of the validator
     */
    function confirmUnbondedValidator(address _valAddr) external {
        dt.Validator storage validator = validators[_valAddr];
        require(validator.status == dt.ValidatorStatus.Unbonding, "Validator not unbonding");
        require(block.number >= validator.unbondBlock, "Unbond block not reached");

        validator.status = dt.ValidatorStatus.Unbonded;
        delete validator.unbondBlock;
        emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Unbonded);
    }

    /**
     * @notice Delegate CELR tokens to a validator
     * @dev Minimal amount per delegate operation is 1 CELR
     * @param _valAddr validator to delegate
     * @param _tokens the amount of delegated CELR tokens
     */
    function delegate(address _valAddr, uint256 _tokens) public whenNotPaused {
        address delAddr = msg.sender;
        require(_tokens >= dt.CELR_DECIMAL, "Minimal amount is 1 CELR");

        dt.Validator storage validator = validators[_valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        uint256 shares = _tokenToShare(_tokens, validator.tokens, validator.shares);

        dt.Delegator storage delegator = validator.delegators[delAddr];
        delegator.shares += shares;
        validator.shares += shares;
        validator.tokens += _tokens;
        if (validator.status == dt.ValidatorStatus.Bonded) {
            bondedTokens += _tokens;
            _decentralizationCheck(validator.tokens);
        }
        CELER_TOKEN.safeTransferFrom(delAddr, address(this), _tokens);
        emit DelegationUpdate(_valAddr, delAddr, validator.tokens, delegator.shares, int256(_tokens));
    }

    /**
     * @notice Undelegate shares from a validator
     * @dev Tokens are delegated by the msgSender to the validator
     * @param _valAddr the address of the validator
     * @param _shares undelegate shares
     */
    function undelegateShares(address _valAddr, uint256 _shares) external {
        require(_shares >= dt.CELR_DECIMAL, "Minimal amount is 1 share");
        dt.Validator storage validator = validators[_valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        uint256 tokens = _shareToToken(_shares, validator.tokens, validator.shares);
        _undelegate(validator, _valAddr, tokens, _shares);
    }

    /**
     * @notice Undelegate shares from a validator
     * @dev Tokens are delegated by the msgSender to the validator
     * @param _valAddr the address of the validator
     * @param _tokens undelegate tokens
     */
    function undelegateTokens(address _valAddr, uint256 _tokens) external {
        require(_tokens >= dt.CELR_DECIMAL, "Minimal amount is 1 CELR");
        dt.Validator storage validator = validators[_valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        uint256 shares = _tokenToShare(_tokens, validator.tokens, validator.shares);
        _undelegate(validator, _valAddr, _tokens, shares);
    }

    /**
     * @notice Complete pending undelegations from a validator
     * @param _valAddr the address of the validator
     */
    function completeUndelegate(address _valAddr) external {
        address delAddr = msg.sender;
        dt.Validator storage validator = validators[_valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        dt.Delegator storage delegator = validator.delegators[delAddr];

        uint256 unbondingPeriod = params[dt.ParamName.UnbondingPeriod];
        bool isUnbonded = validator.status == dt.ValidatorStatus.Unbonded;
        // for all pending undelegations
        uint32 i;
        uint256 undelegationShares;
        for (i = delegator.undelegations.head; i < delegator.undelegations.tail; i++) {
            if (isUnbonded || delegator.undelegations.queue[i].creationBlock + unbondingPeriod <= block.number) {
                // complete undelegation when the validator becomes unbonded or
                // the unbondingPeriod for the pending undelegation is up.
                undelegationShares += delegator.undelegations.queue[i].shares;
                delete delegator.undelegations.queue[i];
                continue;
            }
            break;
        }
        delegator.undelegations.head = i;

        require(undelegationShares > 0, "No undelegation ready to be completed");
        uint256 tokens = _shareToToken(undelegationShares, validator.undelegationTokens, validator.undelegationShares);
        validator.undelegationShares -= undelegationShares;
        validator.undelegationTokens -= tokens;
        CELER_TOKEN.safeTransfer(delAddr, tokens);
        emit Undelegated(_valAddr, delAddr, tokens);
    }

    /**
     * @notice Update commission rate
     * @param _newRate new commission rate
     */
    function updateCommissionRate(uint64 _newRate) external {
        address valAddr = msg.sender;
        dt.Validator storage validator = validators[valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        require(_newRate <= dt.COMMISSION_RATE_BASE, "Invalid new rate");
        validator.commissionRate = _newRate;
        emit ValidatorNotice(valAddr, "commission", abi.encode(_newRate), address(0));
    }

    /**
     * @notice Update minimal self delegation value
     * @param _minSelfDelegation minimal amount of tokens staked by the validator itself
     */
    function updateMinSelfDelegation(uint256 _minSelfDelegation) external {
        address valAddr = msg.sender;
        dt.Validator storage validator = validators[valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        require(_minSelfDelegation >= params[dt.ParamName.MinSelfDelegation], "Insufficient min self delegation");
        if (_minSelfDelegation < validator.minSelfDelegation) {
            require(validator.status != dt.ValidatorStatus.Bonded, "Validator is bonded");
            validator.bondBlock = uint64(block.number + params[dt.ParamName.AdvanceNoticePeriod]);
        }
        validator.minSelfDelegation = _minSelfDelegation;
        emit ValidatorNotice(valAddr, "min-self-delegation", abi.encode(_minSelfDelegation), address(0));
    }

    /**
     * @notice Slash a validator and its delegators
     * @param _slashRequest slash request bytes coded in protobuf
     * @param _sigs list of validator signatures
     */
    function slash(bytes calldata _slashRequest, bytes[] calldata _sigs) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Slash"));
        verifySignatures(abi.encodePacked(domain, _slashRequest), _sigs);

        PbStaking.Slash memory request = PbStaking.decSlash(_slashRequest);
        require(block.timestamp < request.expireTime, "Slash expired");
        require(request.slashFactor <= dt.SLASH_FACTOR_DECIMAL, "Invalid slash factor");
        require(request.slashFactor <= params[dt.ParamName.MaxSlashFactor], "Exceed max slash factor");
        require(!slashNonces[request.nonce], "Used slash nonce");
        slashNonces[request.nonce] = true;

        address valAddr = request.validator;
        dt.Validator storage validator = validators[valAddr];
        require(
            validator.status == dt.ValidatorStatus.Bonded || validator.status == dt.ValidatorStatus.Unbonding,
            "Invalid validator status"
        );

        // slash delegated tokens
        uint256 slashAmt = (validator.tokens * request.slashFactor) / dt.SLASH_FACTOR_DECIMAL;
        validator.tokens -= slashAmt;
        if (validator.status == dt.ValidatorStatus.Bonded) {
            bondedTokens -= slashAmt;
            if (request.jailPeriod > 0 || !hasMinRequiredTokens(valAddr, true)) {
                _unbondValidator(valAddr);
            }
        }
        if (validator.status == dt.ValidatorStatus.Unbonding && request.jailPeriod > 0) {
            validator.bondBlock = uint64(block.number + request.jailPeriod);
        }
        emit DelegationUpdate(valAddr, address(0), validator.tokens, 0, -int256(slashAmt));

        // slash pending undelegations
        uint256 slashUndelegation = (validator.undelegationTokens * request.slashFactor) / dt.SLASH_FACTOR_DECIMAL;
        validator.undelegationTokens -= slashUndelegation;
        slashAmt += slashUndelegation;

        uint256 collectAmt;
        for (uint256 i = 0; i < request.collectors.length; i++) {
            PbStaking.AcctAmtPair memory collector = request.collectors[i];
            if (collectAmt + collector.amount > slashAmt) {
                collector.amount = slashAmt - collectAmt;
            }
            if (collector.amount > 0) {
                collectAmt += collector.amount;
                if (collector.account == address(0)) {
                    CELER_TOKEN.safeTransfer(msg.sender, collector.amount);
                    emit SlashAmtCollected(msg.sender, collector.amount);
                } else {
                    CELER_TOKEN.safeTransfer(collector.account, collector.amount);
                    emit SlashAmtCollected(collector.account, collector.amount);
                }
            }
        }
        forfeiture += slashAmt - collectAmt;
        emit Slash(valAddr, request.nonce, slashAmt);
    }

    function collectForfeiture() external {
        require(forfeiture > 0, "Nothing to collect");
        CELER_TOKEN.safeTransfer(rewardContract, forfeiture);
        forfeiture = 0;
    }

    /**
     * @notice Validator notice event, could be triggered by anyone
     */
    function validatorNotice(
        address _valAddr,
        string calldata _key,
        bytes calldata _data
    ) external {
        dt.Validator storage validator = validators[_valAddr];
        require(validator.status != dt.ValidatorStatus.Null, "Validator is not initialized");
        emit ValidatorNotice(_valAddr, _key, _data, msg.sender);
    }

    function setParamValue(dt.ParamName _name, uint256 _value) external {
        require(msg.sender == govContract, "Caller is not gov contract");
        if (_name == dt.ParamName.MaxBondedValidators) {
            require(bondedValAddrs.length <= _value, "invalid value");
        }
        params[_name] = _value;
    }

    function setGovContract(address _addr) external onlyOwner {
        govContract = _addr;
    }

    function setRewardContract(address _addr) external onlyOwner {
        rewardContract = _addr;
    }

    /**
     * @notice Set max slash factor
     */
    function setMaxSlashFactor(uint256 _maxSlashFactor) external onlyOwner {
        params[dt.ParamName.MaxSlashFactor] = _maxSlashFactor;
    }

    /**
     * @notice Owner drains tokens when the contract is paused
     * @dev emergency use only
     * @param _amount drained token amount
     */
    function drainToken(uint256 _amount) external whenPaused onlyOwner {
        CELER_TOKEN.safeTransfer(msg.sender, _amount);
    }

    /**************************
     *  Public View Functions *
     **************************/

    /**
     * @notice Validate if a message is signed by quorum tokens
     * @param _msg signed message
     * @param _sigs list of validator signatures
     */
    function verifySignatures(bytes memory _msg, bytes[] memory _sigs) public view returns (bool) {
        bytes32 hash = keccak256(_msg).toEthSignedMessageHash();
        uint256 signedTokens;
        address prev = address(0);
        uint256 quorum = getQuorumTokens();
        for (uint256 i = 0; i < _sigs.length; i++) {
            address signer = hash.recover(_sigs[i]);
            require(signer > prev, "Signers not in ascending order");
            prev = signer;
            dt.Validator storage validator = validators[signerVals[signer]];
            if (validator.status != dt.ValidatorStatus.Bonded) {
                continue;
            }
            signedTokens += validator.tokens;
            if (signedTokens >= quorum) {
                return true;
            }
        }
        revert("Quorum not reached");
    }

    /**
     * @notice Verifies that a message is signed by a quorum among the validators.
     * @param _msg signed message
     * @param _sigs the list of signatures
     */
    function verifySigs(
        bytes memory _msg,
        bytes[] calldata _sigs,
        address[] calldata,
        uint256[] calldata
    ) public view override {
        require(verifySignatures(_msg, _sigs), "Failed to verify sigs");
    }

    /**
     * @notice Get quorum amount of tokens
     * @return the quorum amount
     */
    function getQuorumTokens() public view returns (uint256) {
        return (bondedTokens * 2) / 3 + 1;
    }

    /**
     * @notice Get validator info
     * @param _valAddr the address of the validator
     * @return Validator token amount
     */
    function getValidatorTokens(address _valAddr) public view returns (uint256) {
        return validators[_valAddr].tokens;
    }

    /**
     * @notice Get validator info
     * @param _valAddr the address of the validator
     * @return Validator status
     */
    function getValidatorStatus(address _valAddr) public view returns (dt.ValidatorStatus) {
        return validators[_valAddr].status;
    }

    /**
     * @notice Check the given address is a validator or not
     * @param _addr the address to check
     * @return the given address is a validator or not
     */
    function isBondedValidator(address _addr) public view returns (bool) {
        return validators[_addr].status == dt.ValidatorStatus.Bonded;
    }

    /**
     * @notice Get the number of validators
     * @return the number of validators
     */
    function getValidatorNum() public view returns (uint256) {
        return valAddrs.length;
    }

    /**
     * @notice Get the number of bonded validators
     * @return the number of bonded validators
     */
    function getBondedValidatorNum() public view returns (uint256) {
        return bondedValAddrs.length;
    }

    /**
     * @return addresses and token amounts of bonded validators
     */
    function getBondedValidatorsTokens() public view returns (dt.ValidatorTokens[] memory) {
        dt.ValidatorTokens[] memory infos = new dt.ValidatorTokens[](bondedValAddrs.length);
        for (uint256 i = 0; i < bondedValAddrs.length; i++) {
            address valAddr = bondedValAddrs[i];
            infos[i] = dt.ValidatorTokens(valAddr, validators[valAddr].tokens);
        }
        return infos;
    }

    /**
     * @notice Check if min token requirements are met
     * @param _valAddr the address of the validator
     * @param _checkSelfDelegation check self delegation
     */
    function hasMinRequiredTokens(address _valAddr, bool _checkSelfDelegation) public view returns (bool) {
        dt.Validator storage v = validators[_valAddr];
        uint256 valTokens = v.tokens;
        if (valTokens < params[dt.ParamName.MinValidatorTokens]) {
            return false;
        }
        if (_checkSelfDelegation) {
            uint256 selfDelegation = _shareToToken(v.delegators[_valAddr].shares, valTokens, v.shares);
            if (selfDelegation < v.minSelfDelegation) {
                return false;
            }
        }
        return true;
    }

    /**
     * @notice Get the delegator info of a specific validator
     * @param _valAddr the address of the validator
     * @param _delAddr the address of the delegator
     * @return DelegatorInfo from the given validator
     */
    function getDelegatorInfo(address _valAddr, address _delAddr) public view returns (dt.DelegatorInfo memory) {
        dt.Validator storage validator = validators[_valAddr];
        dt.Delegator storage d = validator.delegators[_delAddr];
        uint256 tokens = _shareToToken(d.shares, validator.tokens, validator.shares);

        uint256 undelegationShares;
        uint256 withdrawableUndelegationShares;
        uint256 unbondingPeriod = params[dt.ParamName.UnbondingPeriod];
        bool isUnbonded = validator.status == dt.ValidatorStatus.Unbonded;
        uint256 len = d.undelegations.tail - d.undelegations.head;
        dt.Undelegation[] memory undelegations = new dt.Undelegation[](len);
        for (uint256 i = 0; i < len; i++) {
            undelegations[i] = d.undelegations.queue[i + d.undelegations.head];
            undelegationShares += undelegations[i].shares;
            if (isUnbonded || undelegations[i].creationBlock + unbondingPeriod <= block.number) {
                withdrawableUndelegationShares += undelegations[i].shares;
            }
        }
        uint256 undelegationTokens = _shareToToken(
            undelegationShares,
            validator.undelegationTokens,
            validator.undelegationShares
        );
        uint256 withdrawableUndelegationTokens = _shareToToken(
            withdrawableUndelegationShares,
            validator.undelegationTokens,
            validator.undelegationShares
        );

        return
            dt.DelegatorInfo(
                _valAddr,
                tokens,
                d.shares,
                undelegations,
                undelegationTokens,
                withdrawableUndelegationTokens
            );
    }

    /**
     * @notice Get the value of a specific uint parameter
     * @param _name the key of this parameter
     * @return the value of this parameter
     */
    function getParamValue(dt.ParamName _name) public view returns (uint256) {
        return params[_name];
    }

    /*********************
     * Private Functions *
     *********************/

    function _undelegate(
        dt.Validator storage validator,
        address _valAddr,
        uint256 _tokens,
        uint256 _shares
    ) private {
        address delAddr = msg.sender;
        dt.Delegator storage delegator = validator.delegators[delAddr];
        delegator.shares -= _shares;
        validator.shares -= _shares;
        validator.tokens -= _tokens;
        if (validator.tokens != validator.shares && delegator.shares <= 2) {
            // Remove residual share caused by rounding error when total shares and tokens are not equal
            validator.shares -= delegator.shares;
            delegator.shares = 0;
        }
        require(delegator.shares == 0 || delegator.shares >= dt.CELR_DECIMAL, "not enough remaining shares");

        if (validator.status == dt.ValidatorStatus.Unbonded) {
            CELER_TOKEN.safeTransfer(delAddr, _tokens);
            emit Undelegated(_valAddr, delAddr, _tokens);
            return;
        } else if (validator.status == dt.ValidatorStatus.Bonded) {
            bondedTokens -= _tokens;
            if (!hasMinRequiredTokens(_valAddr, delAddr == _valAddr)) {
                _unbondValidator(_valAddr);
            }
        }
        require(
            delegator.undelegations.tail - delegator.undelegations.head < dt.MAX_UNDELEGATION_ENTRIES,
            "Exceed max undelegation entries"
        );

        uint256 undelegationShares = _tokenToShare(_tokens, validator.undelegationTokens, validator.undelegationShares);
        validator.undelegationShares += undelegationShares;
        validator.undelegationTokens += _tokens;
        dt.Undelegation storage undelegation = delegator.undelegations.queue[delegator.undelegations.tail];
        undelegation.shares = undelegationShares;
        undelegation.creationBlock = block.number;
        delegator.undelegations.tail++;

        emit DelegationUpdate(_valAddr, delAddr, validator.tokens, delegator.shares, -int256(_tokens));
    }

    /**
     * @notice Set validator to bonded
     * @param _valAddr the address of the validator
     */
    function _setBondedValidator(address _valAddr) private {
        dt.Validator storage validator = validators[_valAddr];
        validator.status = dt.ValidatorStatus.Bonded;
        delete validator.unbondBlock;
        bondedTokens += validator.tokens;
        emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Bonded);
    }

    /**
     * @notice Set validator to unbonding
     * @param _valAddr the address of the validator
     */
    function _setUnbondingValidator(address _valAddr) private {
        dt.Validator storage validator = validators[_valAddr];
        validator.status = dt.ValidatorStatus.Unbonding;
        validator.unbondBlock = uint64(block.number + params[dt.ParamName.UnbondingPeriod]);
        bondedTokens -= validator.tokens;
        emit ValidatorStatusUpdate(_valAddr, dt.ValidatorStatus.Unbonding);
    }

    /**
     * @notice Bond a validator
     * @param _valAddr the address of the validator
     */
    function _bondValidator(address _valAddr) private {
        bondedValAddrs.push(_valAddr);
        _setBondedValidator(_valAddr);
    }

    /**
     * @notice Replace a bonded validator
     * @param _valAddr the address of the new validator
     * @param _index the index of the validator to be replaced
     */
    function _replaceBondedValidator(address _valAddr, uint256 _index) private {
        _setUnbondingValidator(bondedValAddrs[_index]);
        bondedValAddrs[_index] = _valAddr;
        _setBondedValidator(_valAddr);
    }

    /**
     * @notice Unbond a validator
     * @param _valAddr validator to be removed
     */
    function _unbondValidator(address _valAddr) private {
        uint256 lastIndex = bondedValAddrs.length - 1;
        for (uint256 i = 0; i < bondedValAddrs.length; i++) {
            if (bondedValAddrs[i] == _valAddr) {
                if (i < lastIndex) {
                    bondedValAddrs[i] = bondedValAddrs[lastIndex];
                }
                bondedValAddrs.pop();
                _setUnbondingValidator(_valAddr);
                return;
            }
        }
        revert("Not bonded validator");
    }

    /**
     * @notice Check if one validator has too much power
     * @param _valTokens token amounts of the validator
     */
    function _decentralizationCheck(uint256 _valTokens) private view {
        uint256 bondedValNum = bondedValAddrs.length;
        if (bondedValNum == 2 || bondedValNum == 3) {
            require(_valTokens < getQuorumTokens(), "Single validator should not have quorum tokens");
        } else if (bondedValNum > 3) {
            require(_valTokens < bondedTokens / 3, "Single validator should not have 1/3 tokens");
        }
    }

    /**
     * @notice Convert token to share
     */
    function _tokenToShare(
        uint256 tokens,
        uint256 totalTokens,
        uint256 totalShares
    ) private pure returns (uint256) {
        if (totalTokens == 0) {
            return tokens;
        }
        return (tokens * totalShares) / totalTokens;
    }

    /**
     * @notice Convert share to token
     */
    function _shareToToken(
        uint256 shares,
        uint256 totalTokens,
        uint256 totalShares
    ) private pure returns (uint256) {
        if (totalShares == 0) {
            return shares;
        }
        return (shares * totalTokens) / totalShares;
    }
}

File 23 of 120 : Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @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);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

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

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

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

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

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

File 24 of 120 : Ownable.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity ^0.8.0;

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 *
 * This adds a normal func that setOwner if _owner is address(0). So we can't allow
 * renounceOwnership. So we can support Proxy based upgradable contract
 */
abstract contract Ownable {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _setOwner(msg.sender);
    }

    /**
     * @dev Only to be called by inherit contracts, in their init func called by Proxy
     * we require _owner == address(0), which is only possible when it's a delegateCall
     * because constructor sets _owner in contract state.
     */
    function initOwner() internal {
        require(_owner == address(0), "owner already set");
        _setOwner(msg.sender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == msg.sender, "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _setOwner(newOwner);
    }

    function _setOwner(address newOwner) private {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 25 of 120 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

File 26 of 120 : ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else if (signature.length == 64) {
            bytes32 r;
            bytes32 vs;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                vs := mload(add(signature, 0x40))
            }
            return tryRecover(hash, r, vs);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }
        if (v != 27 && v != 28) {
            return (address(0), RecoverError.InvalidSignatureV);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

File 27 of 120 : ISigsVerifier.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface ISigsVerifier {
    /**
     * @notice Verifies that a message is signed by a quorum among the signers.
     * @param _msg signed message
     * @param _sigs list of signatures sorted by signer addresses in ascending order
     * @param _signers sorted list of current signers
     * @param _powers powers of current signers
     */
    function verifySigs(
        bytes memory _msg,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external view;
}

File 28 of 120 : PbStaking.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/staking.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbStaking {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct StakingReward {
        address recipient; // tag: 1
        uint256 cumulativeRewardAmount; // tag: 2
    } // end struct StakingReward

    function decStakingReward(bytes memory raw) internal pure returns (StakingReward memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.recipient = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.cumulativeRewardAmount = Pb._uint256(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder StakingReward

    struct Slash {
        address validator; // tag: 1
        uint64 nonce; // tag: 2
        uint64 slashFactor; // tag: 3
        uint64 expireTime; // tag: 4
        uint64 jailPeriod; // tag: 5
        AcctAmtPair[] collectors; // tag: 6
    } // end struct Slash

    function decSlash(bytes memory raw) internal pure returns (Slash memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256[] memory cnts = buf.cntTags(6);
        m.collectors = new AcctAmtPair[](cnts[6]);
        cnts[6] = 0; // reset counter for later use

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.validator = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.nonce = uint64(buf.decVarint());
            } else if (tag == 3) {
                m.slashFactor = uint64(buf.decVarint());
            } else if (tag == 4) {
                m.expireTime = uint64(buf.decVarint());
            } else if (tag == 5) {
                m.jailPeriod = uint64(buf.decVarint());
            } else if (tag == 6) {
                m.collectors[cnts[6]] = decAcctAmtPair(buf.decBytes());
                cnts[6]++;
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder Slash

    struct AcctAmtPair {
        address account; // tag: 1
        uint256 amount; // tag: 2
    } // end struct AcctAmtPair

    function decAcctAmtPair(bytes memory raw) internal pure returns (AcctAmtPair memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.account = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.amount = Pb._uint256(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder AcctAmtPair
}

File 29 of 120 : Whitelist.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "./Ownable.sol";

abstract contract Whitelist is Ownable {
    mapping(address => bool) public whitelist;
    bool public whitelistEnabled;

    event WhitelistedAdded(address account);
    event WhitelistedRemoved(address account);

    modifier onlyWhitelisted() {
        if (whitelistEnabled) {
            require(isWhitelisted(msg.sender), "Caller is not whitelisted");
        }
        _;
    }

    /**
     * @notice Set whitelistEnabled
     */
    function setWhitelistEnabled(bool _whitelistEnabled) external onlyOwner {
        whitelistEnabled = _whitelistEnabled;
    }

    /**
     * @notice Add an account to whitelist
     */
    function addWhitelisted(address account) external onlyOwner {
        require(!isWhitelisted(account), "Already whitelisted");
        whitelist[account] = true;
        emit WhitelistedAdded(account);
    }

    /**
     * @notice Remove an account from whitelist
     */
    function removeWhitelisted(address account) external onlyOwner {
        require(isWhitelisted(account), "Not whitelisted");
        whitelist[account] = false;
        emit WhitelistedRemoved(account);
    }

    /**
     * @return is account whitelisted
     */
    function isWhitelisted(address account) public view returns (bool) {
        return whitelist[account];
    }
}

File 30 of 120 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        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_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}

File 31 of 120 : Pb.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

// runtime proto sol library
library Pb {
    enum WireType {
        Varint,
        Fixed64,
        LengthDelim,
        StartGroup,
        EndGroup,
        Fixed32
    }

    struct Buffer {
        uint256 idx; // the start index of next read. when idx=b.length, we're done
        bytes b; // hold serialized proto msg, readonly
    }

    // create a new in-memory Buffer object from raw msg bytes
    function fromBytes(bytes memory raw) internal pure returns (Buffer memory buf) {
        buf.b = raw;
        buf.idx = 0;
    }

    // whether there are unread bytes
    function hasMore(Buffer memory buf) internal pure returns (bool) {
        return buf.idx < buf.b.length;
    }

    // decode current field number and wiretype
    function decKey(Buffer memory buf) internal pure returns (uint256 tag, WireType wiretype) {
        uint256 v = decVarint(buf);
        tag = v / 8;
        wiretype = WireType(v & 7);
    }

    // count tag occurrences, return an array due to no memory map support
    // have to create array for (maxtag+1) size. cnts[tag] = occurrences
    // should keep buf.idx unchanged because this is only a count function
    function cntTags(Buffer memory buf, uint256 maxtag) internal pure returns (uint256[] memory cnts) {
        uint256 originalIdx = buf.idx;
        cnts = new uint256[](maxtag + 1); // protobuf's tags are from 1 rather than 0
        uint256 tag;
        WireType wire;
        while (hasMore(buf)) {
            (tag, wire) = decKey(buf);
            cnts[tag] += 1;
            skipValue(buf, wire);
        }
        buf.idx = originalIdx;
    }

    // read varint from current buf idx, move buf.idx to next read, return the int value
    function decVarint(Buffer memory buf) internal pure returns (uint256 v) {
        bytes10 tmp; // proto int is at most 10 bytes (7 bits can be used per byte)
        bytes memory bb = buf.b; // get buf.b mem addr to use in assembly
        v = buf.idx; // use v to save one additional uint variable
        assembly {
            tmp := mload(add(add(bb, 32), v)) // load 10 bytes from buf.b[buf.idx] to tmp
        }
        uint256 b; // store current byte content
        v = 0; // reset to 0 for return value
        for (uint256 i = 0; i < 10; i++) {
            assembly {
                b := byte(i, tmp) // don't use tmp[i] because it does bound check and costs extra
            }
            v |= (b & 0x7F) << (i * 7);
            if (b & 0x80 == 0) {
                buf.idx += i + 1;
                return v;
            }
        }
        revert(); // i=10, invalid varint stream
    }

    // read length delimited field and return bytes
    function decBytes(Buffer memory buf) internal pure returns (bytes memory b) {
        uint256 len = decVarint(buf);
        uint256 end = buf.idx + len;
        require(end <= buf.b.length); // avoid overflow
        b = new bytes(len);
        bytes memory bufB = buf.b; // get buf.b mem addr to use in assembly
        uint256 bStart;
        uint256 bufBStart = buf.idx;
        assembly {
            bStart := add(b, 32)
            bufBStart := add(add(bufB, 32), bufBStart)
        }
        for (uint256 i = 0; i < len; i += 32) {
            assembly {
                mstore(add(bStart, i), mload(add(bufBStart, i)))
            }
        }
        buf.idx = end;
    }

    // return packed ints
    function decPacked(Buffer memory buf) internal pure returns (uint256[] memory t) {
        uint256 len = decVarint(buf);
        uint256 end = buf.idx + len;
        require(end <= buf.b.length); // avoid overflow
        // array in memory must be init w/ known length
        // so we have to create a tmp array w/ max possible len first
        uint256[] memory tmp = new uint256[](len);
        uint256 i = 0; // count how many ints are there
        while (buf.idx < end) {
            tmp[i] = decVarint(buf);
            i++;
        }
        t = new uint256[](i); // init t with correct length
        for (uint256 j = 0; j < i; j++) {
            t[j] = tmp[j];
        }
        return t;
    }

    // move idx pass current value field, to beginning of next tag or msg end
    function skipValue(Buffer memory buf, WireType wire) internal pure {
        if (wire == WireType.Varint) {
            decVarint(buf);
        } else if (wire == WireType.LengthDelim) {
            uint256 len = decVarint(buf);
            buf.idx += len; // skip len bytes value data
            require(buf.idx <= buf.b.length); // avoid overflow
        } else {
            revert();
        } // unsupported wiretype
    }

    // type conversion help utils
    function _bool(uint256 x) internal pure returns (bool v) {
        return x != 0;
    }

    function _uint256(bytes memory b) internal pure returns (uint256 v) {
        require(b.length <= 32); // b's length must be smaller than or equal to 32
        assembly {
            v := mload(add(b, 32))
        } // load all 32bytes to v
        v = v >> (8 * (32 - b.length)); // only first b.length is valid
    }

    function _address(bytes memory b) internal pure returns (address v) {
        v = _addressPayable(b);
    }

    function _addressPayable(bytes memory b) internal pure returns (address payable v) {
        require(b.length == 20);
        //load 32bytes then shift right 12 bytes
        assembly {
            v := div(mload(add(b, 32)), 0x1000000000000000000000000)
        }
    }

    function _bytes32(bytes memory b) internal pure returns (bytes32 v) {
        require(b.length == 32);
        assembly {
            v := mload(add(b, 32))
        }
    }

    // uint[] to uint8[]
    function uint8s(uint256[] memory arr) internal pure returns (uint8[] memory t) {
        t = new uint8[](arr.length);
        for (uint256 i = 0; i < t.length; i++) {
            t[i] = uint8(arr[i]);
        }
    }

    function uint32s(uint256[] memory arr) internal pure returns (uint32[] memory t) {
        t = new uint32[](arr.length);
        for (uint256 i = 0; i < t.length; i++) {
            t[i] = uint32(arr[i]);
        }
    }

    function uint64s(uint256[] memory arr) internal pure returns (uint64[] memory t) {
        t = new uint64[](arr.length);
        for (uint256 i = 0; i < t.length; i++) {
            t[i] = uint64(arr[i]);
        }
    }

    function bools(uint256[] memory arr) internal pure returns (bool[] memory t) {
        t = new bool[](arr.length);
        for (uint256 i = 0; i < t.length; i++) {
            t[i] = arr[i] != 0;
        }
    }
}

File 32 of 120 : Viewer.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import {DataTypes as dt} from "./DataTypes.sol";
import "./Staking.sol";

/**
 * @title Viewer of the staking contract
 * @notice Using a separate viewer contract to reduce staking contract size
 */
contract Viewer {
    Staking public immutable staking;

    constructor(Staking _staking) {
        staking = _staking;
    }

    function getValidatorInfos() public view returns (dt.ValidatorInfo[] memory) {
        uint256 valNum = staking.getValidatorNum();
        dt.ValidatorInfo[] memory infos = new dt.ValidatorInfo[](valNum);
        for (uint32 i = 0; i < valNum; i++) {
            infos[i] = getValidatorInfo(staking.valAddrs(i));
        }
        return infos;
    }

    function getBondedValidatorInfos() public view returns (dt.ValidatorInfo[] memory) {
        uint256 bondedValNum = staking.getBondedValidatorNum();
        dt.ValidatorInfo[] memory infos = new dt.ValidatorInfo[](bondedValNum);
        for (uint32 i = 0; i < bondedValNum; i++) {
            infos[i] = getValidatorInfo(staking.bondedValAddrs(i));
        }
        return infos;
    }

    function getValidatorInfo(address _valAddr) public view returns (dt.ValidatorInfo memory) {
        (
            dt.ValidatorStatus status,
            address signer,
            uint256 tokens,
            uint256 shares,
            ,
            ,
            uint256 minSelfDelegation,
            ,
            ,
            uint64 commissionRate
        ) = staking.validators(_valAddr);
        return
            dt.ValidatorInfo({
                valAddr: _valAddr,
                status: status,
                signer: signer,
                tokens: tokens,
                shares: shares,
                minSelfDelegation: minSelfDelegation,
                commissionRate: commissionRate
            });
    }

    function getDelegatorInfos(address _delAddr) public view returns (dt.DelegatorInfo[] memory) {
        uint256 valNum = staking.getValidatorNum();
        dt.DelegatorInfo[] memory infos = new dt.DelegatorInfo[](valNum);
        uint32 num = 0;
        for (uint32 i = 0; i < valNum; i++) {
            address valAddr = staking.valAddrs(i);
            infos[i] = staking.getDelegatorInfo(valAddr, _delAddr);
            if (infos[i].shares != 0 || infos[i].undelegationTokens != 0) {
                num++;
            }
        }
        dt.DelegatorInfo[] memory res = new dt.DelegatorInfo[](num);
        uint32 j = 0;
        for (uint32 i = 0; i < valNum; i++) {
            if (infos[i].shares != 0 || infos[i].undelegationTokens != 0) {
                res[j] = infos[i];
                j++;
            }
        }
        return res;
    }

    function getDelegatorTokens(address _delAddr) public view returns (uint256, uint256) {
        dt.DelegatorInfo[] memory infos = getDelegatorInfos(_delAddr);
        uint256 tokens;
        uint256 undelegationTokens;
        for (uint32 i = 0; i < infos.length; i++) {
            tokens += infos[i].tokens;
            undelegationTokens += infos[i].undelegationTokens;
        }
        return (tokens, undelegationTokens);
    }

    /**
     * @notice Get the minimum staking pool of all bonded validators
     * @return the minimum staking pool of all bonded validators
     */
    function getMinValidatorTokens() public view returns (uint256) {
        uint256 bondedValNum = staking.getBondedValidatorNum();
        if (bondedValNum < staking.params(dt.ParamName.MaxBondedValidators)) {
            return 0;
        }
        uint256 minTokens = dt.MAX_INT;
        for (uint256 i = 0; i < bondedValNum; i++) {
            uint256 tokens = staking.getValidatorTokens(staking.bondedValAddrs(i));
            if (tokens < minTokens) {
                minTokens = tokens;
                if (minTokens == 0) {
                    return 0;
                }
            }
        }
        return minTokens;
    }

    function shouldBondValidator(address _valAddr) public view returns (bool) {
        (dt.ValidatorStatus status, , uint256 tokens, , , , , uint64 bondBlock, , ) = staking.validators(_valAddr);
        if (status == dt.ValidatorStatus.Null || status == dt.ValidatorStatus.Bonded) {
            return false;
        }
        if (block.number < bondBlock) {
            return false;
        }
        if (!staking.hasMinRequiredTokens(_valAddr, true)) {
            return false;
        }
        if (tokens <= getMinValidatorTokens()) {
            return false;
        }
        uint256 nextBondBlock = staking.nextBondBlock();
        if (block.number < nextBondBlock) {
            return false;
        }
        return true;
    }
}

File 33 of 120 : SGN.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypes as dt} from "./DataTypes.sol";
import "../libraries/PbSgn.sol";
import "../safeguard/Pauser.sol";
import "./Staking.sol";

/**
 * @title contract of SGN chain
 */
contract SGN is Pauser {
    using SafeERC20 for IERC20;

    Staking public immutable staking;
    bytes32[] public deposits;
    // account -> (token -> amount)
    mapping(address => mapping(address => uint256)) public withdrawnAmts;
    mapping(address => bytes) public sgnAddrs;

    /* Events */
    event SgnAddrUpdate(address indexed valAddr, bytes oldAddr, bytes newAddr);
    event Deposit(uint256 depositId, address account, address token, uint256 amount);
    event Withdraw(address account, address token, uint256 amount);

    /**
     * @notice SGN constructor
     * @dev Need to deploy Staking contract first before deploying SGN contract
     * @param _staking address of Staking Contract
     */
    constructor(Staking _staking) {
        staking = _staking;
    }

    /**
     * @notice Update sgn address
     * @param _sgnAddr the new address in the layer 2 SGN
     */
    function updateSgnAddr(bytes calldata _sgnAddr) external {
        address valAddr = msg.sender;
        if (staking.signerVals(msg.sender) != address(0)) {
            valAddr = staking.signerVals(msg.sender);
        }

        dt.ValidatorStatus status = staking.getValidatorStatus(valAddr);
        require(status == dt.ValidatorStatus.Unbonded, "Not unbonded validator");

        bytes memory oldAddr = sgnAddrs[valAddr];
        sgnAddrs[valAddr] = _sgnAddr;

        staking.validatorNotice(valAddr, "sgn-addr", _sgnAddr);
        emit SgnAddrUpdate(valAddr, oldAddr, _sgnAddr);
    }

    /**a
     * @notice Deposit to SGN
     * @param _amount subscription fee paid along this function call in CELR tokens
     */
    function deposit(address _token, uint256 _amount) external whenNotPaused {
        address msgSender = msg.sender;
        deposits.push(keccak256(abi.encodePacked(msgSender, _token, _amount)));
        IERC20(_token).safeTransferFrom(msgSender, address(this), _amount);
        uint64 depositId = uint64(deposits.length - 1);
        emit Deposit(depositId, msgSender, _token, _amount);
    }

    /**
     * @notice Withdraw token
     * @dev Here we use cumulative amount to make withdrawal process idempotent
     * @param _withdrawalRequest withdrawal request bytes coded in protobuf
     * @param _sigs list of validator signatures
     */
    function withdraw(bytes calldata _withdrawalRequest, bytes[] calldata _sigs) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Withdrawal"));
        staking.verifySignatures(abi.encodePacked(domain, _withdrawalRequest), _sigs);
        PbSgn.Withdrawal memory withdrawal = PbSgn.decWithdrawal(_withdrawalRequest);

        uint256 amount = withdrawal.cumulativeAmount - withdrawnAmts[withdrawal.account][withdrawal.token];
        require(amount > 0, "No new amount to withdraw");
        withdrawnAmts[withdrawal.account][withdrawal.token] = withdrawal.cumulativeAmount;

        IERC20(withdrawal.token).safeTransfer(withdrawal.account, amount);
        emit Withdraw(withdrawal.account, withdrawal.token, amount);
    }

    /**
     * @notice Owner drains one type of tokens when the contract is paused
     * @dev emergency use only
     * @param _amount drained token amount
     */
    function drainToken(address _token, uint256 _amount) external whenPaused onlyOwner {
        IERC20(_token).safeTransfer(msg.sender, _amount);
    }
}

File 34 of 120 : PbSgn.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/sgn.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbSgn {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct Withdrawal {
        address account; // tag: 1
        address token; // tag: 2
        uint256 cumulativeAmount; // tag: 3
    } // end struct Withdrawal

    function decWithdrawal(bytes memory raw) internal pure returns (Withdrawal memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.account = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.token = Pb._address(buf.decBytes());
            } else if (tag == 3) {
                m.cumulativeAmount = Pb._uint256(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder Withdrawal
}

File 35 of 120 : PeggedTokenBridgeV2.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "../interfaces/ISigsVerifier.sol";
import "../interfaces/IPeggedToken.sol";
import "../interfaces/IPeggedTokenBurnFrom.sol";
import "../libraries/PbPegged.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";

/**
 * @title The bridge contract to mint and burn pegged tokens
 * @dev Work together with OriginalTokenVault deployed at remote chains.
 */
contract PeggedTokenBridgeV2 is Pauser, VolumeControl, DelayedTransfer {
    ISigsVerifier public immutable sigsVerifier;

    mapping(bytes32 => bool) public records;
    mapping(address => uint256) public supplies;

    mapping(address => uint256) public minBurn;
    mapping(address => uint256) public maxBurn;

    event Mint(
        bytes32 mintId,
        address token,
        address account,
        uint256 amount,
        // ref_chain_id defines the reference chain ID, taking values of:
        // 1. The common case: the chain ID on which the remote corresponding deposit or burn happened;
        // 2. Refund for wrong burn: this chain ID on which the burn happened
        uint64 refChainId,
        // ref_id defines a unique reference ID, taking values of:
        // 1. The common case of deposit/burn-mint: the deposit or burn ID on the remote chain;
        // 2. Refund for wrong burn: the burn ID on this chain
        bytes32 refId,
        address depositor
    );
    event Burn(
        bytes32 burnId,
        address token,
        address account,
        uint256 amount,
        uint64 toChainId,
        address toAccount,
        uint64 nonce
    );
    event MinBurnUpdated(address token, uint256 amount);
    event MaxBurnUpdated(address token, uint256 amount);
    event SupplyUpdated(address token, uint256 supply);

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault.
     * @param _request The serialized Mint protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function mint(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external whenNotPaused returns (bytes32) {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Mint"));
        sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
        PbPegged.Mint memory request = PbPegged.decMint(_request);
        bytes32 mintId = keccak256(
            // len = 20 + 20 + 32 + 20 + 8 + 32 + 20 = 152
            abi.encodePacked(
                request.account,
                request.token,
                request.amount,
                request.depositor,
                request.refChainId,
                request.refId,
                address(this)
            )
        );
        require(records[mintId] == false, "record exists");
        records[mintId] = true;
        _updateVolume(request.token, request.amount);
        uint256 delayThreshold = delayThresholds[request.token];
        if (delayThreshold > 0 && request.amount > delayThreshold) {
            _addDelayedTransfer(mintId, request.account, request.token, request.amount);
        } else {
            IPeggedToken(request.token).mint(request.account, request.amount);
        }
        supplies[request.token] += request.amount;
        emit Mint(
            mintId,
            request.token,
            request.account,
            request.amount,
            request.refChainId,
            request.refId,
            request.depositor
        );
        return mintId;
    }

    /**
     * @notice Burn pegged tokens to trigger a cross-chain withdrawal of the original tokens at a remote chain's
     * OriginalTokenVault, or mint at another remote chain
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * @param _token The pegged token address.
     * @param _amount The amount to burn.
     * @param _toChainId If zero, withdraw from original vault; otherwise, the remote chain to mint tokens.
     * @param _toAccount The account to receive tokens on the remote chain
     * @param _nonce A number to guarantee unique depositId. Can be timestamp in practice.
     */
    function burn(
        address _token,
        uint256 _amount,
        uint64 _toChainId,
        address _toAccount,
        uint64 _nonce
    ) external whenNotPaused returns (bytes32) {
        bytes32 burnId = _burn(_token, _amount, _toChainId, _toAccount, _nonce);
        IPeggedToken(_token).burn(msg.sender, _amount);
        return burnId;
    }

    // same with `burn` above, use openzeppelin ERC20Burnable interface
    function burnFrom(
        address _token,
        uint256 _amount,
        uint64 _toChainId,
        address _toAccount,
        uint64 _nonce
    ) external whenNotPaused returns (bytes32) {
        bytes32 burnId = _burn(_token, _amount, _toChainId, _toAccount, _nonce);
        IPeggedTokenBurnFrom(_token).burnFrom(msg.sender, _amount);
        return burnId;
    }

    function _burn(
        address _token,
        uint256 _amount,
        uint64 _toChainId,
        address _toAccount,
        uint64 _nonce
    ) private returns (bytes32) {
        require(_amount > minBurn[_token], "amount too small");
        require(maxBurn[_token] == 0 || _amount <= maxBurn[_token], "amount too large");
        supplies[_token] -= _amount;
        bytes32 burnId = keccak256(
            // len = 20 + 20 + 32 + 8 + 20 + 8 + 8 + 20 = 136
            abi.encodePacked(
                msg.sender,
                _token,
                _amount,
                _toChainId,
                _toAccount,
                _nonce,
                uint64(block.chainid),
                address(this)
            )
        );
        require(records[burnId] == false, "record exists");
        records[burnId] = true;
        emit Burn(burnId, _token, msg.sender, _amount, _toChainId, _toAccount, _nonce);
        return burnId;
    }

    function executeDelayedTransfer(bytes32 id) external whenNotPaused {
        delayedTransfer memory transfer = _executeDelayedTransfer(id);
        IPeggedToken(transfer.token).mint(transfer.receiver, transfer.amount);
    }

    function setMinBurn(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            minBurn[_tokens[i]] = _amounts[i];
            emit MinBurnUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setMaxBurn(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            maxBurn[_tokens[i]] = _amounts[i];
            emit MaxBurnUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setSupply(address _token, uint256 _supply) external onlyOwner {
        supplies[_token] = _supply;
        emit SupplyUpdated(_token, _supply);
    }

    function increaseSupply(address _token, uint256 _delta) external onlyOwner {
        supplies[_token] += _delta;
        emit SupplyUpdated(_token, supplies[_token]);
    }

    function decreaseSupply(address _token, uint256 _delta) external onlyOwner {
        supplies[_token] -= _delta;
        emit SupplyUpdated(_token, supplies[_token]);
    }
}

File 36 of 120 : IPeggedToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IPeggedToken {
    function mint(address _to, uint256 _amount) external;

    function burn(address _from, uint256 _amount) external;
}

File 37 of 120 : IPeggedTokenBurnFrom.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

// used for pegged token with openzeppelin ERC20Burnable interface
// only compatible with PeggedTokenBridgeV2
interface IPeggedTokenBurnFrom {
    function mint(address _to, uint256 _amount) external;

    function burnFrom(address _from, uint256 _amount) external;
}

File 38 of 120 : PbPegged.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/pegged.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbPegged {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct Mint {
        address token; // tag: 1
        address account; // tag: 2
        uint256 amount; // tag: 3
        address depositor; // tag: 4
        uint64 refChainId; // tag: 5
        bytes32 refId; // tag: 6
    } // end struct Mint

    function decMint(bytes memory raw) internal pure returns (Mint memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.token = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.account = Pb._address(buf.decBytes());
            } else if (tag == 3) {
                m.amount = Pb._uint256(buf.decBytes());
            } else if (tag == 4) {
                m.depositor = Pb._address(buf.decBytes());
            } else if (tag == 5) {
                m.refChainId = uint64(buf.decVarint());
            } else if (tag == 6) {
                m.refId = Pb._bytes32(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder Mint

    struct Withdraw {
        address token; // tag: 1
        address receiver; // tag: 2
        uint256 amount; // tag: 3
        address burnAccount; // tag: 4
        uint64 refChainId; // tag: 5
        bytes32 refId; // tag: 6
    } // end struct Withdraw

    function decWithdraw(bytes memory raw) internal pure returns (Withdraw memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.token = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.receiver = Pb._address(buf.decBytes());
            } else if (tag == 3) {
                m.amount = Pb._uint256(buf.decBytes());
            } else if (tag == 4) {
                m.burnAccount = Pb._address(buf.decBytes());
            } else if (tag == 5) {
                m.refChainId = uint64(buf.decVarint());
            } else if (tag == 6) {
                m.refId = Pb._bytes32(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder Withdraw
}

File 39 of 120 : VolumeControl.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "./Governor.sol";

abstract contract VolumeControl is Governor {
    uint256 public epochLength; // seconds
    mapping(address => uint256) public epochVolumes; // key is token
    mapping(address => uint256) public epochVolumeCaps; // key is token
    mapping(address => uint256) public lastOpTimestamps; // key is token

    event EpochLengthUpdated(uint256 length);
    event EpochVolumeUpdated(address token, uint256 cap);

    function setEpochLength(uint256 _length) external onlyGovernor {
        epochLength = _length;
        emit EpochLengthUpdated(_length);
    }

    function setEpochVolumeCaps(address[] calldata _tokens, uint256[] calldata _caps) external onlyGovernor {
        require(_tokens.length == _caps.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            epochVolumeCaps[_tokens[i]] = _caps[i];
            emit EpochVolumeUpdated(_tokens[i], _caps[i]);
        }
    }

    function _updateVolume(address _token, uint256 _amount) internal {
        if (epochLength == 0) {
            return;
        }
        uint256 cap = epochVolumeCaps[_token];
        if (cap == 0) {
            return;
        }
        uint256 volume = epochVolumes[_token];
        uint256 timestamp = block.timestamp;
        uint256 epochStartTime = (timestamp / epochLength) * epochLength;
        if (lastOpTimestamps[_token] < epochStartTime) {
            volume = _amount;
        } else {
            volume += _amount;
        }
        require(volume <= cap, "volume exceeds cap");
        epochVolumes[_token] = volume;
        lastOpTimestamps[_token] = timestamp;
    }
}

File 40 of 120 : DelayedTransfer.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "./Governor.sol";

abstract contract DelayedTransfer is Governor {
    struct delayedTransfer {
        address receiver;
        address token;
        uint256 amount;
        uint256 timestamp;
    }
    mapping(bytes32 => delayedTransfer) public delayedTransfers;
    mapping(address => uint256) public delayThresholds;
    uint256 public delayPeriod; // in seconds

    event DelayedTransferAdded(bytes32 id);
    event DelayedTransferExecuted(bytes32 id, address receiver, address token, uint256 amount);

    event DelayPeriodUpdated(uint256 period);
    event DelayThresholdUpdated(address token, uint256 threshold);

    function setDelayThresholds(address[] calldata _tokens, uint256[] calldata _thresholds) external onlyGovernor {
        require(_tokens.length == _thresholds.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            delayThresholds[_tokens[i]] = _thresholds[i];
            emit DelayThresholdUpdated(_tokens[i], _thresholds[i]);
        }
    }

    function setDelayPeriod(uint256 _period) external onlyGovernor {
        delayPeriod = _period;
        emit DelayPeriodUpdated(_period);
    }

    function _addDelayedTransfer(
        bytes32 id,
        address receiver,
        address token,
        uint256 amount
    ) internal {
        require(delayedTransfers[id].timestamp == 0, "delayed transfer already exists");
        delayedTransfers[id] = delayedTransfer({
            receiver: receiver,
            token: token,
            amount: amount,
            timestamp: block.timestamp
        });
        emit DelayedTransferAdded(id);
    }

    // caller needs to do the actual token transfer
    function _executeDelayedTransfer(bytes32 id) internal returns (delayedTransfer memory) {
        delayedTransfer memory transfer = delayedTransfers[id];
        require(transfer.timestamp > 0, "delayed transfer not exist");
        require(block.timestamp > transfer.timestamp + delayPeriod, "delayed transfer still locked");
        delete delayedTransfers[id];
        emit DelayedTransferExecuted(id, transfer.receiver, transfer.token, transfer.amount);
        return transfer;
    }
}

File 41 of 120 : Governor.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "./Ownable.sol";

abstract contract Governor is Ownable {
    mapping(address => bool) public governors;

    event GovernorAdded(address account);
    event GovernorRemoved(address account);

    modifier onlyGovernor() {
        require(isGovernor(msg.sender), "Caller is not governor");
        _;
    }

    constructor() {
        _addGovernor(msg.sender);
    }

    function isGovernor(address _account) public view returns (bool) {
        return governors[_account];
    }

    function addGovernor(address _account) public onlyOwner {
        _addGovernor(_account);
    }

    function removeGovernor(address _account) public onlyOwner {
        _removeGovernor(_account);
    }

    function renounceGovernor() public {
        _removeGovernor(msg.sender);
    }

    function _addGovernor(address _account) private {
        require(!isGovernor(_account), "Account is already governor");
        governors[_account] = true;
        emit GovernorAdded(_account);
    }

    function _removeGovernor(address _account) private {
        require(isGovernor(_account), "Account is not governor");
        governors[_account] = false;
        emit GovernorRemoved(_account);
    }
}

File 42 of 120 : PeggedTokenBridge.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "../interfaces/ISigsVerifier.sol";
import "../interfaces/IPeggedToken.sol";
import "../libraries/PbPegged.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";

/**
 * @title The bridge contract to mint and burn pegged tokens
 * @dev Work together with OriginalTokenVault deployed at remote chains.
 */
contract PeggedTokenBridge is Pauser, VolumeControl, DelayedTransfer {
    ISigsVerifier public immutable sigsVerifier;

    mapping(bytes32 => bool) public records;

    mapping(address => uint256) public minBurn;
    mapping(address => uint256) public maxBurn;

    event Mint(
        bytes32 mintId,
        address token,
        address account,
        uint256 amount,
        // ref_chain_id defines the reference chain ID, taking values of:
        // 1. The common case: the chain ID on which the remote corresponding deposit or burn happened;
        // 2. Refund for wrong burn: this chain ID on which the burn happened
        uint64 refChainId,
        // ref_id defines a unique reference ID, taking values of:
        // 1. The common case of deposit/burn-mint: the deposit or burn ID on the remote chain;
        // 2. Refund for wrong burn: the burn ID on this chain
        bytes32 refId,
        address depositor
    );
    event Burn(bytes32 burnId, address token, address account, uint256 amount, address withdrawAccount);
    event MinBurnUpdated(address token, uint256 amount);
    event MaxBurnUpdated(address token, uint256 amount);

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault.
     * @param _request The serialized Mint protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function mint(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Mint"));
        sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
        PbPegged.Mint memory request = PbPegged.decMint(_request);
        bytes32 mintId = keccak256(
            // len = 20 + 20 + 32 + 20 + 8 + 32 = 132
            abi.encodePacked(
                request.account,
                request.token,
                request.amount,
                request.depositor,
                request.refChainId,
                request.refId
            )
        );
        require(records[mintId] == false, "record exists");
        records[mintId] = true;
        _updateVolume(request.token, request.amount);
        uint256 delayThreshold = delayThresholds[request.token];
        if (delayThreshold > 0 && request.amount > delayThreshold) {
            _addDelayedTransfer(mintId, request.account, request.token, request.amount);
        } else {
            IPeggedToken(request.token).mint(request.account, request.amount);
        }
        emit Mint(
            mintId,
            request.token,
            request.account,
            request.amount,
            request.refChainId,
            request.refId,
            request.depositor
        );
    }

    /**
     * @notice Burn pegged tokens to trigger a cross-chain withdrawal of the original tokens at a remote chain's
     * OriginalTokenVault.
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * @param _token The pegged token address.
     * @param _amount The amount to burn.
     * @param _withdrawAccount The account to receive the original tokens withdrawn on the remote chain.
     * @param _nonce A number to guarantee unique depositId. Can be timestamp in practice.
     */
    function burn(
        address _token,
        uint256 _amount,
        address _withdrawAccount,
        uint64 _nonce
    ) external whenNotPaused {
        require(_amount > minBurn[_token], "amount too small");
        require(maxBurn[_token] == 0 || _amount <= maxBurn[_token], "amount too large");
        bytes32 burnId = keccak256(
            // len = 20 + 20 + 32 + 20 + 8 + 8 = 108
            abi.encodePacked(msg.sender, _token, _amount, _withdrawAccount, _nonce, uint64(block.chainid))
        );
        require(records[burnId] == false, "record exists");
        records[burnId] = true;
        IPeggedToken(_token).burn(msg.sender, _amount);
        emit Burn(burnId, _token, msg.sender, _amount, _withdrawAccount);
    }

    function executeDelayedTransfer(bytes32 id) external whenNotPaused {
        delayedTransfer memory transfer = _executeDelayedTransfer(id);
        IPeggedToken(transfer.token).mint(transfer.receiver, transfer.amount);
    }

    function setMinBurn(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            minBurn[_tokens[i]] = _amounts[i];
            emit MinBurnUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setMaxBurn(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            maxBurn[_tokens[i]] = _amounts[i];
            emit MaxBurnUpdated(_tokens[i], _amounts[i]);
        }
    }
}

File 43 of 120 : OriginalTokenVaultV2.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/ISigsVerifier.sol";
import "../interfaces/IWETH.sol";
import "../libraries/PbPegged.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";

/**
 * @title the vault to deposit and withdraw original tokens
 * @dev Work together with PeggedTokenBridge contracts deployed at remote chains
 */
contract OriginalTokenVaultV2 is ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {
    using SafeERC20 for IERC20;

    ISigsVerifier public immutable sigsVerifier;

    mapping(bytes32 => bool) public records;

    mapping(address => uint256) public minDeposit;
    mapping(address => uint256) public maxDeposit;

    address public nativeWrap;

    event Deposited(
        bytes32 depositId,
        address depositor,
        address token,
        uint256 amount,
        uint64 mintChainId,
        address mintAccount,
        uint64 nonce
    );
    event Withdrawn(
        bytes32 withdrawId,
        address receiver,
        address token,
        uint256 amount,
        // ref_chain_id defines the reference chain ID, taking values of:
        // 1. The common case of burn-withdraw: the chain ID on which the corresponding burn happened;
        // 2. Pegbridge fee claim: zero / not applicable;
        // 3. Refund for wrong deposit: this chain ID on which the deposit happened
        uint64 refChainId,
        // ref_id defines a unique reference ID, taking values of:
        // 1. The common case of burn-withdraw: the burn ID on the remote chain;
        // 2. Pegbridge fee claim: a per-account nonce;
        // 3. Refund for wrong deposit: the deposit ID on this chain
        bytes32 refId,
        address burnAccount
    );
    event MinDepositUpdated(address token, uint256 amount);
    event MaxDepositUpdated(address token, uint256 amount);

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @notice Lock original tokens to trigger cross-chain mint of pegged tokens at a remote chain's PeggedTokenBridge.
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * @param _token The original token address.
     * @param _amount The amount to deposit.
     * @param _mintChainId The destination chain ID to mint tokens.
     * @param _mintAccount The destination account to receive the minted pegged tokens.
     * @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
     */
    function deposit(
        address _token,
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external nonReentrant whenNotPaused returns (bytes32) {
        bytes32 depId = _deposit(_token, _amount, _mintChainId, _mintAccount, _nonce);
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        emit Deposited(depId, msg.sender, _token, _amount, _mintChainId, _mintAccount, _nonce);
        return depId;
    }

    /**
     * @notice Lock native token as original token to trigger cross-chain mint of pegged tokens at a remote chain's
     * PeggedTokenBridge.
     * @param _amount The amount to deposit.
     * @param _mintChainId The destination chain ID to mint tokens.
     * @param _mintAccount The destination account to receive the minted pegged tokens.
     * @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
     */
    function depositNative(
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external payable nonReentrant whenNotPaused returns (bytes32) {
        require(msg.value == _amount, "Amount mismatch");
        require(nativeWrap != address(0), "Native wrap not set");
        bytes32 depId = _deposit(nativeWrap, _amount, _mintChainId, _mintAccount, _nonce);
        IWETH(nativeWrap).deposit{value: _amount}();
        emit Deposited(depId, msg.sender, nativeWrap, _amount, _mintChainId, _mintAccount, _nonce);
        return depId;
    }

    function _deposit(
        address _token,
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) private returns (bytes32) {
        require(_amount > minDeposit[_token], "amount too small");
        require(maxDeposit[_token] == 0 || _amount <= maxDeposit[_token], "amount too large");
        bytes32 depId = keccak256(
            // len = 20 + 20 + 32 + 8 + 20 + 8 + 8 + 20 = 136
            abi.encodePacked(
                msg.sender,
                _token,
                _amount,
                _mintChainId,
                _mintAccount,
                _nonce,
                uint64(block.chainid),
                address(this)
            )
        );
        require(records[depId] == false, "record exists");
        records[depId] = true;
        return depId;
    }

    /**
     * @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
     * @param _request The serialized Withdraw protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the bridge's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdraw(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external whenNotPaused returns (bytes32) {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Withdraw"));
        sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
        PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
        bytes32 wdId = keccak256(
            // len = 20 + 20 + 32 + 20 + 8 + 32 + 20 = 152
            abi.encodePacked(
                request.receiver,
                request.token,
                request.amount,
                request.burnAccount,
                request.refChainId,
                request.refId,
                address(this)
            )
        );
        require(records[wdId] == false, "record exists");
        records[wdId] = true;
        _updateVolume(request.token, request.amount);
        uint256 delayThreshold = delayThresholds[request.token];
        if (delayThreshold > 0 && request.amount > delayThreshold) {
            _addDelayedTransfer(wdId, request.receiver, request.token, request.amount);
        } else {
            _sendToken(request.receiver, request.token, request.amount);
        }
        emit Withdrawn(
            wdId,
            request.receiver,
            request.token,
            request.amount,
            request.refChainId,
            request.refId,
            request.burnAccount
        );
        return wdId;
    }

    function executeDelayedTransfer(bytes32 id) external whenNotPaused {
        delayedTransfer memory transfer = _executeDelayedTransfer(id);
        _sendToken(transfer.receiver, transfer.token, transfer.amount);
    }

    function setMinDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            minDeposit[_tokens[i]] = _amounts[i];
            emit MinDepositUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setMaxDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            maxDeposit[_tokens[i]] = _amounts[i];
            emit MaxDepositUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setWrap(address _weth) external onlyOwner {
        nativeWrap = _weth;
    }

    function _sendToken(
        address _receiver,
        address _token,
        uint256 _amount
    ) private {
        if (_token == nativeWrap) {
            // withdraw then transfer native to receiver
            IWETH(nativeWrap).withdraw(_amount);
            (bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
            require(sent, "failed to send native token");
        } else {
            IERC20(_token).safeTransfer(_receiver, _amount);
        }
    }

    receive() external payable {}
}

File 44 of 120 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

File 45 of 120 : IWETH.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IWETH {
    function deposit() external payable;

    function withdraw(uint256) external;
}

File 46 of 120 : OriginalTokenVault.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/ISigsVerifier.sol";
import "../interfaces/IWETH.sol";
import "../libraries/PbPegged.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";

/**
 * @title the vault to deposit and withdraw original tokens
 * @dev Work together with PeggedTokenBridge contracts deployed at remote chains
 */
contract OriginalTokenVault is ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {
    using SafeERC20 for IERC20;

    ISigsVerifier public immutable sigsVerifier;

    mapping(bytes32 => bool) public records;

    mapping(address => uint256) public minDeposit;
    mapping(address => uint256) public maxDeposit;

    address public nativeWrap;

    event Deposited(
        bytes32 depositId,
        address depositor,
        address token,
        uint256 amount,
        uint64 mintChainId,
        address mintAccount
    );
    event Withdrawn(
        bytes32 withdrawId,
        address receiver,
        address token,
        uint256 amount,
        // ref_chain_id defines the reference chain ID, taking values of:
        // 1. The common case of burn-withdraw: the chain ID on which the corresponding burn happened;
        // 2. Pegbridge fee claim: zero / not applicable;
        // 3. Refund for wrong deposit: this chain ID on which the deposit happened
        uint64 refChainId,
        // ref_id defines a unique reference ID, taking values of:
        // 1. The common case of burn-withdraw: the burn ID on the remote chain;
        // 2. Pegbridge fee claim: a per-account nonce;
        // 3. Refund for wrong deposit: the deposit ID on this chain
        bytes32 refId,
        address burnAccount
    );
    event MinDepositUpdated(address token, uint256 amount);
    event MaxDepositUpdated(address token, uint256 amount);

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @notice Lock original tokens to trigger cross-chain mint of pegged tokens at a remote chain's PeggedTokenBridge.
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * @param _token The original token address.
     * @param _amount The amount to deposit.
     * @param _mintChainId The destination chain ID to mint tokens.
     * @param _mintAccount The destination account to receive the minted pegged tokens.
     * @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
     */
    function deposit(
        address _token,
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external nonReentrant whenNotPaused {
        bytes32 depId = _deposit(_token, _amount, _mintChainId, _mintAccount, _nonce);
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        emit Deposited(depId, msg.sender, _token, _amount, _mintChainId, _mintAccount);
    }

    /**
     * @notice Lock native token as original token to trigger cross-chain mint of pegged tokens at a remote chain's
     * PeggedTokenBridge.
     * @param _amount The amount to deposit.
     * @param _mintChainId The destination chain ID to mint tokens.
     * @param _mintAccount The destination account to receive the minted pegged tokens.
     * @param _nonce A number input to guarantee unique depositId. Can be timestamp in practice.
     */
    function depositNative(
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external payable nonReentrant whenNotPaused {
        require(msg.value == _amount, "Amount mismatch");
        require(nativeWrap != address(0), "Native wrap not set");
        bytes32 depId = _deposit(nativeWrap, _amount, _mintChainId, _mintAccount, _nonce);
        IWETH(nativeWrap).deposit{value: _amount}();
        emit Deposited(depId, msg.sender, nativeWrap, _amount, _mintChainId, _mintAccount);
    }

    function _deposit(
        address _token,
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) private returns (bytes32) {
        require(_amount > minDeposit[_token], "amount too small");
        require(maxDeposit[_token] == 0 || _amount <= maxDeposit[_token], "amount too large");
        bytes32 depId = keccak256(
            // len = 20 + 20 + 32 + 8 + 20 + 8 + 8 = 116
            abi.encodePacked(msg.sender, _token, _amount, _mintChainId, _mintAccount, _nonce, uint64(block.chainid))
        );
        require(records[depId] == false, "record exists");
        records[depId] = true;
        return depId;
    }

    /**
     * @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
     * @param _request The serialized Withdraw protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the bridge's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdraw(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Withdraw"));
        sigsVerifier.verifySigs(abi.encodePacked(domain, _request), _sigs, _signers, _powers);
        PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
        bytes32 wdId = keccak256(
            // len = 20 + 20 + 32 + 20 + 8 + 32 = 132
            abi.encodePacked(
                request.receiver,
                request.token,
                request.amount,
                request.burnAccount,
                request.refChainId,
                request.refId
            )
        );
        require(records[wdId] == false, "record exists");
        records[wdId] = true;
        _updateVolume(request.token, request.amount);
        uint256 delayThreshold = delayThresholds[request.token];
        if (delayThreshold > 0 && request.amount > delayThreshold) {
            _addDelayedTransfer(wdId, request.receiver, request.token, request.amount);
        } else {
            _sendToken(request.receiver, request.token, request.amount);
        }
        emit Withdrawn(
            wdId,
            request.receiver,
            request.token,
            request.amount,
            request.refChainId,
            request.refId,
            request.burnAccount
        );
    }

    function executeDelayedTransfer(bytes32 id) external whenNotPaused {
        delayedTransfer memory transfer = _executeDelayedTransfer(id);
        _sendToken(transfer.receiver, transfer.token, transfer.amount);
    }

    function setMinDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            minDeposit[_tokens[i]] = _amounts[i];
            emit MinDepositUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setMaxDeposit(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            maxDeposit[_tokens[i]] = _amounts[i];
            emit MaxDepositUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setWrap(address _weth) external onlyOwner {
        nativeWrap = _weth;
    }

    function _sendToken(
        address _receiver,
        address _token,
        uint256 _amount
    ) private {
        if (_token == nativeWrap) {
            // withdraw then transfer native to receiver
            IWETH(nativeWrap).withdraw(_amount);
            (bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
            require(sent, "failed to send native token");
        } else {
            IERC20(_token).safeTransfer(_receiver, _amount);
        }
    }

    receive() external payable {}
}

File 47 of 120 : TransferSwap.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../framework/MessageBusAddress.sol";
import "../framework/MessageSenderApp.sol";
import "../framework/MessageReceiverApp.sol";
import "../../interfaces/IWETH.sol";
import "../../interfaces/IUniswapV2.sol";

/**
 * @title Demo application contract that facilitates swapping on a chain, transferring to another chain,
 * and swapping another time on the destination chain before sending the result tokens to a user
 */
contract TransferSwap is MessageSenderApp, MessageReceiverApp {
    using SafeERC20 for IERC20;

    modifier onlyEOA() {
        require(msg.sender == tx.origin, "Not EOA");
        _;
    }

    struct SwapInfo {
        // if this array has only one element, it means no need to swap
        address[] path;
        // the following fields are only needed if path.length > 1
        address dex; // the DEX to use for the swap
        uint256 deadline; // deadline for the swap
        uint256 minRecvAmt; // minimum receive amount for the swap
    }

    struct SwapRequest {
        SwapInfo swap;
        // the receiving party (the user) of the final output token
        address receiver;
        // this field is best to be per-user per-transaction unique so that
        // a nonce that is specified by the calling party (the user),
        uint64 nonce;
        // indicates whether the output token coming out of the swap on destination
        // chain should be unwrapped before sending to the user
        bool nativeOut;
    }

    enum SwapStatus {
        Null,
        Succeeded,
        Failed,
        Fallback
    }

    // emitted when requested dstChainId == srcChainId, no bridging
    event DirectSwap(
        bytes32 id,
        uint64 srcChainId,
        uint256 amountIn,
        address tokenIn,
        uint256 amountOut,
        address tokenOut
    );
    event SwapRequestSent(bytes32 id, uint64 dstChainId, uint256 srcAmount, address srcToken, address dstToken);
    event SwapRequestDone(bytes32 id, uint256 dstAmount, SwapStatus status);

    mapping(address => uint256) public minSwapAmounts;
    mapping(address => bool) supportedDex;

    // erc20 wrap of gas token of this chain, eg. WETH
    address public nativeWrap;

    constructor(
        address _messageBus,
        address _supportedDex,
        address _nativeWrap
    ) {
        messageBus = _messageBus;
        supportedDex[_supportedDex] = true;
        nativeWrap = _nativeWrap;
    }

    function transferWithSwapNative(
        address _receiver,
        uint256 _amountIn,
        uint64 _dstChainId,
        SwapInfo calldata _srcSwap,
        SwapInfo calldata _dstSwap,
        uint32 _maxBridgeSlippage,
        uint64 _nonce,
        bool _nativeOut
    ) external payable onlyEOA {
        require(msg.value >= _amountIn, "Amount insufficient");
        require(_srcSwap.path[0] == nativeWrap, "token mismatch");
        IWETH(nativeWrap).deposit{value: _amountIn}();
        _transferWithSwap(
            _receiver,
            _amountIn,
            _dstChainId,
            _srcSwap,
            _dstSwap,
            _maxBridgeSlippage,
            _nonce,
            _nativeOut,
            msg.value - _amountIn
        );
    }

    function transferWithSwap(
        address _receiver,
        uint256 _amountIn,
        uint64 _dstChainId,
        SwapInfo calldata _srcSwap,
        SwapInfo calldata _dstSwap,
        uint32 _maxBridgeSlippage,
        uint64 _nonce
    ) external payable onlyEOA {
        IERC20(_srcSwap.path[0]).safeTransferFrom(msg.sender, address(this), _amountIn);
        _transferWithSwap(
            _receiver,
            _amountIn,
            _dstChainId,
            _srcSwap,
            _dstSwap,
            _maxBridgeSlippage,
            _nonce,
            false,
            msg.value
        );
    }

    /**
     * @notice Sends a cross-chain transfer via the liquidity pool-based bridge and sends a message specifying a wanted swap action on the
               destination chain via the message bus
     * @param _receiver the app contract that implements the MessageReceiver abstract contract
     *        NOTE not to be confused with the receiver field in SwapInfo which is an EOA address of a user
     * @param _amountIn the input amount that the user wants to swap and/or bridge
     * @param _dstChainId destination chain ID
     * @param _srcSwap a struct containing swap related requirements
     * @param _dstSwap a struct containing swap related requirements
     * @param _maxBridgeSlippage the max acceptable slippage at bridge, given as percentage in point (pip). Eg. 5000 means 0.5%.
     *        Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the
     *        transfer can be refunded.
     * @param _fee the fee to pay to MessageBus.
     */
    function _transferWithSwap(
        address _receiver,
        uint256 _amountIn,
        uint64 _dstChainId,
        SwapInfo memory _srcSwap,
        SwapInfo memory _dstSwap,
        uint32 _maxBridgeSlippage,
        uint64 _nonce,
        bool _nativeOut,
        uint256 _fee
    ) private {
        require(_srcSwap.path.length > 0, "empty src swap path");
        address srcTokenOut = _srcSwap.path[_srcSwap.path.length - 1];

        require(_amountIn > minSwapAmounts[_srcSwap.path[0]], "amount must be greater than min swap amount");
        uint64 chainId = uint64(block.chainid);
        require(_srcSwap.path.length > 1 || _dstChainId != chainId, "noop is not allowed"); // revert early to save gas

        uint256 srcAmtOut = _amountIn;

        // swap source token for intermediate token on the source DEX
        if (_srcSwap.path.length > 1) {
            bool ok = true;
            (ok, srcAmtOut) = _trySwap(_srcSwap, _amountIn);
            if (!ok) revert("src swap failed");
        }

        if (_dstChainId == chainId) {
            _directSend(_receiver, _amountIn, chainId, _srcSwap, _nonce, srcTokenOut, srcAmtOut);
        } else {
            _crossChainTransferWithSwap(
                _receiver,
                _amountIn,
                chainId,
                _dstChainId,
                _srcSwap,
                _dstSwap,
                _maxBridgeSlippage,
                _nonce,
                _nativeOut,
                _fee,
                srcTokenOut,
                srcAmtOut
            );
        }
    }

    function _directSend(
        address _receiver,
        uint256 _amountIn,
        uint64 _chainId,
        SwapInfo memory _srcSwap,
        uint64 _nonce,
        address srcTokenOut,
        uint256 srcAmtOut
    ) private {
        // no need to bridge, directly send the tokens to user
        IERC20(srcTokenOut).safeTransfer(_receiver, srcAmtOut);
        // use uint64 for chainid to be consistent with other components in the system
        bytes32 id = keccak256(abi.encode(msg.sender, _chainId, _receiver, _nonce, _srcSwap));
        emit DirectSwap(id, _chainId, _amountIn, _srcSwap.path[0], srcAmtOut, srcTokenOut);
    }

    function _crossChainTransferWithSwap(
        address _receiver,
        uint256 _amountIn,
        uint64 _chainId,
        uint64 _dstChainId,
        SwapInfo memory _srcSwap,
        SwapInfo memory _dstSwap,
        uint32 _maxBridgeSlippage,
        uint64 _nonce,
        bool _nativeOut,
        uint256 _fee,
        address srcTokenOut,
        uint256 srcAmtOut
    ) private {
        require(_dstSwap.path.length > 0, "empty dst swap path");
        bytes memory message = abi.encode(
            SwapRequest({swap: _dstSwap, receiver: msg.sender, nonce: _nonce, nativeOut: _nativeOut})
        );
        bytes32 id = _computeSwapRequestId(msg.sender, _chainId, _dstChainId, message);
        // bridge the intermediate token to destination chain along with the message
        // NOTE In production, it's better use a per-user per-transaction nonce so that it's less likely transferId collision
        // would happen at Bridge contract. Currently this nonce is a timestamp supplied by frontend
        sendMessageWithTransfer(
            _receiver,
            srcTokenOut,
            srcAmtOut,
            _dstChainId,
            _nonce,
            _maxBridgeSlippage,
            message,
            MsgDataTypes.BridgeSendType.Liquidity,
            _fee
        );
        emit SwapRequestSent(id, _dstChainId, _amountIn, _srcSwap.path[0], _dstSwap.path[_dstSwap.path.length - 1]);
    }

    /**
     * @notice called by MessageBus when the tokens are checked to be arrived at this contract's address.
               sends the amount received to the receiver. swaps beforehand if swap behavior is defined in message
     * NOTE: if the swap fails, it sends the tokens received directly to the receiver as fallback behavior
     * @param _token the address of the token sent through the bridge
     * @param _amount the amount of tokens received at this contract through the cross-chain bridge
     * @param _srcChainId source chain ID
     * @param _message SwapRequest message that defines the swap behavior on this destination chain
     */
    function executeMessageWithTransfer(
        address, // _sender
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes memory _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        SwapRequest memory m = abi.decode((_message), (SwapRequest));
        require(_token == m.swap.path[0], "bridged token must be the same as the first token in destination swap path");
        bytes32 id = _computeSwapRequestId(m.receiver, _srcChainId, uint64(block.chainid), _message);
        uint256 dstAmount;
        SwapStatus status = SwapStatus.Succeeded;

        if (m.swap.path.length > 1) {
            bool ok = true;
            (ok, dstAmount) = _trySwap(m.swap, _amount);
            if (ok) {
                _sendToken(m.swap.path[m.swap.path.length - 1], dstAmount, m.receiver, m.nativeOut);
                status = SwapStatus.Succeeded;
            } else {
                // handle swap failure, send the received token directly to receiver
                _sendToken(_token, _amount, m.receiver, false);
                dstAmount = _amount;
                status = SwapStatus.Fallback;
            }
        } else {
            // no need to swap, directly send the bridged token to user
            _sendToken(m.swap.path[0], _amount, m.receiver, m.nativeOut);
            dstAmount = _amount;
            status = SwapStatus.Succeeded;
        }
        emit SwapRequestDone(id, dstAmount, status);
        // always return success since swap failure is already handled in-place
        return ExecutionStatus.Success;
    }

    /**
     * @notice called by MessageBus when the executeMessageWithTransfer call fails. does nothing but emitting a "fail" event
     * @param _srcChainId source chain ID
     * @param _message SwapRequest message that defines the swap behavior on this destination chain
     */
    function executeMessageWithTransferFallback(
        address, // _sender
        address, // _token
        uint256, // _amount
        uint64 _srcChainId,
        bytes memory _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        SwapRequest memory m = abi.decode((_message), (SwapRequest));
        bytes32 id = _computeSwapRequestId(m.receiver, _srcChainId, uint64(block.chainid), _message);
        emit SwapRequestDone(id, 0, SwapStatus.Failed);
        // always return fail to mark this transfer as failed since if this function is called then there nothing more
        // we can do in this app as the swap failures are already handled in executeMessageWithTransfer
        return ExecutionStatus.Fail;
    }

    function _trySwap(SwapInfo memory _swap, uint256 _amount) private returns (bool ok, uint256 amountOut) {
        uint256 zero;
        if (!supportedDex[_swap.dex]) {
            return (false, zero);
        }
        IERC20(_swap.path[0]).safeIncreaseAllowance(_swap.dex, _amount);
        try
            IUniswapV2(_swap.dex).swapExactTokensForTokens(
                _amount,
                _swap.minRecvAmt,
                _swap.path,
                address(this),
                _swap.deadline
            )
        returns (uint256[] memory amounts) {
            return (true, amounts[amounts.length - 1]);
        } catch {
            return (false, zero);
        }
    }

    function _sendToken(
        address _token,
        uint256 _amount,
        address _receiver,
        bool _nativeOut
    ) private {
        if (_nativeOut) {
            require(_token == nativeWrap, "token mismatch");
            IWETH(nativeWrap).withdraw(_amount);
            (bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
            require(sent, "failed to send native");
        } else {
            IERC20(_token).safeTransfer(_receiver, _amount);
        }
    }

    function _computeSwapRequestId(
        address _sender,
        uint64 _srcChainId,
        uint64 _dstChainId,
        bytes memory _message
    ) private pure returns (bytes32) {
        return keccak256(abi.encodePacked(_sender, _srcChainId, _dstChainId, _message));
    }

    function setMinSwapAmount(address _token, uint256 _minSwapAmount) external onlyOwner {
        minSwapAmounts[_token] = _minSwapAmount;
    }

    function setSupportedDex(address _dex, bool _enabled) external onlyOwner {
        supportedDex[_dex] = _enabled;
    }

    function setNativeWrap(address _nativeWrap) external onlyOwner {
        nativeWrap = _nativeWrap;
    }

    // This is needed to receive ETH when calling `IWETH.withdraw`
    receive() external payable {}
}

File 48 of 120 : MessageBusAddress.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

import "../../safeguard/Ownable.sol";

abstract contract MessageBusAddress is Ownable {
    event MessageBusUpdated(address messageBus);

    address public messageBus;

    function setMessageBus(address _messageBus) public onlyOwner {
        messageBus = _messageBus;
        emit MessageBusUpdated(messageBus);
    }
}

File 49 of 120 : MessageSenderApp.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

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

import "../libraries/MsgDataTypes.sol";
import "../libraries/MessageSenderLib.sol";
import "../messagebus/MessageBus.sol";
import "./MessageBusAddress.sol";

abstract contract MessageSenderApp is MessageBusAddress {
    using SafeERC20 for IERC20;

    // ============== Utility functions called by apps ==============

    /**
     * @notice Sends a message to a contract on another chain.
     * Sender needs to make sure the uniqueness of the message Id, which is computed as
     * hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message).
     * If messages with the same Id are sent, only one of them will succeed at dst chain.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     * @param _fee The fee amount to pay to MessageBus.
     */
    function sendMessage(
        address _receiver,
        uint64 _dstChainId,
        bytes memory _message,
        uint256 _fee
    ) internal {
        MessageSenderLib.sendMessage(_receiver, _dstChainId, _message, messageBus, _fee);
    }

    /**
     * @notice Sends a message associated with a transfer to a contract on another chain.
     * @param _receiver The address of the destination app contract.
     * @param _token The address of the token to be sent.
     * @param _amount The amount of tokens to be sent.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     *        Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
     *        (100% - max slippage percentage) * amount or the transfer can be refunded.
     *        Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     *        If message is empty, only the token transfer will be sent
     * @param _bridgeSendType One of the {BridgeSendType} enum.
     * @param _fee The fee amount to pay to MessageBus.
     * @return The transfer ID.
     */
    function sendMessageWithTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        bytes memory _message,
        MsgDataTypes.BridgeSendType _bridgeSendType,
        uint256 _fee
    ) internal returns (bytes32) {
        return
            MessageSenderLib.sendMessageWithTransfer(
                _receiver,
                _token,
                _amount,
                _dstChainId,
                _nonce,
                _maxSlippage,
                _message,
                _bridgeSendType,
                messageBus,
                _fee
            );
    }

    /**
     * @notice Sends a token transfer via a bridge.
     * @dev sendMessageWithTransfer with empty message
     * @param _receiver The address of the destination app contract.
     * @param _token The address of the token to be sent.
     * @param _amount The amount of tokens to be sent.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     *        Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
     *        (100% - max slippage percentage) * amount or the transfer can be refunded.
     *        Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}.
     * @param _bridgeSendType One of the {BridgeSendType} enum.
     */
    function sendTokenTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        MsgDataTypes.BridgeSendType _bridgeSendType
    ) internal returns (bytes32) {
        return
            MessageSenderLib.sendMessageWithTransfer(
                _receiver,
                _token,
                _amount,
                _dstChainId,
                _nonce,
                _maxSlippage,
                "", // empty message, which will not trigger sendMessage
                _bridgeSendType,
                messageBus,
                0
            );
    }
}

File 50 of 120 : MessageReceiverApp.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "../interfaces/IMessageReceiverApp.sol";
import "./MessageBusAddress.sol";

abstract contract MessageReceiverApp is IMessageReceiverApp, MessageBusAddress {
    modifier onlyMessageBus() {
        require(msg.sender == messageBus, "caller is not message bus");
        _;
    }

    /**
     * @notice Called by MessageBus (MessageBusReceiver) if the process is originated from MessageBus (MessageBusSender)'s
     *         sendMessageWithTransfer it is only called when the tokens are checked to be arrived at this contract's address.
     * @param _sender The address of the source app contract
     * @param _token The address of the token that comes out of the bridge
     * @param _amount The amount of tokens received at this contract through the cross-chain bridge.
     *        the contract that implements this contract can safely assume that the tokens will arrive before this
     *        function is called.
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransfer(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}

    /**
     * @notice Only called by MessageBus (MessageBusReceiver) if
     *         1. executeMessageWithTransfer reverts, or
     *         2. executeMessageWithTransfer returns ExecutionStatus.Fail
     * @param _sender The address of the source app contract
     * @param _token The address of the token that comes out of the bridge
     * @param _amount The amount of tokens received at this contract through the cross-chain bridge.
     *        the contract that implements this contract can safely assume that the tokens will arrive before this
     *        function is called.
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransferFallback(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}

    /**
     * @notice Called by MessageBus (MessageBusReceiver) to process refund of the original transfer from this contract
     * @param _token The token address of the original transfer
     * @param _amount The amount of the original transfer
     * @param _message The same message associated with the original transfer
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransferRefund(
        address _token,
        uint256 _amount,
        bytes calldata _message,
        address _executor
    ) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}

    /**
     * @notice Called by MessageBus (MessageBusReceiver)
     * @param _sender The address of the source app contract
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessage(
        address _sender,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable virtual override onlyMessageBus returns (ExecutionStatus) {}
}

File 51 of 120 : IUniswapV2.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IUniswapV2 {
    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);

    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);
}

File 52 of 120 : MsgDataTypes.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

library MsgDataTypes {
    // bridge operation type at the sender side (src chain)
    enum BridgeSendType {
        Null,
        Liquidity,
        PegDeposit,
        PegBurn,
        PegV2Deposit,
        PegV2Burn,
        PegV2BurnFrom
    }

    // bridge operation type at the receiver side (dst chain)
    enum TransferType {
        Null,
        LqRelay, // relay through liquidity bridge
        LqWithdraw, // withdraw from liquidity bridge
        PegMint, // mint through pegged token bridge
        PegWithdraw, // withdraw from original token vault
        PegV2Mint, // mint through pegged token bridge v2
        PegV2Withdraw // withdraw from original token vault v2
    }

    enum MsgType {
        MessageWithTransfer,
        MessageOnly
    }

    enum TxStatus {
        Null,
        Success,
        Fail,
        Fallback,
        Pending // transient state within a transaction
    }

    struct TransferInfo {
        TransferType t;
        address sender;
        address receiver;
        address token;
        uint256 amount;
        uint64 wdseq; // only needed for LqWithdraw (refund)
        uint64 srcChainId;
        bytes32 refId;
        bytes32 srcTxHash; // src chain msg tx hash
    }

    struct RouteInfo {
        address sender;
        address receiver;
        uint64 srcChainId;
        bytes32 srcTxHash; // src chain msg tx hash
    }

    struct MsgWithTransferExecutionParams {
        bytes message;
        TransferInfo transfer;
        bytes[] sigs;
        address[] signers;
        uint256[] powers;
    }

    struct BridgeTransferParams {
        bytes request;
        bytes[] sigs;
        address[] signers;
        uint256[] powers;
    }
}

File 53 of 120 : MessageSenderLib.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../../interfaces/IBridge.sol";
import "../../interfaces/IOriginalTokenVault.sol";
import "../../interfaces/IOriginalTokenVaultV2.sol";
import "../../interfaces/IPeggedTokenBridge.sol";
import "../../interfaces/IPeggedTokenBridgeV2.sol";
import "../interfaces/IMessageBus.sol";
import "./MsgDataTypes.sol";

library MessageSenderLib {
    using SafeERC20 for IERC20;

    // ============== Internal library functions called by apps ==============

    /**
     * @notice Sends a message to an app on another chain via MessageBus without an associated transfer.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     * @param _messageBus The address of the MessageBus on this chain.
     * @param _fee The fee amount to pay to MessageBus.
     */
    function sendMessage(
        address _receiver,
        uint64 _dstChainId,
        bytes memory _message,
        address _messageBus,
        uint256 _fee
    ) internal {
        IMessageBus(_messageBus).sendMessage{value: _fee}(_receiver, _dstChainId, _message);
    }

    /**
     * @notice Sends a message to an app on another chain via MessageBus with an associated transfer.
     * @param _receiver The address of the destination app contract.
     * @param _token The address of the token to be sent.
     * @param _amount The amount of tokens to be sent.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     * Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the
     * transfer can be refunded. Only applicable to the {MsgDataTypes.BridgeSendType.Liquidity}.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     * @param _bridgeSendType One of the {MsgDataTypes.BridgeSendType} enum.
     * @param _messageBus The address of the MessageBus on this chain.
     * @param _fee The fee amount to pay to MessageBus.
     * @return The transfer ID.
     */
    function sendMessageWithTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        bytes memory _message,
        MsgDataTypes.BridgeSendType _bridgeSendType,
        address _messageBus,
        uint256 _fee
    ) internal returns (bytes32) {
        (bytes32 transferId, address bridge) = sendTokenTransfer(
            _receiver,
            _token,
            _amount,
            _dstChainId,
            _nonce,
            _maxSlippage,
            _bridgeSendType,
            _messageBus
        );
        if (_message.length > 0) {
            IMessageBus(_messageBus).sendMessageWithTransfer{value: _fee}(
                _receiver,
                _dstChainId,
                bridge,
                transferId,
                _message
            );
        }
        return transferId;
    }

    /**
     * @notice Sends a token transfer via a bridge.
     * @param _receiver The address of the destination app contract.
     * @param _token The address of the token to be sent.
     * @param _amount The amount of tokens to be sent.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     * Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the
     * transfer can be refunded.
     * @param _bridgeSendType One of the {MsgDataTypes.BridgeSendType} enum.
     */
    function sendTokenTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage,
        MsgDataTypes.BridgeSendType _bridgeSendType,
        address _messageBus
    ) internal returns (bytes32 transferId, address bridge) {
        if (_bridgeSendType == MsgDataTypes.BridgeSendType.Liquidity) {
            bridge = IMessageBus(_messageBus).liquidityBridge();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            IBridge(bridge).send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
            transferId = computeLiqBridgeTransferId(_receiver, _token, _amount, _dstChainId, _nonce);
        } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegDeposit) {
            bridge = IMessageBus(_messageBus).pegVault();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            IOriginalTokenVault(bridge).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
            transferId = computePegV1DepositId(_receiver, _token, _amount, _dstChainId, _nonce);
        } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegBurn) {
            bridge = IMessageBus(_messageBus).pegBridge();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            IPeggedTokenBridge(bridge).burn(_token, _amount, _receiver, _nonce);
            // handle cases where certain tokens do not spend allowance for role-based burn
            IERC20(_token).safeApprove(bridge, 0);
            transferId = computePegV1BurnId(_receiver, _token, _amount, _nonce);
        } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2Deposit) {
            bridge = IMessageBus(_messageBus).pegVaultV2();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            transferId = IOriginalTokenVaultV2(bridge).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
        } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2Burn) {
            bridge = IMessageBus(_messageBus).pegBridgeV2();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            transferId = IPeggedTokenBridgeV2(bridge).burn(_token, _amount, _dstChainId, _receiver, _nonce);
            // handle cases where certain tokens do not spend allowance for role-based burn
            IERC20(_token).safeApprove(bridge, 0);
        } else if (_bridgeSendType == MsgDataTypes.BridgeSendType.PegV2BurnFrom) {
            bridge = IMessageBus(_messageBus).pegBridgeV2();
            IERC20(_token).safeIncreaseAllowance(bridge, _amount);
            transferId = IPeggedTokenBridgeV2(bridge).burnFrom(_token, _amount, _dstChainId, _receiver, _nonce);
            // handle cases where certain tokens do not spend allowance for role-based burn
            IERC20(_token).safeApprove(bridge, 0);
        } else {
            revert("bridge type not supported");
        }
    }

    function computeLiqBridgeTransferId(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce
    ) internal view returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(address(this), _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid))
            );
    }

    function computePegV1DepositId(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce
    ) internal view returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(address(this), _token, _amount, _dstChainId, _receiver, _nonce, uint64(block.chainid))
            );
    }

    function computePegV1BurnId(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _nonce
    ) internal view returns (bytes32) {
        return keccak256(abi.encodePacked(address(this), _token, _amount, _receiver, _nonce, uint64(block.chainid)));
    }
}

File 54 of 120 : MessageBus.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "./MessageBusSender.sol";
import "./MessageBusReceiver.sol";

contract MessageBus is MessageBusSender, MessageBusReceiver {
    constructor(
        ISigsVerifier _sigsVerifier,
        address _liquidityBridge,
        address _pegBridge,
        address _pegVault,
        address _pegBridgeV2,
        address _pegVaultV2
    )
        MessageBusSender(_sigsVerifier)
        MessageBusReceiver(_liquidityBridge, _pegBridge, _pegVault, _pegBridgeV2, _pegVaultV2)
    {}

    // this is only to be called by Proxy via delegateCall as initOwner will require _owner is 0.
    // so calling init on this contract directly will guarantee to fail
    function init(
        address _liquidityBridge,
        address _pegBridge,
        address _pegVault,
        address _pegBridgeV2,
        address _pegVaultV2
    ) external {
        // MUST manually call ownable init and must only call once
        initOwner();
        // we don't need sender init as _sigsVerifier is immutable so already in the deployed code
        initReceiver(_liquidityBridge, _pegBridge, _pegVault, _pegBridgeV2, _pegVaultV2);
    }
}

File 55 of 120 : IBridge.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IBridge {
    function send(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage
    ) external;

    function relay(
        bytes calldata _relayRequest,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;

    function transfers(bytes32 transferId) external view returns (bool);

    function withdraws(bytes32 withdrawId) external view returns (bool);

    function withdraw(
        bytes calldata _wdmsg,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;

    /**
     * @notice Verifies that a message is signed by a quorum among the signers.
     * @param _msg signed message
     * @param _sigs list of signatures sorted by signer addresses in ascending order
     * @param _signers sorted list of current signers
     * @param _powers powers of current signers
     */
    function verifySigs(
        bytes memory _msg,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external view;
}

File 56 of 120 : IOriginalTokenVault.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IOriginalTokenVault {
    /**
     * @notice Lock original tokens to trigger mint at a remote chain's PeggedTokenBridge
     * @param _token local token address
     * @param _amount locked token amount
     * @param _mintChainId destination chainId to mint tokens
     * @param _mintAccount destination account to receive minted tokens
     * @param _nonce user input to guarantee unique depositId
     */
    function deposit(
        address _token,
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external;

    /**
     * @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
     * @param _request The serialized Withdraw protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the bridge's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdraw(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;

    function records(bytes32 recordId) external view returns (bool);
}

File 57 of 120 : IOriginalTokenVaultV2.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IOriginalTokenVaultV2 {
    /**
     * @notice Lock original tokens to trigger mint at a remote chain's PeggedTokenBridge
     * @param _token local token address
     * @param _amount locked token amount
     * @param _mintChainId destination chainId to mint tokens
     * @param _mintAccount destination account to receive minted tokens
     * @param _nonce user input to guarantee unique depositId
     */
    function deposit(
        address _token,
        uint256 _amount,
        uint64 _mintChainId,
        address _mintAccount,
        uint64 _nonce
    ) external returns (bytes32);

    /**
     * @notice Withdraw locked original tokens triggered by a burn at a remote chain's PeggedTokenBridge.
     * @param _request The serialized Withdraw protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the bridge's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdraw(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external returns (bytes32);

    function records(bytes32 recordId) external view returns (bool);
}

File 58 of 120 : IPeggedTokenBridge.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IPeggedTokenBridge {
    /**
     * @notice Burn tokens to trigger withdrawal at a remote chain's OriginalTokenVault
     * @param _token local token address
     * @param _amount locked token amount
     * @param _withdrawAccount account who withdraw original tokens on the remote chain
     * @param _nonce user input to guarantee unique depositId
     */
    function burn(
        address _token,
        uint256 _amount,
        address _withdrawAccount,
        uint64 _nonce
    ) external;

    /**
     * @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault.
     * @param _request The serialized Mint protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function mint(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;

    function records(bytes32 recordId) external view returns (bool);
}

File 59 of 120 : IPeggedTokenBridgeV2.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IPeggedTokenBridgeV2 {
    /**
     * @notice Burn pegged tokens to trigger a cross-chain withdrawal of the original tokens at a remote chain's
     * OriginalTokenVault, or mint at another remote chain
     * @param _token The pegged token address.
     * @param _amount The amount to burn.
     * @param _toChainId If zero, withdraw from original vault; otherwise, the remote chain to mint tokens.
     * @param _toAccount The account to receive tokens on the remote chain
     * @param _nonce A number to guarantee unique depositId. Can be timestamp in practice.
     */
    function burn(
        address _token,
        uint256 _amount,
        uint64 _toChainId,
        address _toAccount,
        uint64 _nonce
    ) external returns (bytes32);

    // same with `burn` above, use openzeppelin ERC20Burnable interface
    function burnFrom(
        address _token,
        uint256 _amount,
        uint64 _toChainId,
        address _toAccount,
        uint64 _nonce
    ) external returns (bytes32);

    /**
     * @notice Mint tokens triggered by deposit at a remote chain's OriginalTokenVault.
     * @param _request The serialized Mint protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function mint(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external returns (bytes32);

    function records(bytes32 recordId) external view returns (bool);
}

File 60 of 120 : IMessageBus.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

import "../libraries/MsgDataTypes.sol";

interface IMessageBus {
    function liquidityBridge() external view returns (address);

    function pegBridge() external view returns (address);

    function pegBridgeV2() external view returns (address);

    function pegVault() external view returns (address);

    function pegVaultV2() external view returns (address);

    /**
     * @notice Calculates the required fee for the message.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     @ @return The required fee.
     */
    function calcFee(bytes calldata _message) external view returns (uint256);

    /**
     * @notice Sends a message to a contract on another chain.
     * Sender needs to make sure the uniqueness of the message Id, which is computed as
     * hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message).
     * If messages with the same Id are sent, only one of them will succeed at dst chain..
     * A fee is charged in the native gas token.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     */
    function sendMessage(
        address _receiver,
        uint256 _dstChainId,
        bytes calldata _message
    ) external payable;

    /**
     * @notice Sends a message associated with a transfer to a contract on another chain.
     * If messages with the same srcTransferId are sent, only one of them will succeed at dst chain..
     * A fee is charged in the native token.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _srcBridge The bridge contract to send the transfer with.
     * @param _srcTransferId The transfer ID.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     */
    function sendMessageWithTransfer(
        address _receiver,
        uint256 _dstChainId,
        address _srcBridge,
        bytes32 _srcTransferId,
        bytes calldata _message
    ) external payable;

    /**
     * @notice Withdraws message fee in the form of native gas token.
     * @param _account The address receiving the fee.
     * @param _cumulativeFee The cumulative fee credited to the account. Tracked by SGN.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal must be
     * signed-off by +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdrawFee(
        address _account,
        uint256 _cumulativeFee,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;

    /**
     * @notice Execute a message with a successful transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _transfer The transfer info.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessageWithTransfer(
        bytes calldata _message,
        MsgDataTypes.TransferInfo calldata _transfer,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable;

    /**
     * @notice Execute a message with a refunded transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _transfer The transfer info.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessageWithTransferRefund(
        bytes calldata _message, // the same message associated with the original transfer
        MsgDataTypes.TransferInfo calldata _transfer,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable;

    /**
     * @notice Execute a message not associated with a transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessage(
        bytes calldata _message,
        MsgDataTypes.RouteInfo calldata _route,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable;
}

File 61 of 120 : MessageBusSender.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "../../safeguard/Ownable.sol";
import "../../interfaces/ISigsVerifier.sol";

contract MessageBusSender is Ownable {
    ISigsVerifier public immutable sigsVerifier;

    uint256 public feeBase;
    uint256 public feePerByte;
    mapping(address => uint256) public withdrawnFees;

    event Message(address indexed sender, address receiver, uint256 dstChainId, bytes message, uint256 fee);

    event MessageWithTransfer(
        address indexed sender,
        address receiver,
        uint256 dstChainId,
        address bridge,
        bytes32 srcTransferId,
        bytes message,
        uint256 fee
    );

    event FeeBaseUpdated(uint256 feeBase);
    event FeePerByteUpdated(uint256 feePerByte);

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @notice Sends a message to a contract on another chain.
     * Sender needs to make sure the uniqueness of the message Id, which is computed as
     * hash(type.MessageOnly, sender, receiver, srcChainId, srcTxHash, dstChainId, message).
     * If messages with the same Id are sent, only one of them will succeed at dst chain.
     * A fee is charged in the native gas token.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     */
    function sendMessage(
        address _receiver,
        uint256 _dstChainId,
        bytes calldata _message
    ) external payable {
        require(_dstChainId != block.chainid, "Invalid chainId");
        uint256 minFee = calcFee(_message);
        require(msg.value >= minFee, "Insufficient fee");
        emit Message(msg.sender, _receiver, _dstChainId, _message, msg.value);
    }

    /**
     * @notice Sends a message associated with a transfer to a contract on another chain.
     * If messages with the same srcTransferId are sent, only one of them will succeed.
     * A fee is charged in the native token.
     * @param _receiver The address of the destination app contract.
     * @param _dstChainId The destination chain ID.
     * @param _srcBridge The bridge contract to send the transfer with.
     * @param _srcTransferId The transfer ID.
     * @param _dstChainId The destination chain ID.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     */
    function sendMessageWithTransfer(
        address _receiver,
        uint256 _dstChainId,
        address _srcBridge,
        bytes32 _srcTransferId,
        bytes calldata _message
    ) external payable {
        require(_dstChainId != block.chainid, "Invalid chainId");
        uint256 minFee = calcFee(_message);
        require(msg.value >= minFee, "Insufficient fee");
        // SGN needs to verify
        // 1. msg.sender matches sender of the src transfer
        // 2. dstChainId matches dstChainId of the src transfer
        // 3. bridge is either liquidity bridge, peg src vault, or peg dst bridge
        emit MessageWithTransfer(msg.sender, _receiver, _dstChainId, _srcBridge, _srcTransferId, _message, msg.value);
    }

    /**
     * @notice Withdraws message fee in the form of native gas token.
     * @param _account The address receiving the fee.
     * @param _cumulativeFee The cumulative fee credited to the account. Tracked by SGN.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal must be
     * signed-off by +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdrawFee(
        address _account,
        uint256 _cumulativeFee,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "withdrawFee"));
        sigsVerifier.verifySigs(abi.encodePacked(domain, _account, _cumulativeFee), _sigs, _signers, _powers);
        uint256 amount = _cumulativeFee - withdrawnFees[_account];
        require(amount > 0, "No new amount to withdraw");
        withdrawnFees[_account] = _cumulativeFee;
        (bool sent, ) = _account.call{value: amount, gas: 50000}("");
        require(sent, "failed to withdraw fee");
    }

    /**
     * @notice Calculates the required fee for the message.
     * @param _message Arbitrary message bytes to be decoded by the destination app contract.
     @ @return The required fee.
     */
    function calcFee(bytes calldata _message) public view returns (uint256) {
        return feeBase + _message.length * feePerByte;
    }

    // -------------------- Admin --------------------

    function setFeePerByte(uint256 _fee) external onlyOwner {
        feePerByte = _fee;
        emit FeePerByteUpdated(feePerByte);
    }

    function setFeeBase(uint256 _fee) external onlyOwner {
        feeBase = _fee;
        emit FeeBaseUpdated(feeBase);
    }
}

File 62 of 120 : MessageBusReceiver.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "../libraries/MsgDataTypes.sol";
import "../interfaces/IMessageReceiverApp.sol";
import "../interfaces/IMessageBus.sol";
import "../../interfaces/IBridge.sol";
import "../../interfaces/IOriginalTokenVault.sol";
import "../../interfaces/IOriginalTokenVaultV2.sol";
import "../../interfaces/IPeggedTokenBridge.sol";
import "../../interfaces/IPeggedTokenBridgeV2.sol";
import "../../safeguard/Ownable.sol";

contract MessageBusReceiver is Ownable {
    mapping(bytes32 => MsgDataTypes.TxStatus) public executedMessages;

    address public liquidityBridge; // liquidity bridge address
    address public pegBridge; // peg bridge address
    address public pegVault; // peg original vault address
    address public pegBridgeV2; // peg bridge address
    address public pegVaultV2; // peg original vault address

    // minimum amount of gas needed by this contract before it tries to
    // deliver a message to the target contract.
    uint256 public preExecuteMessageGasUsage;

    event Executed(
        MsgDataTypes.MsgType msgType,
        bytes32 msgId,
        MsgDataTypes.TxStatus status,
        address indexed receiver,
        uint64 srcChainId,
        bytes32 srcTxHash
    );
    event NeedRetry(MsgDataTypes.MsgType msgType, bytes32 msgId, uint64 srcChainId, bytes32 srcTxHash);
    event CallReverted(string reason); // help debug

    event LiquidityBridgeUpdated(address liquidityBridge);
    event PegBridgeUpdated(address pegBridge);
    event PegVaultUpdated(address pegVault);
    event PegBridgeV2Updated(address pegBridgeV2);
    event PegVaultV2Updated(address pegVaultV2);

    constructor(
        address _liquidityBridge,
        address _pegBridge,
        address _pegVault,
        address _pegBridgeV2,
        address _pegVaultV2
    ) {
        liquidityBridge = _liquidityBridge;
        pegBridge = _pegBridge;
        pegVault = _pegVault;
        pegBridgeV2 = _pegBridgeV2;
        pegVaultV2 = _pegVaultV2;
    }

    function initReceiver(
        address _liquidityBridge,
        address _pegBridge,
        address _pegVault,
        address _pegBridgeV2,
        address _pegVaultV2
    ) internal {
        require(liquidityBridge == address(0), "liquidityBridge already set");
        liquidityBridge = _liquidityBridge;
        pegBridge = _pegBridge;
        pegVault = _pegVault;
        pegBridgeV2 = _pegBridgeV2;
        pegVaultV2 = _pegVaultV2;
    }

    // ============== functions called by executor ==============

    /**
     * @notice Execute a message with a successful transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _transfer The transfer info.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessageWithTransfer(
        bytes calldata _message,
        MsgDataTypes.TransferInfo calldata _transfer,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) public payable {
        // For message with token transfer, message Id is computed through transfer info
        // in order to guarantee that each transfer can only be used once.
        bytes32 messageId = verifyTransfer(_transfer);
        require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "transfer already executed");
        executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;

        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "MessageWithTransfer"));
        IBridge(liquidityBridge).verifySigs(
            abi.encodePacked(domain, messageId, _message, _transfer.srcTxHash),
            _sigs,
            _signers,
            _powers
        );
        MsgDataTypes.TxStatus status;
        IMessageReceiverApp.ExecutionStatus est = executeMessageWithTransfer(_transfer, _message);
        if (est == IMessageReceiverApp.ExecutionStatus.Success) {
            status = MsgDataTypes.TxStatus.Success;
        } else if (est == IMessageReceiverApp.ExecutionStatus.Retry) {
            executedMessages[messageId] = MsgDataTypes.TxStatus.Null;
            emit NeedRetry(
                MsgDataTypes.MsgType.MessageWithTransfer,
                messageId,
                _transfer.srcChainId,
                _transfer.srcTxHash
            );
            return;
        } else {
            est = executeMessageWithTransferFallback(_transfer, _message);
            if (est == IMessageReceiverApp.ExecutionStatus.Success) {
                status = MsgDataTypes.TxStatus.Fallback;
            } else {
                status = MsgDataTypes.TxStatus.Fail;
            }
        }
        executedMessages[messageId] = status;
        emitMessageWithTransferExecutedEvent(messageId, status, _transfer);
    }

    /**
     * @notice Execute a message with a refunded transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _transfer The transfer info.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessageWithTransferRefund(
        bytes calldata _message, // the same message associated with the original transfer
        MsgDataTypes.TransferInfo calldata _transfer,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) public payable {
        // similar to executeMessageWithTransfer
        bytes32 messageId = verifyTransfer(_transfer);
        require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "transfer already executed");
        executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;

        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "MessageWithTransferRefund"));
        IBridge(liquidityBridge).verifySigs(
            abi.encodePacked(domain, messageId, _message, _transfer.srcTxHash),
            _sigs,
            _signers,
            _powers
        );
        MsgDataTypes.TxStatus status;
        IMessageReceiverApp.ExecutionStatus est = executeMessageWithTransferRefund(_transfer, _message);
        if (est == IMessageReceiverApp.ExecutionStatus.Success) {
            status = MsgDataTypes.TxStatus.Success;
        } else if (est == IMessageReceiverApp.ExecutionStatus.Retry) {
            executedMessages[messageId] = MsgDataTypes.TxStatus.Null;
            emit NeedRetry(
                MsgDataTypes.MsgType.MessageWithTransfer,
                messageId,
                _transfer.srcChainId,
                _transfer.srcTxHash
            );
            return;
        } else {
            status = MsgDataTypes.TxStatus.Fail;
        }
        executedMessages[messageId] = status;
        emitMessageWithTransferExecutedEvent(messageId, status, _transfer);
    }

    /**
     * @notice Execute a message not associated with a transfer.
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _route The info about the sender and the receiver.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the sigsVerifier's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function executeMessage(
        bytes calldata _message,
        MsgDataTypes.RouteInfo calldata _route,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external payable {
        // For message without associated token transfer, message Id is computed through message info,
        // in order to guarantee that each message can only be applied once
        bytes32 messageId = computeMessageOnlyId(_route, _message);
        require(executedMessages[messageId] == MsgDataTypes.TxStatus.Null, "message already executed");
        executedMessages[messageId] = MsgDataTypes.TxStatus.Pending;

        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Message"));
        IBridge(liquidityBridge).verifySigs(abi.encodePacked(domain, messageId), _sigs, _signers, _powers);
        MsgDataTypes.TxStatus status;
        IMessageReceiverApp.ExecutionStatus est = executeMessage(_route, _message);
        if (est == IMessageReceiverApp.ExecutionStatus.Success) {
            status = MsgDataTypes.TxStatus.Success;
        } else if (est == IMessageReceiverApp.ExecutionStatus.Retry) {
            executedMessages[messageId] = MsgDataTypes.TxStatus.Null;
            emit NeedRetry(MsgDataTypes.MsgType.MessageOnly, messageId, _route.srcChainId, _route.srcTxHash);
            return;
        } else {
            status = MsgDataTypes.TxStatus.Fail;
        }
        executedMessages[messageId] = status;
        emitMessageOnlyExecutedEvent(messageId, status, _route);
    }

    // ================= utils (to avoid stack too deep) =================

    function emitMessageWithTransferExecutedEvent(
        bytes32 _messageId,
        MsgDataTypes.TxStatus _status,
        MsgDataTypes.TransferInfo calldata _transfer
    ) private {
        emit Executed(
            MsgDataTypes.MsgType.MessageWithTransfer,
            _messageId,
            _status,
            _transfer.receiver,
            _transfer.srcChainId,
            _transfer.srcTxHash
        );
    }

    function emitMessageOnlyExecutedEvent(
        bytes32 _messageId,
        MsgDataTypes.TxStatus _status,
        MsgDataTypes.RouteInfo calldata _route
    ) private {
        emit Executed(
            MsgDataTypes.MsgType.MessageOnly,
            _messageId,
            _status,
            _route.receiver,
            _route.srcChainId,
            _route.srcTxHash
        );
    }

    function executeMessageWithTransfer(MsgDataTypes.TransferInfo calldata _transfer, bytes calldata _message)
        private
        returns (IMessageReceiverApp.ExecutionStatus)
    {
        uint256 gasLeftBeforeExecution = gasleft();
        (bool ok, bytes memory res) = address(_transfer.receiver).call{value: msg.value}(
            abi.encodeWithSelector(
                IMessageReceiverApp.executeMessageWithTransfer.selector,
                _transfer.sender,
                _transfer.token,
                _transfer.amount,
                _transfer.srcChainId,
                _message,
                msg.sender
            )
        );
        if (ok) {
            return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
        }
        handleExecutionRevert(gasLeftBeforeExecution, res);
        return IMessageReceiverApp.ExecutionStatus.Fail;
    }

    function executeMessageWithTransferFallback(MsgDataTypes.TransferInfo calldata _transfer, bytes calldata _message)
        private
        returns (IMessageReceiverApp.ExecutionStatus)
    {
        uint256 gasLeftBeforeExecution = gasleft();
        (bool ok, bytes memory res) = address(_transfer.receiver).call{value: msg.value}(
            abi.encodeWithSelector(
                IMessageReceiverApp.executeMessageWithTransferFallback.selector,
                _transfer.sender,
                _transfer.token,
                _transfer.amount,
                _transfer.srcChainId,
                _message,
                msg.sender
            )
        );
        if (ok) {
            return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
        }
        handleExecutionRevert(gasLeftBeforeExecution, res);
        return IMessageReceiverApp.ExecutionStatus.Fail;
    }

    function executeMessageWithTransferRefund(MsgDataTypes.TransferInfo calldata _transfer, bytes calldata _message)
        private
        returns (IMessageReceiverApp.ExecutionStatus)
    {
        uint256 gasLeftBeforeExecution = gasleft();
        (bool ok, bytes memory res) = address(_transfer.receiver).call{value: msg.value}(
            abi.encodeWithSelector(
                IMessageReceiverApp.executeMessageWithTransferRefund.selector,
                _transfer.token,
                _transfer.amount,
                _message,
                msg.sender
            )
        );
        if (ok) {
            return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
        }
        handleExecutionRevert(gasLeftBeforeExecution, res);
        return IMessageReceiverApp.ExecutionStatus.Fail;
    }

    function verifyTransfer(MsgDataTypes.TransferInfo calldata _transfer) private view returns (bytes32) {
        bytes32 transferId;
        address bridgeAddr;
        if (_transfer.t == MsgDataTypes.TransferType.LqRelay) {
            transferId = keccak256(
                abi.encodePacked(
                    _transfer.sender,
                    _transfer.receiver,
                    _transfer.token,
                    _transfer.amount,
                    _transfer.srcChainId,
                    uint64(block.chainid),
                    _transfer.refId
                )
            );
            bridgeAddr = liquidityBridge;
            require(IBridge(bridgeAddr).transfers(transferId) == true, "bridge relay not exist");
        } else if (_transfer.t == MsgDataTypes.TransferType.LqWithdraw) {
            transferId = keccak256(
                abi.encodePacked(
                    uint64(block.chainid),
                    _transfer.wdseq,
                    _transfer.receiver,
                    _transfer.token,
                    _transfer.amount
                )
            );
            bridgeAddr = liquidityBridge;
            require(IBridge(bridgeAddr).withdraws(transferId) == true, "bridge withdraw not exist");
        } else if (
            _transfer.t == MsgDataTypes.TransferType.PegMint || _transfer.t == MsgDataTypes.TransferType.PegWithdraw
        ) {
            transferId = keccak256(
                abi.encodePacked(
                    _transfer.receiver,
                    _transfer.token,
                    _transfer.amount,
                    _transfer.sender,
                    _transfer.srcChainId,
                    _transfer.refId
                )
            );
            if (_transfer.t == MsgDataTypes.TransferType.PegMint) {
                bridgeAddr = pegBridge;
                require(IPeggedTokenBridge(bridgeAddr).records(transferId) == true, "mint record not exist");
            } else {
                // _transfer.t == MsgDataTypes.TransferType.PegWithdraw
                bridgeAddr = pegVault;
                require(IOriginalTokenVault(bridgeAddr).records(transferId) == true, "withdraw record not exist");
            }
        } else if (
            _transfer.t == MsgDataTypes.TransferType.PegV2Mint || _transfer.t == MsgDataTypes.TransferType.PegV2Withdraw
        ) {
            if (_transfer.t == MsgDataTypes.TransferType.PegV2Mint) {
                bridgeAddr = pegBridgeV2;
            } else {
                // MsgDataTypes.TransferType.PegV2Withdraw
                bridgeAddr = pegVaultV2;
            }
            transferId = keccak256(
                abi.encodePacked(
                    _transfer.receiver,
                    _transfer.token,
                    _transfer.amount,
                    _transfer.sender,
                    _transfer.srcChainId,
                    _transfer.refId,
                    bridgeAddr
                )
            );
            if (_transfer.t == MsgDataTypes.TransferType.PegV2Mint) {
                require(IPeggedTokenBridgeV2(bridgeAddr).records(transferId) == true, "mint record not exist");
            } else {
                // MsgDataTypes.TransferType.PegV2Withdraw
                require(IOriginalTokenVaultV2(bridgeAddr).records(transferId) == true, "withdraw record not exist");
            }
        }
        return keccak256(abi.encodePacked(MsgDataTypes.MsgType.MessageWithTransfer, bridgeAddr, transferId));
    }

    function computeMessageOnlyId(MsgDataTypes.RouteInfo calldata _route, bytes calldata _message)
        private
        view
        returns (bytes32)
    {
        return
            keccak256(
                abi.encodePacked(
                    MsgDataTypes.MsgType.MessageOnly,
                    _route.sender,
                    _route.receiver,
                    _route.srcChainId,
                    _route.srcTxHash,
                    uint64(block.chainid),
                    _message
                )
            );
    }

    function executeMessage(MsgDataTypes.RouteInfo calldata _route, bytes calldata _message)
        private
        returns (IMessageReceiverApp.ExecutionStatus)
    {
        uint256 gasLeftBeforeExecution = gasleft();
        (bool ok, bytes memory res) = address(_route.receiver).call{value: msg.value}(
            abi.encodeWithSelector(
                IMessageReceiverApp.executeMessage.selector,
                _route.sender,
                _route.srcChainId,
                _message,
                msg.sender
            )
        );
        if (ok) {
            return abi.decode((res), (IMessageReceiverApp.ExecutionStatus));
        }
        handleExecutionRevert(gasLeftBeforeExecution, res);
        return IMessageReceiverApp.ExecutionStatus.Fail;
    }

    function handleExecutionRevert(uint256 _gasLeftBeforeExecution, bytes memory _returnData) private {
        uint256 gasLeftAfterExecution = gasleft();
        uint256 maxTargetGasLimit = block.gaslimit - preExecuteMessageGasUsage;
        if (_gasLeftBeforeExecution < maxTargetGasLimit && gasLeftAfterExecution <= _gasLeftBeforeExecution / 64) {
            // if this happens, the executor must have not provided sufficient gas limit,
            // then the tx should revert instead of recording a non-retryable failure status
            // https://github.com/wolflo/evm-opcodes/blob/main/gas.md#aa-f-gas-to-send-with-call-operations
            assembly {
                invalid()
            }
        }
        emit CallReverted(getRevertMsg(_returnData));
    }

    // https://ethereum.stackexchange.com/a/83577
    // https://github.com/Uniswap/v3-periphery/blob/v1.0.0/contracts/base/Multicall.sol
    function getRevertMsg(bytes memory _returnData) private pure returns (string memory) {
        // If the _res length is less than 68, then the transaction failed silently (without a revert message)
        if (_returnData.length < 68) return "Transaction reverted silently";
        assembly {
            // Slice the sighash.
            _returnData := add(_returnData, 0x04)
        }
        return abi.decode(_returnData, (string)); // All that remains is the revert string
    }

    // ================= helper functions =====================

    /**
     * @notice combine bridge transfer and msg execution calls into a single tx
     * @dev caller needs to get the required input params from SGN
     * @param _transferParams params to call bridge transfer
     * @param _msgParams params to execute message
     */
    function transferAndExecuteMsg(
        MsgDataTypes.BridgeTransferParams calldata _transferParams,
        MsgDataTypes.MsgWithTransferExecutionParams calldata _msgParams
    ) external {
        _bridgeTransfer(_msgParams.transfer.t, _transferParams);
        executeMessageWithTransfer(
            _msgParams.message,
            _msgParams.transfer,
            _msgParams.sigs,
            _msgParams.signers,
            _msgParams.powers
        );
    }

    /**
     * @notice combine bridge refund and msg execution calls into a single tx
     * @dev caller needs to get the required input params from SGN
     * @param _transferParams params to call bridge transfer for refund
     * @param _msgParams params to execute message for refund
     */
    function refundAndExecuteMsg(
        MsgDataTypes.BridgeTransferParams calldata _transferParams,
        MsgDataTypes.MsgWithTransferExecutionParams calldata _msgParams
    ) external {
        _bridgeTransfer(_msgParams.transfer.t, _transferParams);
        executeMessageWithTransferRefund(
            _msgParams.message,
            _msgParams.transfer,
            _msgParams.sigs,
            _msgParams.signers,
            _msgParams.powers
        );
    }

    function _bridgeTransfer(MsgDataTypes.TransferType t, MsgDataTypes.BridgeTransferParams calldata _transferParams)
        private
    {
        if (t == MsgDataTypes.TransferType.LqRelay) {
            IBridge(liquidityBridge).relay(
                _transferParams.request,
                _transferParams.sigs,
                _transferParams.signers,
                _transferParams.powers
            );
        } else if (t == MsgDataTypes.TransferType.LqWithdraw) {
            IBridge(liquidityBridge).withdraw(
                _transferParams.request,
                _transferParams.sigs,
                _transferParams.signers,
                _transferParams.powers
            );
        } else if (t == MsgDataTypes.TransferType.PegMint) {
            IPeggedTokenBridge(pegBridge).mint(
                _transferParams.request,
                _transferParams.sigs,
                _transferParams.signers,
                _transferParams.powers
            );
        } else if (t == MsgDataTypes.TransferType.PegV2Mint) {
            IPeggedTokenBridgeV2(pegBridgeV2).mint(
                _transferParams.request,
                _transferParams.sigs,
                _transferParams.signers,
                _transferParams.powers
            );
        } else if (t == MsgDataTypes.TransferType.PegWithdraw) {
            IOriginalTokenVault(pegVault).withdraw(
                _transferParams.request,
                _transferParams.sigs,
                _transferParams.signers,
                _transferParams.powers
            );
        } else if (t == MsgDataTypes.TransferType.PegV2Withdraw) {
            IOriginalTokenVaultV2(pegVaultV2).withdraw(
                _transferParams.request,
                _transferParams.sigs,
                _transferParams.signers,
                _transferParams.powers
            );
        }
    }

    // ================= contract config =================

    function setLiquidityBridge(address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        liquidityBridge = _addr;
        emit LiquidityBridgeUpdated(liquidityBridge);
    }

    function setPegBridge(address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        pegBridge = _addr;
        emit PegBridgeUpdated(pegBridge);
    }

    function setPegVault(address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        pegVault = _addr;
        emit PegVaultUpdated(pegVault);
    }

    function setPegBridgeV2(address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        pegBridgeV2 = _addr;
        emit PegBridgeV2Updated(pegBridgeV2);
    }

    function setPegVaultV2(address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        pegVaultV2 = _addr;
        emit PegVaultV2Updated(pegVaultV2);
    }

    function setPreExecuteMessageGasUsage(uint256 _usage) public onlyOwner {
        preExecuteMessageGasUsage = _usage;
    }
}

File 63 of 120 : IMessageReceiverApp.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IMessageReceiverApp {
    enum ExecutionStatus {
        Fail, // execution failed, finalized
        Success, // execution succeeded, finalized
        Retry // execution rejected, can retry later
    }

    /**
     * @notice Called by MessageBus (MessageBusReceiver) if the process is originated from MessageBus (MessageBusSender)'s
     *         sendMessageWithTransfer it is only called when the tokens are checked to be arrived at this contract's address.
     * @param _sender The address of the source app contract
     * @param _token The address of the token that comes out of the bridge
     * @param _amount The amount of tokens received at this contract through the cross-chain bridge.
     *        the contract that implements this contract can safely assume that the tokens will arrive before this
     *        function is called.
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransfer(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable returns (ExecutionStatus);

    /**
     * @notice Only called by MessageBus (MessageBusReceiver) if
     *         1. executeMessageWithTransfer reverts, or
     *         2. executeMessageWithTransfer returns ExecutionStatus.Fail
     * @param _sender The address of the source app contract
     * @param _token The address of the token that comes out of the bridge
     * @param _amount The amount of tokens received at this contract through the cross-chain bridge.
     *        the contract that implements this contract can safely assume that the tokens will arrive before this
     *        function is called.
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransferFallback(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable returns (ExecutionStatus);

    /**
     * @notice Called by MessageBus (MessageBusReceiver) to process refund of the original transfer from this contract
     * @param _token The token address of the original transfer
     * @param _amount The amount of the original transfer
     * @param _message The same message associated with the original transfer
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessageWithTransferRefund(
        address _token,
        uint256 _amount,
        bytes calldata _message,
        address _executor
    ) external payable returns (ExecutionStatus);

    /**
     * @notice Called by MessageBus (MessageBusReceiver)
     * @param _sender The address of the source app contract
     * @param _srcChainId The source chain ID where the transfer is originated from
     * @param _message Arbitrary message bytes originated from and encoded by the source app contract
     * @param _executor Address who called the MessageBus execution function
     */
    function executeMessage(
        address _sender,
        uint64 _srcChainId,
        bytes calldata _message,
        address _executor
    ) external payable returns (ExecutionStatus);
}

File 64 of 120 : TransferSwapSendBack.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "../framework/MessageSenderApp.sol";
import "../framework/MessageReceiverApp.sol";

interface ISwapToken {
    // function sellBase(address to) external returns (uint256);
    // uniswap v2
    function swapExactTokensForTokens(
        uint256,
        uint256,
        address[] calldata,
        address,
        uint256
    ) external returns (uint256[] memory);
}

contract CrossChainSwap is MessageSenderApp, MessageReceiverApp {
    using SafeERC20 for IERC20;

    address public dex; // needed on swap chain

    struct SwapInfo {
        address wantToken; // token user want to receive on dest chain
        address user;
        bool sendBack; // if true, send wantToken back to start chain
        uint32 cbrMaxSlippage; // _maxSlippage for cbridge send
    }

    constructor(address dex_) {
        dex = dex_;
    }

    // ========== on start chain ==========

    uint64 nonce; // required by IBridge.send

    // this func could be called by a router contract
    function startCrossChainSwap(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        SwapInfo calldata swapInfo // wantToken on destChain and actual user address as receiver when send back
    ) external payable {
        nonce += 1;
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        bytes memory message = abi.encode(swapInfo);
        sendMessageWithTransfer(
            _receiver,
            _token,
            _amount,
            _dstChainId,
            nonce,
            swapInfo.cbrMaxSlippage,
            message,
            MsgDataTypes.BridgeSendType.Liquidity,
            msg.value
        );
    }

    // ========== on swap chain ==========
    // do dex, send received asset to src chain via bridge
    function executeMessageWithTransfer(
        address, // _sender
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes memory _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        SwapInfo memory swapInfo = abi.decode((_message), (SwapInfo));
        IERC20(_token).approve(dex, _amount);
        address[] memory path = new address[](2);
        path[0] = _token;
        path[1] = swapInfo.wantToken;
        if (swapInfo.sendBack) {
            nonce += 1;
            uint256[] memory swapReturn = ISwapToken(dex).swapExactTokensForTokens(
                _amount,
                0,
                path,
                address(this),
                type(uint256).max
            );
            // send received token back to start chain. swapReturn[1] is amount of wantToken
            sendTokenTransfer(
                swapInfo.user,
                swapInfo.wantToken,
                swapReturn[1],
                _srcChainId,
                nonce,
                swapInfo.cbrMaxSlippage,
                MsgDataTypes.BridgeSendType.Liquidity
            );
        } else {
            // swap to wantToken and send to user
            ISwapToken(dex).swapExactTokensForTokens(_amount, 0, path, swapInfo.user, type(uint256).max);
        }
        // bytes memory notice; // send back to src chain to handleMessage
        // sendMessage(_sender, _srcChainId, notice);
        return ExecutionStatus.Success;
    }
}

File 65 of 120 : MsgTest.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../framework/MessageSenderApp.sol";
import "../framework/MessageReceiverApp.sol";

/** @title Application to test message with transfer refund flow */
contract MsgTest is MessageSenderApp, MessageReceiverApp {
    using SafeERC20 for IERC20;
    uint64 nonce;

    event MessageReceivedWithTransfer(
        address token,
        uint256 amount,
        address sender,
        uint64 srcChainId,
        address receiver,
        bytes message
    );
    event Refunded(address receiver, address token, uint256 amount, bytes message);
    event MessageReceived(address sender, uint64 srcChainId, uint64 nonce, bytes message);

    constructor(address _messageBus) {
        messageBus = _messageBus;
    }

    function sendMessageWithTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint32 _maxSlippage,
        bytes calldata _message,
        MsgDataTypes.BridgeSendType _bridgeSendType
    ) external payable {
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        bytes memory message = abi.encode(msg.sender, _message);
        sendMessageWithTransfer(
            _receiver,
            _token,
            _amount,
            _dstChainId,
            nonce,
            _maxSlippage,
            message,
            _bridgeSendType,
            msg.value
        );
        nonce++;
    }

    function executeMessageWithTransfer(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes memory _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        (address receiver, bytes memory message) = abi.decode((_message), (address, bytes));
        IERC20(_token).safeTransfer(receiver, _amount);
        emit MessageReceivedWithTransfer(_token, _amount, _sender, _srcChainId, receiver, message);
        return ExecutionStatus.Success;
    }

    function executeMessageWithTransferRefund(
        address _token,
        uint256 _amount,
        bytes calldata _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        (address receiver, bytes memory message) = abi.decode((_message), (address, bytes));
        IERC20(_token).safeTransfer(receiver, _amount);
        emit Refunded(receiver, _token, _amount, message);
        return ExecutionStatus.Success;
    }

    function sendMessage(
        address _receiver,
        uint64 _dstChainId,
        bytes calldata _message
    ) external payable {
        bytes memory message = abi.encode(nonce, _message);
        nonce++;
        sendMessage(_receiver, _dstChainId, message, msg.value);
    }

    function sendMessages(
        address _receiver,
        uint64 _dstChainId,
        bytes[] calldata _messages,
        uint256[] calldata _fees
    ) external payable {
        for (uint256 i = 0; i < _messages.length; i++) {
            bytes memory message = abi.encode(nonce, _messages[i]);
            nonce++;
            sendMessage(_receiver, _dstChainId, message, _fees[i]);
        }
    }

    function sendMessageWithNonce(
        address _receiver,
        uint64 _dstChainId,
        bytes calldata _message,
        uint64 _nonce
    ) external payable {
        bytes memory message = abi.encode(_nonce, _message);
        sendMessage(_receiver, _dstChainId, message, msg.value);
    }

    function executeMessage(
        address _sender,
        uint64 _srcChainId,
        bytes calldata _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        (uint64 n, bytes memory message) = abi.decode((_message), (uint64, bytes));
        require(n != 100000000000001, "invalid nonce"); // test revert with reason
        if (n == 100000000000002) {
            // test revert without reason
            revert();
        } else if (n == 100000000000003) {
            return ExecutionStatus.Retry;
        }
        emit MessageReceived(_sender, _srcChainId, n, message);
        return ExecutionStatus.Success;
    }

    function drainToken(address _token, uint256 _amount) external onlyOwner {
        IERC20(_token).safeTransfer(msg.sender, _amount);
    }
}

File 66 of 120 : RestrictedMultiBridgeTokenOwner.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "../../../safeguard/Ownable.sol";

interface IMultiBridgeToken {
    function updateBridgeSupplyCap(address _bridge, uint256 _cap) external;
}

// restrict multi-bridge token to effectively only have one bridge (minter)
contract RestrictedMultiBridgeTokenOwner is Ownable {
    address public immutable token;
    address public bridge;

    constructor(address _token, address _bridge) {
        token = _token;
        bridge = _bridge;
    }

    function updateBridgeSupplyCap(uint256 _cap) external onlyOwner {
        IMultiBridgeToken(token).updateBridgeSupplyCap(bridge, _cap);
    }

    function changeBridge(address _bridge, uint256 _cap) external onlyOwner {
        // set previous bridge cap to 1 to disable mint but still allow burn
        // till its total supply becomes zero
        IMultiBridgeToken(token).updateBridgeSupplyCap(bridge, 1);
        // set new bridge and cap
        IMultiBridgeToken(token).updateBridgeSupplyCap(_bridge, _cap);
        bridge = _bridge;
    }

    function revokeBridge(address _bridge) external onlyOwner {
        // set previous bridge cap to 0 to disable both mint and burn
        IMultiBridgeToken(token).updateBridgeSupplyCap(_bridge, 0);
    }
}

File 67 of 120 : MultiBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../safeguard/Ownable.sol";

/**
 * @title Example Multi-Bridge Pegged ERC20 token
 */
contract MultiBridgeToken is ERC20, Ownable {
    struct Supply {
        uint256 cap;
        uint256 total;
    }
    mapping(address => Supply) public bridges; // bridge address -> supply

    uint8 private immutable _decimals;

    event BridgeSupplyCapUpdated(address bridge, uint256 supplyCap);

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) ERC20(name_, symbol_) {
        _decimals = decimals_;
    }

    /**
     * @notice Mints tokens to an address. Increases total amount minted by the calling bridge.
     * @param _to The address to mint tokens to.
     * @param _amount The amount to mint.
     */
    function mint(address _to, uint256 _amount) external returns (bool) {
        Supply storage b = bridges[msg.sender];
        require(b.cap > 0, "invalid caller");
        b.total += _amount;
        require(b.total <= b.cap, "exceeds bridge supply cap");
        _mint(_to, _amount);
        return true;
    }

    /**
     * @notice Burns tokens for msg.sender.
     * @param _amount The amount to burn.
     */
    function burn(uint256 _amount) external returns (bool) {
        _burn(msg.sender, _amount);
        return true;
    }

    /**
     * @notice Burns tokens from an address. Decreases total amount minted if called by a bridge.
     * Alternative to {burnFrom} for compatibility with some bridge implementations.
     * See {_burnFrom}.
     * @param _from The address to burn tokens from.
     * @param _amount The amount to burn.
     */
    function burn(address _from, uint256 _amount) external returns (bool) {
        return _burnFrom(_from, _amount);
    }

    /**
     * @notice Burns tokens from an address. Decreases total amount minted if called by a bridge.
     * See {_burnFrom}.
     * @param _from The address to burn tokens from.
     * @param _amount The amount to burn.
     */
    function burnFrom(address _from, uint256 _amount) external returns (bool) {
        return _burnFrom(_from, _amount);
    }

    /**
     * @dev Burns tokens from an address, deducting from the caller's allowance.
     *      Decreases total amount minted if called by a bridge.
     * @param _from The address to burn tokens from.
     * @param _amount The amount to burn.
     */
    function _burnFrom(address _from, uint256 _amount) internal returns (bool) {
        Supply storage b = bridges[msg.sender];
        if (b.cap > 0 || b.total > 0) {
            // set cap to 1 would effectively disable a deprecated bridge's ability to burn
            require(b.total >= _amount, "exceeds bridge minted amount");
            unchecked {
                b.total -= _amount;
            }
        }
        _spendAllowance(_from, msg.sender, _amount);
        _burn(_from, _amount);
        return true;
    }

    /**
     * @notice Returns the decimals of the token.
     */
    function decimals() public view virtual override returns (uint8) {
        return _decimals;
    }

    /**
     * @notice Updates the supply cap for a bridge.
     * @param _bridge The bridge address.
     * @param _cap The new supply cap.
     */
    function updateBridgeSupplyCap(address _bridge, uint256 _cap) external onlyOwner {
        // cap == 0 means revoking bridge role
        bridges[_bridge].cap = _cap;
        emit BridgeSupplyCapUpdated(_bridge, _cap);
    }

    /**
     * @notice Returns the owner address. Required by BEP20.
     */
    function getOwner() external view returns (address) {
        return owner();
    }
}

File 68 of 120 : ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, _allowances[owner][spender] + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = _allowances[owner][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Spend `amount` form the allowance of `owner` toward `spender`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}

File 69 of 120 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

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

File 70 of 120 : MultiBridgeTokenPermit.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "../MultiBridgeToken.sol";

/**
 * @title Example Multi-Bridge Pegged ERC20Permit token
 */
contract MultiBridgeTokenPermit is ERC20Permit, MultiBridgeToken {
    uint8 private immutable _decimals;

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) MultiBridgeToken(name_, symbol_, decimals_) ERC20Permit(name_) {
        _decimals = decimals_;
    }

    function decimals() public view override(ERC20, MultiBridgeToken) returns (uint8) {
        return _decimals;
    }
}

File 71 of 120 : draft-ERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol)

pragma solidity ^0.8.0;

import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";

/**
 * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * _Available since v3.4._
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
    using Counters for Counters.Counter;

    mapping(address => Counters.Counter) private _nonces;

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private immutable _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @dev See {IERC20Permit-permit}.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        require(signer == owner, "ERC20Permit: invalid signature");

        _approve(owner, spender, value);
    }

    /**
     * @dev See {IERC20Permit-nonces}.
     */
    function nonces(address owner) public view virtual override returns (uint256) {
        return _nonces[owner].current();
    }

    /**
     * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * @dev "Consume a nonce": return the current value and increment.
     *
     * _Available since v4.1._
     */
    function _useNonce(address owner) internal virtual returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
    }
}

File 72 of 120 : draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 73 of 120 : draft-EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;
    address private immutable _CACHED_THIS;

    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private immutable _TYPE_HASH;

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        bytes32 hashedName = keccak256(bytes(name));
        bytes32 hashedVersion = keccak256(bytes(version));
        bytes32 typeHash = keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );
        _HASHED_NAME = hashedName;
        _HASHED_VERSION = hashedVersion;
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
        _CACHED_THIS = address(this);
        _TYPE_HASH = typeHash;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
            return _CACHED_DOMAIN_SEPARATOR;
        } else {
            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
        }
    }

    function _buildDomainSeparator(
        bytes32 typeHash,
        bytes32 nameHash,
        bytes32 versionHash
    ) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }
}

File 74 of 120 : Counters.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

File 75 of 120 : SingleBridgeTokenPermit.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "../SingleBridgeToken.sol";

/**
 * @title Example Pegged ERC20Permit token
 */
contract SingleBridgeTokenPermit is ERC20Permit, SingleBridgeToken {
    uint8 private immutable _decimals;

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_,
        address bridge_
    ) SingleBridgeToken(name_, symbol_, decimals_, bridge_) ERC20Permit(name_) {
        _decimals = decimals_;
    }

    function decimals() public view override(ERC20, SingleBridgeToken) returns (uint8) {
        return _decimals;
    }
}

File 76 of 120 : SingleBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title Example Pegged ERC20 token
 */
contract SingleBridgeToken is ERC20, Ownable {
    address public bridge;

    uint8 private immutable _decimals;

    event BridgeUpdated(address bridge);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_,
        address bridge_
    ) ERC20(name_, symbol_) {
        _decimals = decimals_;
        bridge = bridge_;
    }

    /**
     * @notice Mints tokens to an address.
     * @param _to The address to mint tokens to.
     * @param _amount The amount to mint.
     */
    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(_to, _amount);
        return true;
    }

    /**
     * @notice Burns tokens for msg.sender.
     * @param _amount The amount to burn.
     */
    function burn(uint256 _amount) external returns (bool) {
        _burn(msg.sender, _amount);
        return true;
    }

    /**
     * @notice Burns tokens from an address.
     * Alternative to {burnFrom} for compatibility with some bridge implementations.
     * See {_burnFrom}.
     * @param _from The address to burn tokens from.
     * @param _amount The amount to burn.
     */
    function burn(address _from, uint256 _amount) external returns (bool) {
        return _burnFrom(_from, _amount);
    }

    /**
     * @notice Burns tokens from an address.
     * See {_burnFrom}.
     * @param _from The address to burn tokens from.
     * @param _amount The amount to burn.
     */
    function burnFrom(address _from, uint256 _amount) external returns (bool) {
        return _burnFrom(_from, _amount);
    }

    /**
     * @dev Burns tokens from an address, deducting from the caller's allowance.
     * @param _from The address to burn tokens from.
     * @param _amount The amount to burn.
     */
    function _burnFrom(address _from, uint256 _amount) internal returns (bool) {
        _spendAllowance(_from, msg.sender, _amount);
        _burn(_from, _amount);
        return true;
    }

    /**
     * @notice Returns the decimals of the token.
     */
    function decimals() public view virtual override returns (uint8) {
        return _decimals;
    }

    /**
     * @notice Updates the bridge address.
     * @param _bridge The bridge address.
     */
    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    /**
     * @notice Returns the owner address. Required by BEP20.
     */
    function getOwner() external view returns (address) {
        return owner();
    }
}

File 77 of 120 : Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 78 of 120 : WrappedBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

// Use pegged model to support no-slippage liquidity pool
contract WrappedBridgeToken is ERC20, Ownable {
    using SafeERC20 for IERC20;

    // The PeggedTokenBridge
    address public bridge;
    // The canonical
    address public immutable canonical;

    mapping(address => uint256) public liquidity;

    event BridgeUpdated(address bridge);
    event LiquidityAdded(address provider, uint256 amount);
    event LiquidityRemoved(address provider, uint256 amount);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        address bridge_,
        address canonical_
    ) ERC20(name_, symbol_) {
        bridge = bridge_;
        canonical = canonical_;
    }

    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(address(this), _amount);
        IERC20(canonical).safeTransfer(_to, _amount);
        return true;
    }

    function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
        _burn(address(this), _amount);
        IERC20(canonical).safeTransferFrom(_from, address(this), _amount);
        return true;
    }

    function addLiquidity(uint256 _amount) external {
        liquidity[msg.sender] += _amount;
        IERC20(canonical).safeTransferFrom(msg.sender, address(this), _amount);
        emit LiquidityAdded(msg.sender, _amount);
    }

    function removeLiquidity(uint256 _amount) external {
        liquidity[msg.sender] -= _amount;
        IERC20(canonical).safeTransfer(msg.sender, _amount);
        emit LiquidityRemoved(msg.sender, _amount);
    }

    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    function decimals() public view virtual override returns (uint8) {
        return ERC20(canonical).decimals();
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }
}

File 79 of 120 : WETH.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract WETH is ERC20 {
    constructor() ERC20("WETH", "WETH") {}

    function deposit() external payable {
        _mint(msg.sender, msg.value);
    }

    function withdraw(uint256 _amount) external {
        _burn(msg.sender, _amount);
        (bool sent, ) = msg.sender.call{value: _amount, gas: 50000}("");
        require(sent, "failed to send");
    }

    receive() external payable {}
}

File 80 of 120 : TestERC20.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

/**
 * @title A test ERC20 token.
 */
contract TestERC20 is ERC20 {
    uint256 public constant INITIAL_SUPPLY = 1e28;

    /**
     * @dev Constructor that gives msg.sender all of the existing tokens.
     */
    constructor() ERC20("TestERC20", "TERC20") {
        _mint(msg.sender, INITIAL_SUPPLY);
    }
}

File 81 of 120 : SwapBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

interface ISwapCanoToken {
    function swapBridgeForCanonical(address, uint256) external returns (uint256);

    function swapCanonicalForBridge(address, uint256) external returns (uint256);
}

/**
 * @title Per bridge intermediary token that supports swapping with a canonical token.
 */
contract SwapBridgeToken is ERC20, Ownable {
    using SafeERC20 for IERC20;

    address public bridge;
    address public immutable canonical; // canonical token that support swap

    event BridgeUpdated(address bridge);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        address bridge_,
        address canonical_
    ) ERC20(name_, symbol_) {
        bridge = bridge_;
        canonical = canonical_;
    }

    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(address(this), _amount); // add amount to myself so swapBridgeForCanonical can transfer amount
        uint256 got = ISwapCanoToken(canonical).swapBridgeForCanonical(address(this), _amount);
        // now this has canonical token, next step is to transfer to user
        IERC20(canonical).safeTransfer(_to, got);
        return true;
    }

    function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
        IERC20(canonical).safeTransferFrom(_from, address(this), _amount);
        uint256 got = ISwapCanoToken(canonical).swapCanonicalForBridge(address(this), _amount);
        _burn(address(this), got);
        return true;
    }

    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    // approve canonical token so swapBridgeForCanonical can work. or we approve before call it in mint w/ added gas
    function approveCanonical() external onlyOwner {
        _approve(address(this), canonical, type(uint256).max);
    }

    function revokeCanonical() external onlyOwner {
        _approve(address(this), canonical, 0);
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }

    function decimals() public view virtual override returns (uint8) {
        return ERC20(canonical).decimals();
    }
}

File 82 of 120 : IntermediaryOriginalToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title Intermediary token that automatically transfers the canonical token when interacting with approved bridges.
 */
contract IntermediaryOriginalToken is ERC20, Ownable {
    using SafeERC20 for IERC20;

    mapping(address => bool) public bridges;
    address public immutable canonical; // canonical token

    event BridgeUpdated(address bridge, bool enable);

    constructor(
        string memory name_,
        string memory symbol_,
        address[] memory bridges_,
        address canonical_
    ) ERC20(name_, symbol_) {
        for (uint256 i = 0; i < bridges_.length; i++) {
            bridges[bridges_[i]] = true;
        }
        canonical = canonical_;
    }

    function transfer(address _to, uint256 _amount) public virtual override returns (bool) {
        bool success = super.transfer(_to, _amount);
        if (bridges[msg.sender]) {
            _burn(_to, _amount);
            IERC20(canonical).safeTransfer(_to, _amount);
        }
        return success;
    }

    function transferFrom(
        address _from,
        address _to,
        uint256 _amount
    ) public virtual override returns (bool) {
        if (bridges[msg.sender]) {
            _mint(_from, _amount);
            IERC20(canonical).safeTransferFrom(_from, address(this), _amount);
        }
        return super.transferFrom(_from, _to, _amount);
    }

    function updateBridge(address _bridge, bool _enable) external onlyOwner {
        bridges[_bridge] = _enable;
        emit BridgeUpdated(_bridge, _enable);
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }

    function decimals() public view virtual override returns (uint8) {
        return ERC20(canonical).decimals();
    }
}

File 83 of 120 : IntermediaryBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

interface IERC20MintableBurnable is IERC20 {
    function mint(address receiver, uint256 amount) external;

    function burn(uint256 amount) external;
}

/**
 * @title Per bridge intermediary token that delegates to a canonical token.
 * Useful for canonical tokens that don't support the burn / burnFrom function signature required by
 * PeggedTokenBridge.
 */
contract IntermediaryBridgeToken is ERC20, Ownable {
    using SafeERC20 for IERC20;

    address public bridge;
    address public immutable canonical; // canonical token that support swap

    event BridgeUpdated(address bridge);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        address bridge_,
        address canonical_
    ) ERC20(name_, symbol_) {
        bridge = bridge_;
        canonical = canonical_;
    }

    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(address(this), _amount); // totalSupply == bridge liquidity
        IERC20MintableBurnable(canonical).mint(_to, _amount);
        return true;
    }

    function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
        _burn(address(this), _amount);
        IERC20(canonical).safeTransferFrom(_from, address(this), _amount);
        IERC20MintableBurnable(canonical).burn(_amount);
        return true;
    }

    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }

    function decimals() public view virtual override returns (uint8) {
        return ERC20(canonical).decimals();
    }
}

File 84 of 120 : OntologyBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

interface IOntologyBridgeTokenWrapper {
    function swapBridgeForCanonical(
        address bridgeToken,
        address _to,
        uint256 _amount
    ) external returns (uint256);

    function swapCanonicalForBridge(
        address bridgeToken,
        address _to,
        uint256 _amount
    ) external payable returns (uint256);
}

/**
 * @title Intermediary bridge token that supports swapping with the Ontology bridge token wrapper.
 * NOTE: The bridge wrapper is NOT the canonical token itself.
 */
contract OntologyBridgeToken is ERC20, Ownable {
    using SafeERC20 for IERC20;

    // The PeggedTokenBridge
    address public bridge;
    // Bridge token wrapper for swapping
    address public immutable wrapper;
    // The canonical token
    address public immutable canonical;

    event BridgeUpdated(address bridge);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        address bridge_,
        address wrapper_,
        address canonical_
    ) ERC20(name_, symbol_) {
        bridge = bridge_;
        wrapper = wrapper_;
        canonical = canonical_;
    }

    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(address(this), _amount);
        _approve(address(this), wrapper, _amount);
        // NOTE: swapBridgeForCanonical automatically transfers canonical token to _to.
        IOntologyBridgeTokenWrapper(wrapper).swapBridgeForCanonical(address(this), _to, _amount);
        return true;
    }

    function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
        IERC20(canonical).safeTransferFrom(_from, address(this), _amount);
        IERC20(canonical).safeIncreaseAllowance(address(wrapper), _amount);
        // NOTE: swapCanonicalForBridge automatically transfers bridge token to _from.
        uint256 got = IOntologyBridgeTokenWrapper(wrapper).swapCanonicalForBridge(address(this), _from, _amount);
        _burn(_from, got);
        return true;
    }

    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    function decimals() public view virtual override returns (uint8) {
        return ERC20(canonical).decimals();
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }
}

File 85 of 120 : MaiBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

interface IMaiBridgeHub {
    // send bridge token, get asset
    function swapIn(address, uint256) external;

    // send asset, get bridge token back
    function swapOut(address, uint256) external;

    // asset address
    function asset() external view returns (address);
}

/**
 * @title Intermediary bridge token that supports swapping with the Mai hub.
 * NOTE: Mai hub is NOT the canonical token itself. The asset is set in the hub constructor.
 */
contract MaiBridgeToken is ERC20, Ownable {
    using SafeERC20 for IERC20;

    // The PeggedTokenBridge
    address public bridge;
    // Mai hub for swapping
    address public immutable maihub;
    // The canonical Mai token
    address public immutable asset;

    event BridgeUpdated(address bridge);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        address bridge_,
        address maihub_
    ) ERC20(name_, symbol_) {
        bridge = bridge_;
        maihub = maihub_;
        asset = IMaiBridgeHub(maihub_).asset();
    }

    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(address(this), _amount); // add amount to myself so swapIn can transfer amount to hub
        _approve(address(this), maihub, _amount);
        IMaiBridgeHub(maihub).swapIn(address(this), _amount);
        // now this has canonical token, next step is to transfer to user
        IERC20(asset).safeTransfer(_to, _amount);
        return true;
    }

    function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
        IERC20(asset).safeTransferFrom(_from, address(this), _amount);
        IERC20(asset).safeIncreaseAllowance(address(maihub), _amount);
        IMaiBridgeHub(maihub).swapOut(address(this), _amount);
        _burn(address(this), _amount);
        return true;
    }

    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    function decimals() public view virtual override returns (uint8) {
        return ERC20(asset).decimals();
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }
}

File 86 of 120 : FraxBridgeToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

interface IFraxCanoToken {
    function exchangeOldForCanonical(address, uint256) external returns (uint256);

    function exchangeCanonicalForOld(address, uint256) external returns (uint256);
}

/**
 * @title Intermediary bridge token that supports swapping with the canonical Frax token.
 */
contract FraxBridgeToken is ERC20, Ownable {
    using SafeERC20 for IERC20;

    // The PeggedTokenBridge
    address public bridge;
    // The canonical Frax token that supports swapping
    address public immutable canonical;

    event BridgeUpdated(address bridge);

    modifier onlyBridge() {
        require(msg.sender == bridge, "caller is not bridge");
        _;
    }

    constructor(
        string memory name_,
        string memory symbol_,
        address bridge_,
        address canonical_
    ) ERC20(name_, symbol_) {
        bridge = bridge_;
        canonical = canonical_;
    }

    function mint(address _to, uint256 _amount) external onlyBridge returns (bool) {
        _mint(address(this), _amount); // add amount to myself so exchangeOldForCanonical can transfer amount
        _approve(address(this), canonical, _amount);
        uint256 got = IFraxCanoToken(canonical).exchangeOldForCanonical(address(this), _amount);
        // now this has canonical token, next step is to transfer to user
        IERC20(canonical).safeTransfer(_to, got);
        return true;
    }

    function burn(address _from, uint256 _amount) external onlyBridge returns (bool) {
        IERC20(canonical).safeTransferFrom(_from, address(this), _amount);
        uint256 got = IFraxCanoToken(canonical).exchangeCanonicalForOld(address(this), _amount);
        _burn(address(this), got);
        return true;
    }

    function updateBridge(address _bridge) external onlyOwner {
        bridge = _bridge;
        emit BridgeUpdated(bridge);
    }

    function decimals() public view virtual override returns (uint8) {
        return ERC20(canonical).decimals();
    }

    // to make compatible with BEP20
    function getOwner() external view returns (address) {
        return owner();
    }
}

File 87 of 120 : ERC20Burnable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)

pragma solidity ^0.8.0;

import "../ERC20.sol";
import "../../../utils/Context.sol";

/**
 * @dev Extension of {ERC20} that allows token holders to destroy both their own
 * tokens and those that they have an allowance for, in a way that can be
 * recognized off-chain (via event analysis).
 */
abstract contract ERC20Burnable is Context, ERC20 {
    /**
     * @dev Destroys `amount` tokens from the caller.
     *
     * See {ERC20-_burn}.
     */
    function burn(uint256 amount) public virtual {
        _burn(_msgSender(), amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, deducting from the caller's
     * allowance.
     *
     * See {ERC20-_burn} and {ERC20-allowance}.
     *
     * Requirements:
     *
     * - the caller must have allowance for ``accounts``'s tokens of at least
     * `amount`.
     */
    function burnFrom(address account, uint256 amount) public virtual {
        _spendAllowance(account, _msgSender(), amount);
        _burn(account, amount);
    }
}

File 88 of 120 : ERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: balance query for the zero address");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC721: owner query for nonexistent token");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overriden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not owner nor approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        require(_exists(tokenId), "ERC721: approved query for nonexistent token");

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
        _safeTransfer(from, to, tokenId, _data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `_data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _owners[tokenId] != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        require(_exists(tokenId), "ERC721: operator query for nonexistent token");
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, _data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId);

        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId);

        // Clear approvals
        _approve(address(0), tokenId);

        _balances[owner] -= 1;
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits a {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {}
}

File 89 of 120 : IERC721.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;
}

File 90 of 120 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

File 91 of 120 : IERC721Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

File 92 of 120 : ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

File 93 of 120 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

File 94 of 120 : Signers.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "../safeguard/Ownable.sol";
import "../interfaces/ISigsVerifier.sol";

/**
 * @title Multi-sig verification and management functions for {Bridge}.
 */
contract Signers is Ownable, ISigsVerifier {
    using ECDSA for bytes32;

    bytes32 public ssHash;
    uint256 public triggerTime; // timestamp when last update was triggered

    // reset can be called by the owner address for emergency recovery
    uint256 public resetTime;
    uint256 public noticePeriod; // advance notice period as seconds for reset
    uint256 constant MAX_INT = 2**256 - 1;

    event SignersUpdated(address[] _signers, uint256[] _powers);

    event ResetNotification(uint256 resetTime);

    /**
     * @notice Verifies that a message is signed by a quorum among the signers
     * The sigs must be sorted by signer addresses in ascending order.
     * @param _msg signed message
     * @param _sigs list of signatures sorted by signer addresses in ascending order
     * @param _signers sorted list of current signers
     * @param _powers powers of current signers
     */
    function verifySigs(
        bytes memory _msg,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) public view override {
        bytes32 h = keccak256(abi.encodePacked(_signers, _powers));
        require(ssHash == h, "Mismatch current signers");
        _verifySignedPowers(keccak256(_msg).toEthSignedMessageHash(), _sigs, _signers, _powers);
    }

    /**
     * @notice Update new signers.
     * @param _newSigners sorted list of new signers
     * @param _curPowers powers of new signers
     * @param _sigs list of signatures sorted by signer addresses in ascending order
     * @param _curSigners sorted list of current signers
     * @param _curPowers powers of current signers
     */
    function updateSigners(
        uint256 _triggerTime,
        address[] calldata _newSigners,
        uint256[] calldata _newPowers,
        bytes[] calldata _sigs,
        address[] calldata _curSigners,
        uint256[] calldata _curPowers
    ) external {
        // use trigger time for nonce protection, must be ascending
        require(_triggerTime > triggerTime, "Trigger time is not increasing");
        // make sure triggerTime is not too large, as it cannot be decreased once set
        require(_triggerTime < block.timestamp + 3600, "Trigger time is too large");
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "UpdateSigners"));
        verifySigs(abi.encodePacked(domain, _triggerTime, _newSigners, _newPowers), _sigs, _curSigners, _curPowers);
        _updateSigners(_newSigners, _newPowers);
        triggerTime = _triggerTime;
    }

    /**
     * @notice reset signers, only used for init setup and emergency recovery
     */
    function resetSigners(address[] calldata _signers, uint256[] calldata _powers) external onlyOwner {
        require(block.timestamp > resetTime, "not reach reset time");
        resetTime = MAX_INT;
        _updateSigners(_signers, _powers);
    }

    function notifyResetSigners() external onlyOwner {
        resetTime = block.timestamp + noticePeriod;
        emit ResetNotification(resetTime);
    }

    function increaseNoticePeriod(uint256 period) external onlyOwner {
        require(period > noticePeriod, "notice period can only be increased");
        noticePeriod = period;
    }

    // separate from verifySigs func to avoid "stack too deep" issue
    function _verifySignedPowers(
        bytes32 _hash,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) private pure {
        require(_signers.length == _powers.length, "signers and powers length not match");
        uint256 totalPower; // sum of all signer.power
        for (uint256 i = 0; i < _signers.length; i++) {
            totalPower += _powers[i];
        }
        uint256 quorum = (totalPower * 2) / 3 + 1;

        uint256 signedPower; // sum of signer powers who are in sigs
        address prev = address(0);
        uint256 index = 0;
        for (uint256 i = 0; i < _sigs.length; i++) {
            address signer = _hash.recover(_sigs[i]);
            require(signer > prev, "signers not in ascending order");
            prev = signer;
            // now find match signer add its power
            while (signer > _signers[index]) {
                index += 1;
                require(index < _signers.length, "signer not found");
            }
            if (signer == _signers[index]) {
                signedPower += _powers[index];
            }
            if (signedPower >= quorum) {
                // return early to save gas
                return;
            }
        }
        revert("quorum not reached");
    }

    function _updateSigners(address[] calldata _signers, uint256[] calldata _powers) private {
        require(_signers.length == _powers.length, "signers and powers length not match");
        address prev = address(0);
        for (uint256 i = 0; i < _signers.length; i++) {
            require(_signers[i] > prev, "New signers not in ascending order");
            prev = _signers[i];
        }
        ssHash = keccak256(abi.encodePacked(_signers, _powers));
        emit SignersUpdated(_signers, _powers);
    }
}

File 95 of 120 : NFTBridge.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;

import "../framework/MessageReceiverApp.sol";
import "../interfaces/IMessageBus.sol";
import "../../safeguard/Pauser.sol";

// interface for NFT contract, ERC721 and metadata, only funcs needed by NFTBridge
interface INFT {
    function tokenURI(uint256 tokenId) external view returns (string memory);

    function ownerOf(uint256 tokenId) external view returns (address owner);

    // we do not support NFT that charges transfer fees
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    // impl by NFToken contract, mint an NFT with id and uri to user or burn
    function bridgeMint(
        address to,
        uint256 id,
        string memory uri
    ) external;

    function burn(uint256 id) external;
}

/** @title NFT Bridge */
contract NFTBridge is MessageReceiverApp, Pauser {
    /// per dest chain id executor fee in this chain's gas token
    mapping(uint64 => uint256) public destTxFee;
    /// per dest chain id NFTBridge address
    mapping(uint64 => address) public destBridge;
    /// first key is NFT address on this chain, 2nd key is dest chain id, value is address on dest chain
    mapping(address => mapping(uint64 => address)) public destNFTAddr;

    /// only set to true if NFT addr on this chain is the orig, so we will use deposit/withdraw instead of burn/mint.
    /// not applicable for mcn nft (always burn/mint)
    mapping(address => bool) public origNFT;

    struct NFTMsg {
        address user; // receiver of minted or withdrawn NFT
        address nft; // NFT contract on mint/withdraw chain
        uint256 id; // token ID
        string uri; // tokenURI from source NFT
    }
    // emit in deposit or burn
    event Sent(address sender, address srcNft, uint256 id, uint64 dstChid, address receiver, address dstNft);
    // emit for mint or withdraw message
    event Received(address receiver, address nft, uint256 id, uint64 srcChid);

    // emit when params change
    event SetDestNFT(address srcNft, uint64 dstChid, address dstNft);
    event SetTxFee(uint64 chid, uint256 fee);
    event SetDestBridge(uint64 dstChid, address dstNftBridge);
    event FeeClaimed(uint256 amount);
    event SetOrigNFT(address nft, bool isOrig);
    // emit if executeMessage calls nft transfer or bridgeMint returns error
    event ExtCallErr(bytes returnData);

    constructor(address _msgBus) {
        messageBus = _msgBus;
    }

    // only to be called by Proxy via delegatecall and will modify Proxy state
    // initOwner will fail if owner is already set, so only delegateCall will work
    function init(address _msgBus) external {
        initOwner();
        messageBus = _msgBus;
    }

    /**
     * @notice totalFee returns gas token value to be set in user tx, includes both cbridge msg fee and executor fee on dest chain
     * @dev we use _nft address for user as it's same length so same msg cost
     * @param _dstChid dest chain ID
     * @param _nft address of source NFT contract
     * @param _id token ID to bridge (need to get accurate tokenURI length)
     * @return total fee needed for user tx
     */
    function totalFee(
        uint64 _dstChid,
        address _nft,
        uint256 _id
    ) external view returns (uint256) {
        string memory _uri = INFT(_nft).tokenURI(_id);
        bytes memory message = abi.encode(NFTMsg(_nft, _nft, _id, _uri));
        return IMessageBus(messageBus).calcFee(message) + destTxFee[_dstChid];
    }

    // ===== called by user
    /**
     * @notice locks or burn user's NFT in this contract and send message to mint (or withdraw) on dest chain
     * @param _nft address of source NFT contract
     * @param _id nft token ID to bridge
     * @param _dstChid dest chain ID
     * @param _receiver receiver address on dest chain
     */
    function sendTo(
        address _nft,
        uint256 _id,
        uint64 _dstChid,
        address _receiver
    ) external payable whenNotPaused {
        require(msg.sender == INFT(_nft).ownerOf(_id), "not token owner");
        string memory _uri = INFT(_nft).tokenURI(_id);
        if (origNFT[_nft] == true) {
            // deposit
            INFT(_nft).transferFrom(msg.sender, address(this), _id);
            require(INFT(_nft).ownerOf(_id) == address(this), "transfer NFT failed");
        } else {
            // burn
            INFT(_nft).burn(_id);
        }
        (address _dstBridge, address _dstNft) = checkAddr(_nft, _dstChid);
        msgBus(_dstBridge, _dstChid, abi.encode(NFTMsg(_receiver, _dstNft, _id, _uri)));
        emit Sent(msg.sender, _nft, _id, _dstChid, _receiver, _dstNft);
    }

    // ===== called by MCN NFT after NFT is burnt
    function sendMsg(
        uint64 _dstChid,
        address _sender,
        address _receiver,
        uint256 _id,
        string calldata _uri
    ) external payable whenNotPaused {
        address _nft = msg.sender;
        (address _dstBridge, address _dstNft) = checkAddr(_nft, _dstChid);
        msgBus(_dstBridge, _dstChid, abi.encode(NFTMsg(_receiver, _dstNft, _id, _uri)));
        emit Sent(_sender, _nft, _id, _dstChid, _receiver, _dstNft);
    }

    // ===== called by msgbus
    function executeMessage(
        address sender,
        uint64 srcChid,
        bytes memory _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        // Must check sender to ensure msg is from another nft bridge
        // but we allow retry later in case it's a temporary config error
        // risk is invalid sender will be retried but this can be easily filtered
        // in executor or require manual trigger for retry
        if (paused() || sender != destBridge[srcChid]) {
            return ExecutionStatus.Retry;
        }
        // withdraw original locked nft back to user, or mint new nft depending on if this is the orig chain of nft
        NFTMsg memory nftMsg = abi.decode((_message), (NFTMsg));
        // if we are on nft orig chain, use transfer, otherwise, use mint
        if (origNFT[nftMsg.nft] == true) {
            try INFT(nftMsg.nft).transferFrom(address(this), nftMsg.user, nftMsg.id) {
                // do nothing here to move on to emit Received event and return success
            } catch (bytes memory returnData) {
                emit ExtCallErr(returnData);
                return ExecutionStatus.Retry;
            }
        } else {
            try INFT(nftMsg.nft).bridgeMint(nftMsg.user, nftMsg.id, nftMsg.uri) {
                // do nothing here to move on to emit Received event and return success
            } catch (bytes memory returnData) {
                emit ExtCallErr(returnData);
                return ExecutionStatus.Retry;
            }
        }
        emit Received(nftMsg.user, nftMsg.nft, nftMsg.id, srcChid);
        return ExecutionStatus.Success;
    }

    // ===== internal utils
    // check _nft and destChid are valid, return dstBridge and dstNft
    function checkAddr(address _nft, uint64 _dstChid) internal view returns (address dstBridge, address dstNft) {
        dstBridge = destBridge[_dstChid];
        require(dstBridge != address(0), "dest NFT Bridge not found");
        dstNft = destNFTAddr[_nft][_dstChid];
        require(dstNft != address(0), "dest NFT not found");
    }

    // check fee and call msgbus sendMessage
    function msgBus(
        address _dstBridge,
        uint64 _dstChid,
        bytes memory message
    ) internal {
        uint256 fee = IMessageBus(messageBus).calcFee(message);
        require(msg.value >= fee + destTxFee[_dstChid], "insufficient fee");
        IMessageBus(messageBus).sendMessage{value: fee}(_dstBridge, _dstChid, message);
    }

    // only owner
    // set per NFT, per chain id, address
    function setDestNFT(
        address srcNft,
        uint64 dstChid,
        address dstNft
    ) external onlyOwner {
        destNFTAddr[srcNft][dstChid] = dstNft;
        emit SetDestNFT(srcNft, dstChid, dstNft);
    }

    // set all dest chains
    function setDestNFTs(
        address srcNft,
        uint64[] calldata dstChid,
        address[] calldata dstNft
    ) external onlyOwner {
        require(dstChid.length == dstNft.length, "length mismatch");
        for (uint256 i = 0; i < dstChid.length; i++) {
            destNFTAddr[srcNft][dstChid[i]] = dstNft[i];
        }
    }

    // set destTxFee
    function setTxFee(uint64 chid, uint256 fee) external onlyOwner {
        destTxFee[chid] = fee;
        emit SetTxFee(chid, fee);
    }

    // set per chain id, nft bridge address
    function setDestBridge(uint64 dstChid, address dstNftBridge) external onlyOwner {
        destBridge[dstChid] = dstNftBridge;
        emit SetDestBridge(dstChid, dstNftBridge);
    }

    // batch set nft bridge addresses for multiple chainids
    function setDestBridges(uint64[] calldata dstChid, address[] calldata dstNftBridge) external onlyOwner {
        for (uint256 i = 0; i < dstChid.length; i++) {
            destBridge[dstChid[i]] = dstNftBridge[i];
        }
    }

    // only called on NFT's orig chain, not applicable for mcn nft
    function setOrigNFT(address _nft) external onlyOwner {
        origNFT[_nft] = true;
        emit SetOrigNFT(_nft, true);
    }

    // remove origNFT entry
    function delOrigNFT(address _nft) external onlyOwner {
        delete origNFT[_nft];
        emit SetOrigNFT(_nft, false);
    }

    // send all gas token this contract has to owner
    function claimFee() external onlyOwner {
        uint256 amount = address(this).balance;
        payable(msg.sender).transfer(amount);
        emit FeeClaimed(amount);
    }
}

File 96 of 120 : BridgeTransferLib.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

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

import "./PbBridge.sol";
import "./PbPegged.sol";
import "./PbPool.sol";
import "../interfaces/IBridge.sol";
import "../interfaces/IOriginalTokenVault.sol";
import "../interfaces/IOriginalTokenVaultV2.sol";
import "../interfaces/IPeggedTokenBridge.sol";
import "../interfaces/IPeggedTokenBridgeV2.sol";

interface INativeWrap {
    function nativeWrap() external view returns (address);
}

library BridgeTransferLib {
    using SafeERC20 for IERC20;

    enum BridgeSendType {
        Null,
        Liquidity,
        PegDeposit,
        PegBurn,
        PegV2Deposit,
        PegV2Burn,
        PegV2BurnFrom
    }

    enum BridgeReceiveType {
        Null,
        LqRelay,
        LqWithdraw,
        PegMint,
        PegWithdraw,
        PegV2Mint,
        PegV2Withdraw
    }

    struct ReceiveInfo {
        bytes32 transferId;
        address receiver;
        address token; // 0 address for native token
        uint256 amount;
        bytes32 refid; // reference id, e.g., srcTransferId for refund
    }

    // ============== Internal library functions called by apps ==============

    /**
     * @notice Send a cross-chain transfer either via liquidity pool-based bridge or in the form of pegged mint / burn.
     * @param _receiver The address of the receiver.
     * @param _token The address of the token.
     * @param _amount The amount of the transfer.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     *        Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
     *        (100% - max slippage percentage) * amount or the transfer can be refunded.
     *        Only applicable to the {BridgeSendType.Liquidity}.
     * @param _bridgeSendType The type of the bridge used by this transfer. One of the {BridgeSendType} enum.
     * @param _bridgeAddr The address of the bridge used.
     */
    function sendTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage, // slippage * 1M, eg. 0.5% -> 5000
        BridgeSendType _bridgeSendType,
        address _bridgeAddr
    ) internal returns (bytes32) {
        bytes32 transferId;
        IERC20(_token).safeIncreaseAllowance(_bridgeAddr, _amount);
        if (_bridgeSendType == BridgeSendType.Liquidity) {
            IBridge(_bridgeAddr).send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
            transferId = keccak256(
                abi.encodePacked(address(this), _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid))
            );
        } else if (_bridgeSendType == BridgeSendType.PegDeposit) {
            IOriginalTokenVault(_bridgeAddr).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
            transferId = keccak256(
                abi.encodePacked(address(this), _token, _amount, _dstChainId, _receiver, _nonce, uint64(block.chainid))
            );
        } else if (_bridgeSendType == BridgeSendType.PegBurn) {
            IPeggedTokenBridge(_bridgeAddr).burn(_token, _amount, _receiver, _nonce);
            transferId = keccak256(
                abi.encodePacked(address(this), _token, _amount, _receiver, _nonce, uint64(block.chainid))
            );
            // handle cases where certain tokens do not spend allowance for role-based burn
            IERC20(_token).safeApprove(_bridgeAddr, 0);
        } else if (_bridgeSendType == BridgeSendType.PegV2Deposit) {
            transferId = IOriginalTokenVaultV2(_bridgeAddr).deposit(_token, _amount, _dstChainId, _receiver, _nonce);
        } else if (_bridgeSendType == BridgeSendType.PegV2Burn) {
            transferId = IPeggedTokenBridgeV2(_bridgeAddr).burn(_token, _amount, _dstChainId, _receiver, _nonce);
            // handle cases where certain tokens do not spend allowance for role-based burn
            IERC20(_token).safeApprove(_bridgeAddr, 0);
        } else if (_bridgeSendType == BridgeSendType.PegV2BurnFrom) {
            transferId = IPeggedTokenBridgeV2(_bridgeAddr).burnFrom(_token, _amount, _dstChainId, _receiver, _nonce);
            // handle cases where certain tokens do not spend allowance for role-based burn
            IERC20(_token).safeApprove(_bridgeAddr, 0);
        } else {
            revert("bridge send type not supported");
        }
        return transferId;
    }

    /**
     * @notice Receive a cross-chain transfer.
     * @param _request The serialized request protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     * @param _bridgeReceiveType The type of the received transfer. One of the {BridgeReceiveType} enum.
     * @param _bridgeAddr The address of the bridge used.
     */
    function receiveTransfer(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers,
        BridgeReceiveType _bridgeReceiveType,
        address _bridgeAddr
    ) internal returns (ReceiveInfo memory) {
        if (_bridgeReceiveType == BridgeReceiveType.LqRelay) {
            return receiveLiquidityRelay(_request, _sigs, _signers, _powers, _bridgeAddr);
        } else if (_bridgeReceiveType == BridgeReceiveType.LqWithdraw) {
            return receiveLiquidityWithdraw(_request, _sigs, _signers, _powers, _bridgeAddr);
        } else if (_bridgeReceiveType == BridgeReceiveType.PegWithdraw) {
            return receivePegWithdraw(_request, _sigs, _signers, _powers, _bridgeAddr);
        } else if (_bridgeReceiveType == BridgeReceiveType.PegMint) {
            return receivePegMint(_request, _sigs, _signers, _powers, _bridgeAddr);
        } else if (_bridgeReceiveType == BridgeReceiveType.PegV2Withdraw) {
            return receivePegV2Withdraw(_request, _sigs, _signers, _powers, _bridgeAddr);
        } else if (_bridgeReceiveType == BridgeReceiveType.PegV2Mint) {
            return receivePegV2Mint(_request, _sigs, _signers, _powers, _bridgeAddr);
        } else {
            revert("bridge receive type not supported");
        }
    }

    /**
     * @notice Receive a liquidity bridge relay.
     * @param _request The serialized request protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     * @param _bridgeAddr The address of liquidity bridge.
     */
    function receiveLiquidityRelay(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers,
        address _bridgeAddr
    ) internal returns (ReceiveInfo memory) {
        ReceiveInfo memory recv;
        PbBridge.Relay memory request = PbBridge.decRelay(_request);
        recv.transferId = keccak256(
            abi.encodePacked(
                request.sender,
                request.receiver,
                request.token,
                request.amount,
                request.srcChainId,
                uint64(block.chainid),
                request.srcTransferId
            )
        );
        recv.refid = request.srcTransferId;
        recv.receiver = request.receiver;
        recv.token = request.token;
        recv.amount = request.amount;
        if (!IBridge(_bridgeAddr).transfers(recv.transferId)) {
            IBridge(_bridgeAddr).relay(_request, _sigs, _signers, _powers);
        }
        return recv;
    }

    /**
     * @notice Receive a liquidity bridge withdrawal.
     * @param _request The serialized request protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     * @param _bridgeAddr The address of liquidity bridge.
     */
    function receiveLiquidityWithdraw(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers,
        address _bridgeAddr
    ) internal returns (ReceiveInfo memory) {
        ReceiveInfo memory recv;
        PbPool.WithdrawMsg memory request = PbPool.decWithdrawMsg(_request);
        recv.transferId = keccak256(
            abi.encodePacked(request.chainid, request.seqnum, request.receiver, request.token, request.amount)
        );
        recv.refid = request.refid;
        recv.receiver = request.receiver;
        if (INativeWrap(_bridgeAddr).nativeWrap() == request.token) {
            recv.token = address(0);
        } else {
            recv.token = request.token;
        }
        recv.amount = request.amount;
        if (!IBridge(_bridgeAddr).withdraws(recv.transferId)) {
            IBridge(_bridgeAddr).withdraw(_request, _sigs, _signers, _powers);
        }
        return recv;
    }

    /**
     * @notice Receive an OriginalTokenVault withdrawal.
     * @param _request The serialized request protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     * @param _bridgeAddr The address of OriginalTokenVault.
     */
    function receivePegWithdraw(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers,
        address _bridgeAddr
    ) internal returns (ReceiveInfo memory) {
        ReceiveInfo memory recv;
        PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
        recv.transferId = keccak256(
            abi.encodePacked(
                request.receiver,
                request.token,
                request.amount,
                request.burnAccount,
                request.refChainId,
                request.refId
            )
        );
        recv.refid = request.refId;
        recv.receiver = request.receiver;
        if (INativeWrap(_bridgeAddr).nativeWrap() == request.token) {
            recv.token = address(0);
        } else {
            recv.token = request.token;
        }
        recv.amount = request.amount;
        if (!IOriginalTokenVault(_bridgeAddr).records(recv.transferId)) {
            IOriginalTokenVault(_bridgeAddr).withdraw(_request, _sigs, _signers, _powers);
        }
        return recv;
    }

    /**
     * @notice Receive a PeggedTokenBridge mint.
     * @param _request The serialized request protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     * @param _bridgeAddr The address of PeggedTokenBridge.
     */
    function receivePegMint(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers,
        address _bridgeAddr
    ) internal returns (ReceiveInfo memory) {
        ReceiveInfo memory recv;
        PbPegged.Mint memory request = PbPegged.decMint(_request);
        recv.transferId = keccak256(
            abi.encodePacked(
                request.account,
                request.token,
                request.amount,
                request.depositor,
                request.refChainId,
                request.refId
            )
        );
        recv.refid = request.refId;
        recv.receiver = request.account;
        recv.token = request.token;
        recv.amount = request.amount;
        if (!IPeggedTokenBridge(_bridgeAddr).records(recv.transferId)) {
            IPeggedTokenBridge(_bridgeAddr).mint(_request, _sigs, _signers, _powers);
        }
        return recv;
    }

    /**
     * @notice Receive an OriginalTokenVaultV2 withdrawal.
     * @param _request The serialized request protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A request must be signed-off by
     * +2/3 of the bridge's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     * @param _bridgeAddr The address of OriginalTokenVaultV2.
     */
    function receivePegV2Withdraw(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers,
        address _bridgeAddr
    ) internal returns (ReceiveInfo memory) {
        ReceiveInfo memory recv;
        PbPegged.Withdraw memory request = PbPegged.decWithdraw(_request);
        if (IOriginalTokenVaultV2(_bridgeAddr).records(request.refId)) {
            recv.transferId = keccak256(
                abi.encodePacked(
                    request.receiver,
                    request.token,
                    request.amount,
                    request.burnAccount,
                    request.refChainId,
                    request.refId,
                    _bridgeAddr
                )
            );
        } else {
            recv.transferId = IOriginalTokenVaultV2(_bridgeAddr).withdraw(_request, _sigs, _signers, _powers);
        }
        recv.refid = request.refId;
        recv.receiver = request.receiver;
        if (INativeWrap(_bridgeAddr).nativeWrap() == request.token) {
            recv.token = address(0);
        } else {
            recv.token = request.token;
        }
        recv.amount = request.amount;
        return recv;
    }

    /**
     * @notice Receive a PeggedTokenBridgeV2 mint.
     * @param _request The serialized request protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A request must be signed-off by
     * +2/3 of the bridge's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     * @param _bridgeAddr The address of PeggedTokenBridgeV2.
     */
    function receivePegV2Mint(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers,
        address _bridgeAddr
    ) internal returns (ReceiveInfo memory) {
        ReceiveInfo memory recv;
        PbPegged.Mint memory request = PbPegged.decMint(_request);
        if (IPeggedTokenBridgeV2(_bridgeAddr).records(request.refId)) {
            recv.transferId = keccak256(
                abi.encodePacked(
                    request.account,
                    request.token,
                    request.amount,
                    request.depositor,
                    request.refChainId,
                    request.refId,
                    _bridgeAddr
                )
            );
        } else {
            recv.transferId = IPeggedTokenBridgeV2(_bridgeAddr).mint(_request, _sigs, _signers, _powers);
        }
        recv.refid = request.refId;
        recv.receiver = request.account;
        recv.token = request.token;
        recv.amount = request.amount;
        return recv;
    }

    function bridgeRefundType(BridgeSendType _bridgeSendType) internal pure returns (BridgeReceiveType) {
        if (_bridgeSendType == BridgeSendType.Liquidity) {
            return BridgeReceiveType.LqWithdraw;
        }
        if (_bridgeSendType == BridgeSendType.PegDeposit) {
            return BridgeReceiveType.PegWithdraw;
        }
        if (_bridgeSendType == BridgeSendType.PegBurn) {
            return BridgeReceiveType.PegMint;
        }
        if (_bridgeSendType == BridgeSendType.PegV2Deposit) {
            return BridgeReceiveType.PegV2Withdraw;
        }
        if (_bridgeSendType == BridgeSendType.PegV2Burn || _bridgeSendType == BridgeSendType.PegV2BurnFrom) {
            return BridgeReceiveType.PegV2Mint;
        }
        return BridgeReceiveType.Null;
    }
}

File 97 of 120 : PbBridge.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: bridge.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbBridge {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct Relay {
        address sender; // tag: 1
        address receiver; // tag: 2
        address token; // tag: 3
        uint256 amount; // tag: 4
        uint64 srcChainId; // tag: 5
        uint64 dstChainId; // tag: 6
        bytes32 srcTransferId; // tag: 7
    } // end struct Relay

    function decRelay(bytes memory raw) internal pure returns (Relay memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.sender = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.receiver = Pb._address(buf.decBytes());
            } else if (tag == 3) {
                m.token = Pb._address(buf.decBytes());
            } else if (tag == 4) {
                m.amount = Pb._uint256(buf.decBytes());
            } else if (tag == 5) {
                m.srcChainId = uint64(buf.decVarint());
            } else if (tag == 6) {
                m.dstChainId = uint64(buf.decVarint());
            } else if (tag == 7) {
                m.srcTransferId = Pb._bytes32(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder Relay
}

File 98 of 120 : PbPool.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/pool.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbPool {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct WithdrawMsg {
        uint64 chainid; // tag: 1
        uint64 seqnum; // tag: 2
        address receiver; // tag: 3
        address token; // tag: 4
        uint256 amount; // tag: 5
        bytes32 refid; // tag: 6
    } // end struct WithdrawMsg

    function decWithdrawMsg(bytes memory raw) internal pure returns (WithdrawMsg memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.chainid = uint64(buf.decVarint());
            } else if (tag == 2) {
                m.seqnum = uint64(buf.decVarint());
            } else if (tag == 3) {
                m.receiver = Pb._address(buf.decBytes());
            } else if (tag == 4) {
                m.token = Pb._address(buf.decBytes());
            } else if (tag == 5) {
                m.amount = Pb._uint256(buf.decBytes());
            } else if (tag == 6) {
                m.refid = Pb._bytes32(buf.decBytes());
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder WithdrawMsg
}

File 99 of 120 : Pool.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IWETH.sol";
import "../libraries/PbPool.sol";
import "../safeguard/Pauser.sol";
import "../safeguard/VolumeControl.sol";
import "../safeguard/DelayedTransfer.sol";
import "./Signers.sol";

/**
 * @title Liquidity pool functions for {Bridge}.
 */
contract Pool is Signers, ReentrancyGuard, Pauser, VolumeControl, DelayedTransfer {
    using SafeERC20 for IERC20;

    uint64 public addseq; // ensure unique LiquidityAdded event, start from 1
    mapping(address => uint256) public minAdd; // add _amount must > minAdd

    // map of successful withdraws, if true means already withdrew money or added to delayedTransfers
    mapping(bytes32 => bool) public withdraws;

    // erc20 wrap of gas token of this chain, eg. WETH, when relay ie. pay out,
    // if request.token equals this, will withdraw and send native token to receiver
    // note we don't check whether it's zero address. when this isn't set, and request.token
    // is all 0 address, guarantee fail
    address public nativeWrap;

    // liquidity events
    event LiquidityAdded(
        uint64 seqnum,
        address provider,
        address token,
        uint256 amount // how many tokens were added
    );
    event WithdrawDone(
        bytes32 withdrawId,
        uint64 seqnum,
        address receiver,
        address token,
        uint256 amount,
        bytes32 refid
    );
    event MinAddUpdated(address token, uint256 amount);

    /**
     * @notice Add liquidity to the pool-based bridge.
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * @param _token The address of the token.
     * @param _amount The amount to add.
     */
    function addLiquidity(address _token, uint256 _amount) external nonReentrant whenNotPaused {
        require(_amount > minAdd[_token], "amount too small");
        addseq += 1;
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        emit LiquidityAdded(addseq, msg.sender, _token, _amount);
    }

    /**
     * @notice Add native token liquidity to the pool-based bridge.
     * @param _amount The amount to add.
     */
    function addNativeLiquidity(uint256 _amount) external payable nonReentrant whenNotPaused {
        require(msg.value == _amount, "Amount mismatch");
        require(nativeWrap != address(0), "Native wrap not set");
        require(_amount > minAdd[nativeWrap], "amount too small");
        addseq += 1;
        IWETH(nativeWrap).deposit{value: _amount}();
        emit LiquidityAdded(addseq, msg.sender, nativeWrap, _amount);
    }

    /**
     * @notice Withdraw funds from the bridge pool.
     * @param _wdmsg The serialized Withdraw protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A withdrawal must be
     * signed-off by +2/3 of the bridge's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function withdraw(
        bytes calldata _wdmsg,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "WithdrawMsg"));
        verifySigs(abi.encodePacked(domain, _wdmsg), _sigs, _signers, _powers);
        // decode and check wdmsg
        PbPool.WithdrawMsg memory wdmsg = PbPool.decWithdrawMsg(_wdmsg);
        // len = 8 + 8 + 20 + 20 + 32 = 88
        bytes32 wdId = keccak256(
            abi.encodePacked(wdmsg.chainid, wdmsg.seqnum, wdmsg.receiver, wdmsg.token, wdmsg.amount)
        );
        require(withdraws[wdId] == false, "withdraw already succeeded");
        withdraws[wdId] = true;
        _updateVolume(wdmsg.token, wdmsg.amount);
        uint256 delayThreshold = delayThresholds[wdmsg.token];
        if (delayThreshold > 0 && wdmsg.amount > delayThreshold) {
            _addDelayedTransfer(wdId, wdmsg.receiver, wdmsg.token, wdmsg.amount);
        } else {
            _sendToken(wdmsg.receiver, wdmsg.token, wdmsg.amount);
        }
        emit WithdrawDone(wdId, wdmsg.seqnum, wdmsg.receiver, wdmsg.token, wdmsg.amount, wdmsg.refid);
    }

    function executeDelayedTransfer(bytes32 id) external whenNotPaused {
        delayedTransfer memory transfer = _executeDelayedTransfer(id);
        _sendToken(transfer.receiver, transfer.token, transfer.amount);
    }

    function setMinAdd(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            minAdd[_tokens[i]] = _amounts[i];
            emit MinAddUpdated(_tokens[i], _amounts[i]);
        }
    }

    function _sendToken(
        address _receiver,
        address _token,
        uint256 _amount
    ) internal {
        if (_token == nativeWrap) {
            // withdraw then transfer native to receiver
            IWETH(nativeWrap).withdraw(_amount);
            (bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
            require(sent, "failed to send native token");
        } else {
            IERC20(_token).safeTransfer(_receiver, _amount);
        }
    }

    // set nativeWrap, for relay requests, if token == nativeWrap, will withdraw first then transfer native to receiver
    function setWrap(address _weth) external onlyOwner {
        nativeWrap = _weth;
    }
}

File 100 of 120 : ContractAsSender.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

import "../libraries/BridgeTransferLib.sol";
import "../safeguard/Pauser.sol";

/**
 * @title Example contract to send cBridge transfers. Supports the liquidity pool-based {Bridge}, the {OriginalTokenVault} for pegged
 * deposit and the {PeggedTokenBridge} for pegged burn. Includes handling of refunds for failed transfers.
 * @notice For the bad Bridge.send/PeggedTokenBridge.deposit of native token(eg.ETH) or wrapped native token(eg.WETH),
 * its refund asset depends on whether the nativeWrap of Bridge/PeggedTokenBridge is set or not AT THE MOMENT OF REFUNDING.
 * If the nativeWrap is set, the refund asset would always be native token (eg.ETH), even though the original sending asset
 * is wrapped native token. If the nativeWrap isn't set, the refund asset would always be wrapped native token.
 */
contract ContractAsSender is ReentrancyGuard, Pauser {
    using SafeERC20 for IERC20;

    mapping(BridgeTransferLib.BridgeSendType => address) public bridges;
    mapping(bytes32 => address) public records;
    address public nativeWrap;

    event Deposited(address depositor, address token, uint256 amount);
    event BridgeUpdated(BridgeTransferLib.BridgeSendType bridgeSendType, address bridgeAddr);

    /**
     * @notice Send a cross-chain transfer either via liquidity pool-based bridge or in form of mint/burn.
     * @param _receiver The address of the receiver.
     * @param _token The address of the token.
     * @param _amount The amount of the transfer.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     *        Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least
     *        (100% - max slippage percentage) * amount or the transfer can be refunded.
     *        Only applicable to the {BridgeSendType.Liquidity}.
     * @param _bridgeSendType The type of bridge used by this transfer. One of the {BridgeSendType} enum.
     */
    function transfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage, // slippage * 1M, eg. 0.5% -> 5000
        BridgeTransferLib.BridgeSendType _bridgeSendType
    ) external nonReentrant whenNotPaused onlyOwner returns (bytes32) {
        address _bridgeAddr = bridges[_bridgeSendType];
        require(_bridgeAddr != address(0), "unknown bridge type");
        bytes32 transferId = BridgeTransferLib.sendTransfer(
            _receiver,
            _token,
            _amount,
            _dstChainId,
            _nonce,
            _maxSlippage,
            _bridgeSendType,
            _bridgeAddr
        );
        require(records[transferId] == address(0), "record exists");
        records[transferId] = msg.sender;
        return transferId;
    }

    /**
     * @notice Refund a failed cross-chain transfer.
     * @param _request The serialized request protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     * @param _bridgeSendType The type of bridge used by this failed transfer. One of the {BridgeSendType} enum.
     */
    function refund(
        bytes calldata _request,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers,
        BridgeTransferLib.BridgeSendType _bridgeSendType
    ) external nonReentrant whenNotPaused onlyOwner returns (bytes32) {
        address _bridgeAddr = bridges[_bridgeSendType];
        require(_bridgeAddr != address(0), "unknown bridge type");
        BridgeTransferLib.ReceiveInfo memory refundInfo = BridgeTransferLib.receiveTransfer(
            _request,
            _sigs,
            _signers,
            _powers,
            BridgeTransferLib.bridgeRefundType(_bridgeSendType),
            _bridgeAddr
        );
        require(refundInfo.receiver == address(this), "invalid refund");
        address _receiver = records[refundInfo.refid];
        require(_receiver != address(0), "unknown transfer id or already refunded");
        delete records[refundInfo.refid];
        _sendToken(_receiver, refundInfo.token, refundInfo.amount);
        return refundInfo.transferId;
    }

    /**
     * @notice Send token to user. For native token and wrapped native token, this contract may not have enough _token to
     * send to _receiver. This may caused by others refund an original transfer that is sent from this contract via cBridge
     * contract right before you call refund function of this contract and then the nativeWrap of cBridge contract is
     * modified right after that the refund triggered by that guy completes.
     * As a consequence, native token and wrapped native token possessed by this contract are mixed. But don't worry,
     * the total sum of two tokens keeps correct. So in order to avoid deadlocking any token, we'd better have a
     * balance check before sending out native token or wrapped native token. If the balance of _token is not sufficient,
     * we change to sent the other token.
     */
    function _sendToken(
        address _receiver,
        address _token,
        uint256 _amount
    ) internal {
        if (_token == address(0)) {
            // refund asset is ETH
            if (address(this).balance >= _amount) {
                (bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
                require(sent, "failed to send native token");
            } else {
                // in case of refund asset is WETH
                IERC20(_token).safeTransfer(_receiver, _amount);
            }
        } else if (_token == nativeWrap) {
            // refund asset is WETH
            if (IERC20(_token).balanceOf(address(this)) >= _amount) {
                IERC20(_token).safeTransfer(_receiver, _amount);
            } else {
                // in case of refund asset is ETH
                (bool sent, ) = _receiver.call{value: _amount, gas: 50000}("");
                require(sent, "failed to send native token");
            }
        } else {
            IERC20(_token).safeTransfer(_receiver, _amount);
        }
    }

    // ----------------------Admin operation-----------------------

    /**
     * @notice Lock tokens.
     * @param _token The deposited token address.
     * @param _amount The amount to deposit.
     */
    function deposit(address _token, uint256 _amount) external nonReentrant whenNotPaused onlyOwner {
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        emit Deposited(msg.sender, _token, _amount);
    }

    function setBridgeAddress(BridgeTransferLib.BridgeSendType _bridgeSendType, address _addr) public onlyOwner {
        require(_addr != address(0), "invalid address");
        bridges[_bridgeSendType] = _addr;
        emit BridgeUpdated(_bridgeSendType, _addr);
    }

    // set nativeWrap
    function setWrap(address _weth) external onlyOwner {
        nativeWrap = _weth;
    }

    // This is needed to receive ETH if a refund asset is ETH
    receive() external payable {}
}

File 101 of 120 : ContractAsLP.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IPool.sol";
import "../interfaces/IWithdrawInbox.sol";
import "../safeguard/Pauser.sol";

/**
 * @title Example contract to provide liquidity to {Bridge}. Supports withdrawing liquidity via {WithdrawInbox}.
 */
contract ContractAsLP is ReentrancyGuard, Pauser {
    using SafeERC20 for IERC20;

    address public bridge;
    address public inbox;

    event Deposited(address depositor, address token, uint256 amount);

    constructor(address _bridge, address _inbox) {
        bridge = _bridge;
        inbox = _inbox;
    }

    /**
     * @notice Deposit tokens.
     * @param _token The deposited token address.
     * @param _amount The amount to deposit.
     */
    function deposit(address _token, uint256 _amount) external nonReentrant whenNotPaused onlyOwner {
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        emit Deposited(msg.sender, _token, _amount);
    }

    /**
     * @notice Add liquidity to the pool-based bridge.
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * @param _token The address of the token.
     * @param _amount The amount to add.
     */
    function addLiquidity(address _token, uint256 _amount) external whenNotPaused onlyOwner {
        require(IERC20(_token).balanceOf(address(this)) >= _amount, "insufficient balance");
        IERC20(_token).safeIncreaseAllowance(bridge, _amount);
        IPool(bridge).addLiquidity(_token, _amount);
    }

    /**
     * @notice Withdraw liquidity from the pool-based bridge.
     * NOTE: Each of your withdrawal request should have different _wdSeq.
     * NOTE: Tokens to withdraw within one withdrawal request should have the same symbol.
     * @param _wdSeq The unique sequence number to identify this withdrawal request.
     * @param _receiver The receiver address on _toChain.
     * @param _toChain The chain Id to receive the withdrawn tokens.
     * @param _fromChains The chain Ids to withdraw tokens.
     * @param _tokens The token to withdraw on each fromChain.
     * @param _ratios The withdrawal ratios of each token.
     * @param _slippages The max slippages of each token for cross-chain withdraw.
     */
    function withdraw(
        uint64 _wdSeq,
        address _receiver,
        uint64 _toChain,
        uint64[] calldata _fromChains,
        address[] calldata _tokens,
        uint32[] calldata _ratios,
        uint32[] calldata _slippages
    ) external whenNotPaused onlyOwner {
        IWithdrawInbox(inbox).withdraw(_wdSeq, _receiver, _toChain, _fromChains, _tokens, _ratios, _slippages);
    }
}

File 102 of 120 : IPool.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IPool {
    function addLiquidity(address _token, uint256 _amount) external;

    function withdraws(bytes32 withdrawId) external view returns (bool);

    function withdraw(
        bytes calldata _wdmsg,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external;
}

File 103 of 120 : IWithdrawInbox.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.0;

interface IWithdrawInbox {
    function withdraw(
        uint64 _wdSeq,
        address _receiver,
        uint64 _toChain,
        uint64[] calldata _fromChains,
        address[] calldata _tokens,
        uint32[] calldata _ratios,
        uint32[] calldata _slippages
    ) external;
}

File 104 of 120 : Bridge.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../libraries/PbBridge.sol";
import "./Pool.sol";

/**
 * @title The liquidity-pool based bridge.
 */
contract Bridge is Pool {
    using SafeERC20 for IERC20;

    // liquidity events
    event Send(
        bytes32 transferId,
        address sender,
        address receiver,
        address token,
        uint256 amount,
        uint64 dstChainId,
        uint64 nonce,
        uint32 maxSlippage
    );
    event Relay(
        bytes32 transferId,
        address sender,
        address receiver,
        address token,
        uint256 amount,
        uint64 srcChainId,
        bytes32 srcTransferId
    );
    // gov events
    event MinSendUpdated(address token, uint256 amount);
    event MaxSendUpdated(address token, uint256 amount);

    mapping(bytes32 => bool) public transfers;
    mapping(address => uint256) public minSend; // send _amount must > minSend
    mapping(address => uint256) public maxSend;

    // min allowed max slippage uint32 value is slippage * 1M, eg. 0.5% -> 5000
    uint32 public minimalMaxSlippage;

    /**
     * @notice Send a cross-chain transfer via the liquidity pool-based bridge.
     * NOTE: This function DOES NOT SUPPORT fee-on-transfer / rebasing tokens.
     * @param _receiver The address of the receiver.
     * @param _token The address of the token.
     * @param _amount The amount of the transfer.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A number input to guarantee uniqueness of transferId. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     * Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the
     * transfer can be refunded.
     */
    function send(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage // slippage * 1M, eg. 0.5% -> 5000
    ) external nonReentrant whenNotPaused {
        bytes32 transferId = _send(_receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        emit Send(transferId, msg.sender, _receiver, _token, _amount, _dstChainId, _nonce, _maxSlippage);
    }

    /**
     * @notice Send a cross-chain transfer via the liquidity pool-based bridge using the native token.
     * @param _receiver The address of the receiver.
     * @param _amount The amount of the transfer.
     * @param _dstChainId The destination chain ID.
     * @param _nonce A unique number. Can be timestamp in practice.
     * @param _maxSlippage The max slippage accepted, given as percentage in point (pip). Eg. 5000 means 0.5%.
     * Must be greater than minimalMaxSlippage. Receiver is guaranteed to receive at least (100% - max slippage percentage) * amount or the
     * transfer can be refunded.
     */
    function sendNative(
        address _receiver,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage
    ) external payable nonReentrant whenNotPaused {
        require(msg.value == _amount, "Amount mismatch");
        require(nativeWrap != address(0), "Native wrap not set");
        bytes32 transferId = _send(_receiver, nativeWrap, _amount, _dstChainId, _nonce, _maxSlippage);
        IWETH(nativeWrap).deposit{value: _amount}();
        emit Send(transferId, msg.sender, _receiver, nativeWrap, _amount, _dstChainId, _nonce, _maxSlippage);
    }

    function _send(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint64 _nonce,
        uint32 _maxSlippage
    ) private returns (bytes32) {
        require(_amount > minSend[_token], "amount too small");
        require(maxSend[_token] == 0 || _amount <= maxSend[_token], "amount too large");
        require(_maxSlippage > minimalMaxSlippage, "max slippage too small");
        bytes32 transferId = keccak256(
            // uint64(block.chainid) for consistency as entire system uses uint64 for chain id
            // len = 20 + 20 + 20 + 32 + 8 + 8 + 8 = 116
            abi.encodePacked(msg.sender, _receiver, _token, _amount, _dstChainId, _nonce, uint64(block.chainid))
        );
        require(transfers[transferId] == false, "transfer exists");
        transfers[transferId] = true;
        return transferId;
    }

    /**
     * @notice Relay a cross-chain transfer sent from a liquidity pool-based bridge on another chain.
     * @param _relayRequest The serialized Relay protobuf.
     * @param _sigs The list of signatures sorted by signing addresses in ascending order. A relay must be signed-off by
     * +2/3 of the bridge's current signing power to be delivered.
     * @param _signers The sorted list of signers.
     * @param _powers The signing powers of the signers.
     */
    function relay(
        bytes calldata _relayRequest,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "Relay"));
        verifySigs(abi.encodePacked(domain, _relayRequest), _sigs, _signers, _powers);
        PbBridge.Relay memory request = PbBridge.decRelay(_relayRequest);
        // len = 20 + 20 + 20 + 32 + 8 + 8 + 32 = 140
        bytes32 transferId = keccak256(
            abi.encodePacked(
                request.sender,
                request.receiver,
                request.token,
                request.amount,
                request.srcChainId,
                request.dstChainId,
                request.srcTransferId
            )
        );
        require(transfers[transferId] == false, "transfer exists");
        transfers[transferId] = true;
        _updateVolume(request.token, request.amount);
        uint256 delayThreshold = delayThresholds[request.token];
        if (delayThreshold > 0 && request.amount > delayThreshold) {
            _addDelayedTransfer(transferId, request.receiver, request.token, request.amount);
        } else {
            _sendToken(request.receiver, request.token, request.amount);
        }

        emit Relay(
            transferId,
            request.sender,
            request.receiver,
            request.token,
            request.amount,
            request.srcChainId,
            request.srcTransferId
        );
    }

    function setMinSend(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            minSend[_tokens[i]] = _amounts[i];
            emit MinSendUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setMaxSend(address[] calldata _tokens, uint256[] calldata _amounts) external onlyGovernor {
        require(_tokens.length == _amounts.length, "length mismatch");
        for (uint256 i = 0; i < _tokens.length; i++) {
            maxSend[_tokens[i]] = _amounts[i];
            emit MaxSendUpdated(_tokens[i], _amounts[i]);
        }
    }

    function setMinimalMaxSlippage(uint32 _minimalMaxSlippage) external onlyGovernor {
        minimalMaxSlippage = _minimalMaxSlippage;
    }

    // This is needed to receive ETH when calling `IWETH.withdraw`
    receive() external payable {}
}

File 105 of 120 : PbFarming.sol
// SPDX-License-Identifier: GPL-3.0-only

// Code generated by protoc-gen-sol. DO NOT EDIT.
// source: contracts/libraries/proto/farming.proto
pragma solidity 0.8.9;
import "./Pb.sol";

library PbFarming {
    using Pb for Pb.Buffer; // so we can call Pb funcs on Buffer obj

    struct FarmingRewards {
        address recipient; // tag: 1
        address[] tokenAddresses; // tag: 2
        uint256[] cumulativeRewardAmounts; // tag: 3
    } // end struct FarmingRewards

    function decFarmingRewards(bytes memory raw) internal pure returns (FarmingRewards memory m) {
        Pb.Buffer memory buf = Pb.fromBytes(raw);

        uint256[] memory cnts = buf.cntTags(3);
        m.tokenAddresses = new address[](cnts[2]);
        cnts[2] = 0; // reset counter for later use
        m.cumulativeRewardAmounts = new uint256[](cnts[3]);
        cnts[3] = 0; // reset counter for later use

        uint256 tag;
        Pb.WireType wire;
        while (buf.hasMore()) {
            (tag, wire) = buf.decKey();
            if (false) {}
            // solidity has no switch/case
            else if (tag == 1) {
                m.recipient = Pb._address(buf.decBytes());
            } else if (tag == 2) {
                m.tokenAddresses[cnts[2]] = Pb._address(buf.decBytes());
                cnts[2]++;
            } else if (tag == 3) {
                m.cumulativeRewardAmounts[cnts[3]] = Pb._uint256(buf.decBytes());
                cnts[3]++;
            } else {
                buf.skipValue(wire);
            } // skip value of unknown tag
        }
    } // end decoder FarmingRewards
}

File 106 of 120 : FarmingRewards.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/ISigsVerifier.sol";
import "../libraries/PbFarming.sol";
import "../safeguard/Pauser.sol";

/**
 * @title A contract to hold and distribute farming rewards.
 */
contract FarmingRewards is Pauser {
    using SafeERC20 for IERC20;

    ISigsVerifier public immutable sigsVerifier;

    // recipient => tokenAddress => amount
    mapping(address => mapping(address => uint256)) public claimedRewardAmounts;

    event FarmingRewardClaimed(address indexed recipient, address indexed token, uint256 reward);
    event FarmingRewardContributed(address indexed contributor, address indexed token, uint256 contribution);

    constructor(ISigsVerifier _sigsVerifier) {
        sigsVerifier = _sigsVerifier;
    }

    /**
     * @notice Claim rewards
     * @dev Here we use cumulative reward to make claim process idempotent
     * @param _rewardsRequest rewards request bytes coded in protobuf
     * @param _sigs list of signatures sorted by signer addresses in ascending order
     * @param _signers sorted list of current signers
     * @param _powers powers of current signers
     */
    function claimRewards(
        bytes calldata _rewardsRequest,
        bytes[] calldata _sigs,
        address[] calldata _signers,
        uint256[] calldata _powers
    ) external whenNotPaused {
        bytes32 domain = keccak256(abi.encodePacked(block.chainid, address(this), "FarmingRewards"));
        sigsVerifier.verifySigs(abi.encodePacked(domain, _rewardsRequest), _sigs, _signers, _powers);
        PbFarming.FarmingRewards memory rewards = PbFarming.decFarmingRewards(_rewardsRequest);
        bool hasNewReward;
        for (uint256 i = 0; i < rewards.tokenAddresses.length; i++) {
            address token = rewards.tokenAddresses[i];
            uint256 cumulativeRewardAmount = rewards.cumulativeRewardAmounts[i];
            uint256 newReward = cumulativeRewardAmount - claimedRewardAmounts[rewards.recipient][token];
            if (newReward > 0) {
                hasNewReward = true;
                claimedRewardAmounts[rewards.recipient][token] = cumulativeRewardAmount;
                IERC20(token).safeTransfer(rewards.recipient, newReward);
                emit FarmingRewardClaimed(rewards.recipient, token, newReward);
            }
        }
        require(hasNewReward, "No new reward");
    }

    /**
     * @notice Contribute reward tokens to the reward pool
     * @param _token the address of the token to contribute
     * @param _amount the amount of the token to contribute
     */
    function contributeToRewardPool(address _token, uint256 _amount) external whenNotPaused {
        address contributor = msg.sender;
        IERC20(_token).safeTransferFrom(contributor, address(this), _amount);

        emit FarmingRewardContributed(contributor, _token, _amount);
    }

    /**
     * @notice Owner drains tokens when the contract is paused
     * @dev emergency use only
     * @param _token the address of the token to drain
     * @param _amount drained token amount
     */
    function drainToken(address _token, uint256 _amount) external whenPaused onlyOwner {
        IERC20(_token).safeTransfer(msg.sender, _amount);
    }
}

File 107 of 120 : ERC721URIStorage.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)

pragma solidity ^0.8.0;

import "../ERC721.sol";

/**
 * @dev ERC721 token with storage based token URI management.
 */
abstract contract ERC721URIStorage is ERC721 {
    using Strings for uint256;

    // Optional mapping for token URIs
    mapping(uint256 => string) private _tokenURIs;

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");

        string memory _tokenURI = _tokenURIs[tokenId];
        string memory base = _baseURI();

        // If there is no base URI, return the token URI.
        if (bytes(base).length == 0) {
            return _tokenURI;
        }
        // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
        if (bytes(_tokenURI).length > 0) {
            return string(abi.encodePacked(base, _tokenURI));
        }

        return super.tokenURI(tokenId);
    }

    /**
     * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
        require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
        _tokenURIs[tokenId] = _tokenURI;
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual override {
        super._burn(tokenId);

        if (bytes(_tokenURIs[tokenId]).length != 0) {
            delete _tokenURIs[tokenId];
        }
    }
}

File 108 of 120 : PegNFT.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

contract PegNFT is ERC721URIStorage {
    address public immutable nftBridge;

    constructor(
        string memory name_,
        string memory symbol_,
        address _nftBridge
    ) ERC721(name_, symbol_) {
        nftBridge = _nftBridge;
    }

    modifier onlyNftBridge() {
        require(msg.sender == nftBridge, "caller is not bridge");
        _;
    }

    function bridgeMint(
        address to,
        uint256 id,
        string memory uri
    ) external onlyNftBridge {
        _mint(to, id);
        _setTokenURI(id, uri);
    }

    function burn(uint256 id) external onlyNftBridge {
        _burn(id);
    }
}

File 109 of 120 : OrigNFT.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "../../safeguard/Ownable.sol";

contract OrigNFT is ERC721URIStorage, Ownable {
    constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {}

    function mint(
        address to,
        uint256 id,
        string memory uri
    ) external onlyOwner {
        _mint(to, id);
        _setTokenURI(id, uri);
    }
}

File 110 of 120 : MCNNFT.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "../../safeguard/Pauser.sol";

interface INFTBridge {
    function sendMsg(
        uint64 _dstChid,
        address _sender,
        address _receiver,
        uint256 _id,
        string calldata _uri
    ) external payable;

    function sendMsg(
        uint64 _dstChid,
        address _sender,
        bytes calldata _receiver,
        uint256 _id,
        string calldata _uri
    ) external payable;

    function totalFee(
        uint64 _dstChid,
        address _nft,
        uint256 _id
    ) external view returns (uint256);
}

// Multi-Chain Native NFT, same contract on all chains. User interacts with this directly.
contract MCNNFT is ERC721URIStorage, Pauser {
    event NFTBridgeUpdated(address);
    address public nftBridge;

    constructor(
        string memory name_,
        string memory symbol_,
        address _nftBridge
    ) ERC721(name_, symbol_) {
        nftBridge = _nftBridge;
    }

    modifier onlyNftBridge() {
        require(msg.sender == nftBridge, "caller is not bridge");
        _;
    }

    function bridgeMint(
        address to,
        uint256 id,
        string memory uri
    ) external onlyNftBridge {
        _mint(to, id);
        _setTokenURI(id, uri);
    }

    // calls nft bridge to get total fee for crossChain msg.Value
    function totalFee(uint64 _dstChid, uint256 _id) external view returns (uint256) {
        return INFTBridge(nftBridge).totalFee(_dstChid, address(this), _id);
    }

    // called by user, burn token on this chain and mint same id/uri on dest chain
    function crossChain(
        uint64 _dstChid,
        uint256 _id,
        address _receiver
    ) external payable whenNotPaused {
        require(msg.sender == ownerOf(_id), "not token owner");
        string memory _uri = tokenURI(_id);
        _burn(_id);
        INFTBridge(nftBridge).sendMsg{value: msg.value}(_dstChid, msg.sender, _receiver, _id, _uri);
    }

    // support chains using bytes for address
    function crossChain(
        uint64 _dstChid,
        uint256 _id,
        bytes calldata _receiver
    ) external payable whenNotPaused {
        require(msg.sender == ownerOf(_id), "not token owner");
        string memory _uri = tokenURI(_id);
        _burn(_id);
        INFTBridge(nftBridge).sendMsg{value: msg.value}(_dstChid, msg.sender, _receiver, _id, _uri);
    }

    // ===== only Owner
    function mint(
        address to,
        uint256 id,
        string memory uri
    ) external onlyOwner {
        _mint(to, id);
        _setTokenURI(id, uri);
    }

    function setNFTBridge(address _newBridge) public onlyOwner {
        nftBridge = _newBridge;
        emit NFTBridgeUpdated(_newBridge);
    }
}

File 111 of 120 : MintableERC20.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";

/**
 * @title A mintable {ERC20} token.
 */
contract MintableERC20 is ERC20Burnable, Ownable {
    uint8 private _decimals;

    /**
     * @dev Constructor that gives msg.sender an initial supply of tokens.
     */
    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_,
        uint256 initialSupply_
    ) ERC20(name_, symbol_) {
        _decimals = decimals_;
        _mint(msg.sender, initialSupply_);
    }

    /**
     * @dev Creates `amount` new tokens for `to`.
     */
    function mint(address to, uint256 amount) public onlyOwner {
        _mint(to, amount);
    }

    function decimals() public view override returns (uint8) {
        return _decimals;
    }
}

File 112 of 120 : Faucet.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract Faucet is Ownable {
    using SafeERC20 for IERC20;

    uint256 public minDripBlkInterval;
    mapping(address => uint256) public lastDripBlk;

    /**
     * @dev Sends 0.01% of each token to the caller.
     * @param tokens The tokens to drip.
     */
    function drip(address[] calldata tokens) public {
        require(block.number - lastDripBlk[msg.sender] >= minDripBlkInterval, "too frequent");
        for (uint256 i = 0; i < tokens.length; i++) {
            IERC20 token = IERC20(tokens[i]);
            uint256 balance = token.balanceOf(address(this));
            require(balance > 0, "Faucet is empty");
            token.safeTransfer(msg.sender, balance / 10000); // 0.01%
        }
        lastDripBlk[msg.sender] = block.number;
    }

    /**
     * @dev Owner set minDripBlkInterval
     *
     * @param _interval minDripBlkInterval value
     */
    function setMinDripBlkInterval(uint256 _interval) external onlyOwner {
        minDripBlkInterval = _interval;
    }

    /**
     * @dev Owner drains one type of tokens
     *
     * @param _asset drained asset address
     * @param _amount drained asset amount
     */
    function drainToken(address _asset, uint256 _amount) external onlyOwner {
        IERC20(_asset).safeTransfer(msg.sender, _amount);
    }
}

File 113 of 120 : MintSwapCanonicalTokenPermit.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "../MintSwapCanonicalToken.sol";

/**
 * @title MintSwapCanonicalToke with ERC20Permit
 */
contract MintSwapCanonicalTokenPermit is ERC20Permit, MintSwapCanonicalToken {
    uint8 private immutable _decimals;

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) MintSwapCanonicalToken(name_, symbol_, decimals_) ERC20Permit(name_) {
        _decimals = decimals_;
    }

    function decimals() public view override(ERC20, MultiBridgeToken) returns (uint8) {
        return _decimals;
    }
}

File 114 of 120 : MintSwapCanonicalToken.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./MultiBridgeToken.sol";

/**
 * @title Canonical token that supports multi-bridge minter and multi-token swap
 */
contract MintSwapCanonicalToken is MultiBridgeToken {
    using SafeERC20 for IERC20;

    // bridge token address -> minted amount and cap for each bridge
    mapping(address => Supply) public swapSupplies;

    event TokenSwapCapUpdated(address token, uint256 cap);

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) MultiBridgeToken(name_, symbol_, decimals_) {}

    /**
     * @notice msg.sender has bridge token and wants to get canonical token.
     * @param _bridgeToken The intermediary token address for a particular bridge.
     * @param _amount The amount.
     */
    function swapBridgeForCanonical(address _bridgeToken, uint256 _amount) external returns (uint256) {
        Supply storage supply = swapSupplies[_bridgeToken];
        require(supply.cap > 0, "invalid bridge token");
        require(supply.total + _amount < supply.cap, "exceed swap cap");

        supply.total += _amount;
        _mint(msg.sender, _amount);

        // move bridge token from msg.sender to canonical token _amount
        IERC20(_bridgeToken).safeTransferFrom(msg.sender, address(this), _amount);
        return _amount;
    }

    /**
     * @notice msg.sender has canonical token and wants to get bridge token (eg. for cross chain burn).
     * @param _bridgeToken The intermediary token address for a particular bridge.
     * @param _amount The amount.
     */
    function swapCanonicalForBridge(address _bridgeToken, uint256 _amount) external returns (uint256) {
        Supply storage supply = swapSupplies[_bridgeToken];
        require(supply.cap > 0, "invalid bridge token");

        supply.total -= _amount;
        _burn(msg.sender, _amount);

        IERC20(_bridgeToken).safeTransfer(msg.sender, _amount);
        return _amount;
    }

    /**
     * @dev Update existing bridge token swap cap or add a new bridge token with swap cap.
     * Setting cap to 0 will disable the bridge token.
     * @param _bridgeToken The intermediary token address for a particular bridge.
     * @param _swapCap The new swap cap.
     */
    function setBridgeTokenSwapCap(address _bridgeToken, uint256 _swapCap) external onlyOwner {
        swapSupplies[_bridgeToken].cap = _swapCap;
        emit TokenSwapCapUpdated(_bridgeToken, _swapCap);
    }
}

File 115 of 120 : MintSwapCanonicalTokenUpgradable.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity >=0.8.9;

import "./MintSwapCanonicalToken.sol";

/**
 * @title Upgradable canonical token that supports multi-bridge minter and multi-token swap
 */

// First deploy this contract, constructor will set name, symbol and owner in contract state, but these are NOT used.
// decimal isn't saved in state because it's immutable in MultiBridgeToken and will be set in the code binary.
// Then deploy proxy contract with this contract as impl, proxy constructor will delegatecall this.init which sets name, symbol and owner in proxy contract state.
// why we need to shadow name and symbol: ERC20 only allows set them in constructor which isn't available after deploy so proxy state can't be updated.
contract MintSwapCanonicalTokenUpgradable is MintSwapCanonicalToken {
    string private _name;
    string private _symbol;

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) MintSwapCanonicalToken(name_, symbol_, decimals_) {}

    // only to be called by Proxy via delegatecall and will modify Proxy state
    // this func has no access control because initOwner only allows delegateCall
    function init(string memory name_, string memory symbol_) external {
        initOwner(); // this will fail if Ownable._owner is already set
        _name = name_;
        _symbol = symbol_;
    }

    // override name, symbol and owner getters
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }
}

File 116 of 120 : MintSwapCanonicalTokenUpgradableFreezable.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "./Freezable.sol";
import "../MintSwapCanonicalTokenUpgradable.sol";

/**
 * @title Upgradable canonical token that supports multi-bridge minter and multi-token swap. Support freezable erc20 transfer
 */
contract MintSwapCanonicalTokenUpgradableFreezable is MintSwapCanonicalTokenUpgradable, Freezable {
    string private _name;
    string private _symbol;

    constructor(
        string memory name_,
        string memory symbol_,
        uint8 decimals_
    ) MintSwapCanonicalTokenUpgradable(name_, symbol_, decimals_) {}

    // freezable related
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual override {
        super._beforeTokenTransfer(from, to, amount);
        require(!isFrozen(from), "ERC20Freezable: from account is frozen");
        require(!isFrozen(to), "ERC20Freezable: to account is frozen");
    }

    function freeze(address _account) public onlyOwner {
        freezes[_account] = true;
        emit Frozen(_account);
    }

    function unfreeze(address _account) public onlyOwner {
        freezes[_account] = false;
        emit Unfrozen(_account);
    }
}

File 117 of 120 : Freezable.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

abstract contract Freezable {
    event Frozen(address account);
    event Unfrozen(address account);
    mapping(address => bool) internal freezes;

    function isFrozen(address _account) public view virtual returns (bool) {
        return freezes[_account];
    }

    modifier whenAccountNotFrozen(address _account) {
        require(!isFrozen(_account), "Freezable: frozen");
        _;
    }

    modifier whenAccountFrozen(address _account) {
        require(isFrozen(_account), "Freezable: not frozen");
        _;
    }
}

File 118 of 120 : WithdrawInbox.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "../safeguard/Ownable.sol";

/**
 * @title A contract to initiate withdrawal requests for contracts tha provide liquidity to {Bridge}.
 */
contract WithdrawInbox is Ownable {
    // min allowed max slippage uint32 value is slippage * 1M, eg. 0.5% -> 5000
    uint32 public minimalMaxSlippage;
    // the period of time during which a withdrawal request is intended to be valid
    uint256 public validityPeriod;

    // contract LP withdrawal request
    event WithdrawalRequest(
        uint64 seqNum,
        address sender,
        address receiver,
        uint64 toChain,
        uint64[] fromChains,
        address[] tokens,
        uint32[] ratios,
        uint32[] slippages,
        uint256 deadline
    );

    constructor() {
        // default validityPeriod is 2 hours
        validityPeriod = 7200;
    }

    /**
     * @notice Withdraw liquidity from the pool-based bridge.
     * NOTE: Each of your withdrawal request should have different _wdSeq.
     * NOTE: Tokens to withdraw within one withdrawal request should have the same symbol.
     * @param _wdSeq The unique sequence number to identify this withdrawal request.
     * @param _receiver The receiver address on _toChain.
     * @param _toChain The chain Id to receive the withdrawn tokens.
     * @param _fromChains The chain Ids to withdraw tokens.
     * @param _tokens The token to withdraw on each fromChain.
     * @param _ratios The withdrawal ratios of each token.
     * @param _slippages The max slippages of each token for cross-chain withdraw.
     */
    function withdraw(
        uint64 _wdSeq,
        address _receiver,
        uint64 _toChain,
        uint64[] calldata _fromChains,
        address[] calldata _tokens,
        uint32[] calldata _ratios,
        uint32[] calldata _slippages
    ) external {
        require(_fromChains.length > 0, "empty withdrawal request");
        require(
            _tokens.length == _fromChains.length &&
                _ratios.length == _fromChains.length &&
                _slippages.length == _fromChains.length,
            "length mismatch"
        );
        for (uint256 i = 0; i < _ratios.length; i++) {
            require(_ratios[i] > 0 && _ratios[i] <= 1e8, "invalid ratio");
            require(_slippages[i] >= minimalMaxSlippage, "slippage too small");
        }
        uint256 _deadline = block.timestamp + validityPeriod;
        emit WithdrawalRequest(
            _wdSeq,
            msg.sender,
            _receiver,
            _toChain,
            _fromChains,
            _tokens,
            _ratios,
            _slippages,
            _deadline
        );
    }

    // ------------------------Admin operations--------------------------

    function setMinimalMaxSlippage(uint32 _minimalMaxSlippage) external onlyOwner {
        minimalMaxSlippage = _minimalMaxSlippage;
    }

    function setValidityPeriod(uint256 _validityPeriod) external onlyOwner {
        validityPeriod = _validityPeriod;
    }
}

File 119 of 120 : BatchTransfer.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "../framework/MessageSenderApp.sol";
import "../framework/MessageReceiverApp.sol";

/** @title Sample app to test message passing flow, not for production use */
contract BatchTransfer is MessageSenderApp, MessageReceiverApp {
    using SafeERC20 for IERC20;

    struct TransferRequest {
        uint64 nonce;
        address[] accounts;
        uint256[] amounts;
        address sender;
    }

    enum TransferStatus {
        Null,
        Success,
        Fail
    }

    struct TransferReceipt {
        uint64 nonce;
        TransferStatus status;
    }

    constructor(address _messageBus) {
        messageBus = _messageBus;
    }

    // ============== functions and states on source chain ==============

    uint64 nonce;

    struct BatchTransferStatus {
        bytes32 h; // hash(receiver, dstChainId)
        TransferStatus status;
    }
    mapping(uint64 => BatchTransferStatus) public status; // nonce -> BatchTransferStatus

    modifier onlyEOA() {
        require(msg.sender == tx.origin, "Not EOA");
        _;
    }

    function batchTransfer(
        address _receiver,
        address _token,
        uint256 _amount,
        uint64 _dstChainId,
        uint32 _maxSlippage,
        MsgDataTypes.BridgeSendType _bridgeSendType,
        address[] calldata _accounts,
        uint256[] calldata _amounts
    ) external payable onlyEOA {
        uint256 totalAmt;
        for (uint256 i = 0; i < _amounts.length; i++) {
            totalAmt += _amounts[i];
        }
        // commented out the slippage check below to trigger failure case for handleFailedMessageWithTransfer testing
        // uint256 minRecv = _amount - (_amount * _maxSlippage) / 1e6;
        // require(minRecv > totalAmt, "invalid maxSlippage");
        nonce += 1;
        status[nonce] = BatchTransferStatus({
            h: keccak256(abi.encodePacked(_receiver, _dstChainId)),
            status: TransferStatus.Null
        });
        IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
        bytes memory message = abi.encode(
            TransferRequest({nonce: nonce, accounts: _accounts, amounts: _amounts, sender: msg.sender})
        );
        // MsgSenderApp util function
        sendMessageWithTransfer(
            _receiver,
            _token,
            _amount,
            _dstChainId,
            nonce,
            _maxSlippage,
            message,
            _bridgeSendType,
            msg.value
        );
    }

    // called on source chain for handling of bridge failures (bad liquidity, bad slippage, etc...)
    function executeMessageWithTransferRefund(
        address _token,
        uint256 _amount,
        bytes calldata _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        TransferRequest memory transfer = abi.decode((_message), (TransferRequest));
        IERC20(_token).safeTransfer(transfer.sender, _amount);
        return ExecutionStatus.Success;
    }

    // ============== functions on destination chain ==============

    // handler function required by MsgReceiverApp
    function executeMessage(
        address _sender,
        uint64 _srcChainId,
        bytes memory _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        TransferReceipt memory receipt = abi.decode((_message), (TransferReceipt));
        require(status[receipt.nonce].h == keccak256(abi.encodePacked(_sender, _srcChainId)), "invalid message");
        status[receipt.nonce].status = receipt.status;
        return ExecutionStatus.Success;
    }

    // handler function required by MsgReceiverApp
    function executeMessageWithTransfer(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes memory _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        TransferRequest memory transfer = abi.decode((_message), (TransferRequest));
        uint256 totalAmt;
        for (uint256 i = 0; i < transfer.accounts.length; i++) {
            IERC20(_token).safeTransfer(transfer.accounts[i], transfer.amounts[i]);
            totalAmt += transfer.amounts[i];
        }
        uint256 remainder = _amount - totalAmt;
        if (_amount > totalAmt) {
            // transfer the remainder of the money to sender as fee for executing this transfer
            IERC20(_token).safeTransfer(transfer.sender, remainder);
        }
        bytes memory message = abi.encode(TransferReceipt({nonce: transfer.nonce, status: TransferStatus.Success}));
        // MsgSenderApp util function
        sendMessage(_sender, _srcChainId, message, msg.value);
        return ExecutionStatus.Success;
    }

    // handler function required by MsgReceiverApp
    // called only if handleMessageWithTransfer above was reverted
    function executeMessageWithTransferFallback(
        address _sender,
        address _token,
        uint256 _amount,
        uint64 _srcChainId,
        bytes memory _message,
        address // executor
    ) external payable override onlyMessageBus returns (ExecutionStatus) {
        TransferRequest memory transfer = abi.decode((_message), (TransferRequest));
        IERC20(_token).safeTransfer(transfer.sender, _amount);
        bytes memory message = abi.encode(TransferReceipt({nonce: transfer.nonce, status: TransferStatus.Fail}));
        sendMessage(_sender, _srcChainId, message, msg.value);
        return ExecutionStatus.Success;
    }
}

File 120 of 120 : Govern.sol
// SPDX-License-Identifier: GPL-3.0-only

pragma solidity 0.8.9;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypes as dt} from "./DataTypes.sol";
import "./Staking.sol";

/**
 * @title Governance module for Staking contract
 */
contract Govern {
    using SafeERC20 for IERC20;

    Staking public immutable staking;
    IERC20 public immutable celerToken;

    enum ProposalStatus {
        Uninitiated,
        Voting,
        Closed
    }

    enum VoteOption {
        Null,
        Yes,
        Abstain,
        No
    }

    struct ParamProposal {
        address proposer;
        uint256 deposit;
        uint256 voteDeadline;
        dt.ParamName name;
        uint256 newValue;
        ProposalStatus status;
        mapping(address => VoteOption) votes;
    }

    mapping(uint256 => ParamProposal) public paramProposals;
    uint256 public nextParamProposalId;

    uint256 public forfeiture;
    address public immutable collector;

    event CreateParamProposal(
        uint256 proposalId,
        address proposer,
        uint256 deposit,
        uint256 voteDeadline,
        dt.ParamName name,
        uint256 newValue
    );
    event VoteParam(uint256 proposalId, address voter, VoteOption vote);
    event ConfirmParamProposal(uint256 proposalId, bool passed, dt.ParamName name, uint256 newValue);

    constructor(
        Staking _staking,
        address _celerTokenAddress,
        address _collector
    ) {
        staking = _staking;
        celerToken = IERC20(_celerTokenAddress);
        collector = _collector;
    }

    /**
     * @notice Get the vote type of a voter on a parameter proposal
     * @param _proposalId the proposal id
     * @param _voter the voter address
     * @return the vote type of the given voter on the given parameter proposal
     */
    function getParamProposalVote(uint256 _proposalId, address _voter) public view returns (VoteOption) {
        return paramProposals[_proposalId].votes[_voter];
    }

    /**
     * @notice Create a parameter proposal
     * @param _name the key of this parameter
     * @param _value the new proposed value of this parameter
     */
    function createParamProposal(dt.ParamName _name, uint256 _value) external {
        ParamProposal storage p = paramProposals[nextParamProposalId];
        nextParamProposalId = nextParamProposalId + 1;
        address msgSender = msg.sender;
        uint256 deposit = staking.getParamValue(dt.ParamName.ProposalDeposit);

        p.proposer = msgSender;
        p.deposit = deposit;
        p.voteDeadline = block.number + staking.getParamValue(dt.ParamName.VotingPeriod);
        p.name = _name;
        p.newValue = _value;
        p.status = ProposalStatus.Voting;

        celerToken.safeTransferFrom(msgSender, address(this), deposit);

        emit CreateParamProposal(nextParamProposalId - 1, msgSender, deposit, p.voteDeadline, _name, _value);
    }

    /**
     * @notice Vote for a parameter proposal with a specific type of vote
     * @param _proposalId the id of the parameter proposal
     * @param _vote the type of vote
     */
    function voteParam(uint256 _proposalId, VoteOption _vote) external {
        address valAddr = msg.sender;
        require(staking.getValidatorStatus(valAddr) == dt.ValidatorStatus.Bonded, "Voter is not a bonded validator");
        ParamProposal storage p = paramProposals[_proposalId];
        require(p.status == ProposalStatus.Voting, "Invalid proposal status");
        require(block.number < p.voteDeadline, "Vote deadline passed");
        require(p.votes[valAddr] == VoteOption.Null, "Voter has voted");
        require(_vote != VoteOption.Null, "Invalid vote");

        p.votes[valAddr] = _vote;

        emit VoteParam(_proposalId, valAddr, _vote);
    }

    /**
     * @notice Confirm a parameter proposal
     * @param _proposalId the id of the parameter proposal
     */
    function confirmParamProposal(uint256 _proposalId) external {
        uint256 yesVotes;
        uint256 bondedTokens;
        dt.ValidatorTokens[] memory validators = staking.getBondedValidatorsTokens();
        for (uint32 i = 0; i < validators.length; i++) {
            if (getParamProposalVote(_proposalId, validators[i].valAddr) == VoteOption.Yes) {
                yesVotes += validators[i].tokens;
            }
            bondedTokens += validators[i].tokens;
        }
        bool passed = (yesVotes >= (bondedTokens * 2) / 3 + 1);

        ParamProposal storage p = paramProposals[_proposalId];
        require(p.status == ProposalStatus.Voting, "Invalid proposal status");
        require(block.number >= p.voteDeadline, "Vote deadline not reached");

        p.status = ProposalStatus.Closed;
        if (passed) {
            staking.setParamValue(p.name, p.newValue);
            celerToken.safeTransfer(p.proposer, p.deposit);
        } else {
            forfeiture += p.deposit;
        }

        emit ConfirmParamProposal(_proposalId, passed, p.name, p.newValue);
    }

    function collectForfeiture() external {
        require(forfeiture > 0, "Nothing to collect");
        celerToken.safeTransfer(collector, forfeiture);
        forfeiture = 0;
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 800
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "abi"
      ]
    }
  },
  "metadata": {
    "useLiteralContent": true
  }
}

Contract ABI

[{"inputs":[{"internalType":"contract ISigsVerifier","name":"_sigsVerifier","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"burnId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint64","name":"toChainId","type":"uint64"},{"indexed":false,"internalType":"address","name":"toAccount","type":"address"},{"indexed":false,"internalType":"uint64","name":"nonce","type":"uint64"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"period","type":"uint256"}],"name":"DelayPeriodUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"threshold","type":"uint256"}],"name":"DelayThresholdUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"DelayedTransferAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"id","type":"bytes32"},{"indexed":false,"internalType":"address","name":"receiver","type":"address"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"DelayedTransferExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"length","type":"uint256"}],"name":"EpochLengthUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"cap","type":"uint256"}],"name":"EpochVolumeUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"GovernorAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"GovernorRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"MaxBurnUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"MinBurnUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"mintId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint64","name":"refChainId","type":"uint64"},{"indexed":false,"internalType":"bytes32","name":"refId","type":"bytes32"},{"indexed":false,"internalType":"address","name":"depositor","type":"address"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"PauserAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"PauserRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"uint256","name":"supply","type":"uint256"}],"name":"SupplyUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"addGovernor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"addPauser","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint64","name":"_toChainId","type":"uint64"},{"internalType":"address","name":"_toAccount","type":"address"},{"internalType":"uint64","name":"_nonce","type":"uint64"}],"name":"burn","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"uint64","name":"_toChainId","type":"uint64"},{"internalType":"address","name":"_toAccount","type":"address"},{"internalType":"uint64","name":"_nonce","type":"uint64"}],"name":"burnFrom","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_delta","type":"uint256"}],"name":"decreaseSupply","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"delayPeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"delayThresholds","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"delayedTransfers","outputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"timestamp","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"epochLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"epochVolumeCaps","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"epochVolumes","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"id","type":"bytes32"}],"name":"executeDelayedTransfer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"governors","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_delta","type":"uint256"}],"name":"increaseSupply","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"isGovernor","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"isPauser","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"lastOpTimestamps","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"maxBurn","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"minBurn","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"_request","type":"bytes"},{"internalType":"bytes[]","name":"_sigs","type":"bytes[]"},{"internalType":"address[]","name":"_signers","type":"address[]"},{"internalType":"uint256[]","name":"_powers","type":"uint256[]"}],"name":"mint","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"pausers","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"records","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"removeGovernor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"removePauser","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceGovernor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renouncePauser","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_period","type":"uint256"}],"name":"setDelayPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_tokens","type":"address[]"},{"internalType":"uint256[]","name":"_thresholds","type":"uint256[]"}],"name":"setDelayThresholds","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_length","type":"uint256"}],"name":"setEpochLength","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_tokens","type":"address[]"},{"internalType":"uint256[]","name":"_caps","type":"uint256[]"}],"name":"setEpochVolumeCaps","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_tokens","type":"address[]"},{"internalType":"uint256[]","name":"_amounts","type":"uint256[]"}],"name":"setMaxBurn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"_tokens","type":"address[]"},{"internalType":"uint256[]","name":"_amounts","type":"uint256[]"}],"name":"setMinBurn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"},{"internalType":"uint256","name":"_supply","type":"uint256"}],"name":"setSupply","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sigsVerifier","outputs":[{"internalType":"contract ISigsVerifier","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"supplies","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60a06040523480156200001157600080fd5b50604051620032123803806200321283398101604081905262000034916200024f565b6200003f3362000074565b6000805460ff60a01b191690556200005733620000c4565b62000062336200018f565b6001600160a01b031660805262000281565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b03811660009081526001602052604090205460ff1615620001335760405162461bcd60e51b815260206004820152601960248201527f4163636f756e7420697320616c7265616479207061757365720000000000000060448201526064015b60405180910390fd5b6001600160a01b038116600081815260016020818152604092839020805460ff191690921790915590519182527f6719d08c1888103bea251a4ed56406bd0c3e69723c8a1686e017e7bbe159b6f891015b60405180910390a150565b6001600160a01b03811660009081526002602052604090205460ff1615620001fa5760405162461bcd60e51b815260206004820152601b60248201527f4163636f756e7420697320616c726561647920676f7665726e6f72000000000060448201526064016200012a565b6001600160a01b038116600081815260026020908152604091829020805460ff1916600117905590519182527fdc5a48d79e2e147530ff63ecdbed5a5a66adb9d5cf339384d5d076da197c40b5910162000184565b6000602082840312156200026257600080fd5b81516001600160a01b03811681146200027a57600080fd5b9392505050565b608051612f6e620002a460003960008181610601015261157b0152612f6e6000f3fe608060405234801561001057600080fd5b50600436106102c85760003560e01c806382dc1ec41161017b578063bf4816f0116100d8578063eecdac881161008c578063f832138311610071578063f8321383146106a0578063f8734302146106c0578063f9a8ea08146106d357600080fd5b8063eecdac881461067a578063f2fde38b1461068d57600080fd5b8063e026049c116100bd578063e026049c14610623578063e3eece261461062b578063e43581b81461064e57600080fd5b8063bf4816f0146105e9578063ccf2683b146105fc57600080fd5b8063a00293011161012f578063b1c94d9411610114578063b1c94d94146105ad578063b4d8cedc146105b6578063b5f2bc47146105c957600080fd5b8063a00293011461052d578063adc0d57f1461054057600080fd5b80638da5cb5b116101605780638da5cb5b146104e25780639e25fc5c146105075780639e422c331461051a57600080fd5b806382dc1ec4146104c75780638456cb59146104da57600080fd5b806352532faa116102295780636b2c0f55116101dd57806379fcd8ee116101c257806379fcd8ee146104715780637f8560131461048457806380f51c12146104a457600080fd5b80636b2c0f55146104565780636ef8d66d1461046957600080fd5b806357d775f81161020e57806357d775f81461041b5780635c975abb1461042457806360216b001461043657600080fd5b806352532faa146103e857806354eea7961461040857600080fd5b80633d5721071161028057806346fbf68e1161026557806346fbf68e1461038957806347b16c6c146103b5578063497bf3b2146103c857600080fd5b80633d5721071461036e5780633f4ba83a1461038157600080fd5b806317bdbae5116102b157806317bdbae51461031a578063274cee311461032d5780633c4a25d01461035b57600080fd5b806301e64725146102cd57806315d0975c14610305575b600080fd5b6102f06102db3660046129b4565b600a6020526000908152604090205460ff1681565b60405190151581526020015b60405180910390f35b6103186103133660046129e9565b6106e6565b005b610318610328366004612a5f565b6107d7565b61034d61033b366004612acb565b600b6020526000908152604090205481565b6040519081526020016102fc565b610318610369366004612acb565b610975565b61031861037c3660046129b4565b6109ea565b610318610a7e565b6102f0610397366004612acb565b6001600160a01b031660009081526001602052604090205460ff1690565b6103186103c3366004612a5f565b610ae7565b61034d6103d6366004612acb565b600d6020526000908152604090205481565b61034d6103f6366004612acb565b60086020526000908152604090205481565b6103186104163660046129b4565b610c7e565b61034d60035481565b600054600160a01b900460ff166102f0565b61034d610444366004612acb565b60046020526000908152604090205481565b610318610464366004612acb565b610d0b565b610318610d7d565b61031861047f3660046129e9565b610d86565b61034d610492366004612acb565b600c6020526000908152604090205481565b6102f06104b2366004612acb565b60016020526000908152604090205460ff1681565b6103186104d5366004612acb565b610e17565b610318610e89565b6000546001600160a01b03165b6040516001600160a01b0390911681526020016102fc565b6103186105153660046129b4565b610ef0565b61034d610528366004612b05565b610fbd565b61034d61053b366004612b05565b611089565b61058261054e3660046129b4565b60076020526000908152604090208054600182015460028301546003909301546001600160a01b0392831693919092169184565b604080516001600160a01b0395861681529490931660208501529183015260608201526080016102fc565b61034d60095481565b6103186105c43660046129e9565b61111c565b61034d6105d7366004612acb565b60056020526000908152604090205481565b6103186105f7366004612a5f565b6111d6565b6104ef7f000000000000000000000000000000000000000000000000000000000000000081565b61031861136d565b6102f0610639366004612acb565b60026020526000908152604090205460ff1681565b6102f061065c366004612acb565b6001600160a01b031660009081526002602052604090205460ff1690565b610318610688366004612acb565b611376565b61031861069b366004612acb565b6113e8565b61034d6106ae366004612acb565b60066020526000908152604090205481565b61034d6106ce366004612b63565b6114d6565b6103186106e1366004612a5f565b611921565b336106f96000546001600160a01b031690565b6001600160a01b0316146107545760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064015b60405180910390fd5b6001600160a01b0382166000908152600b60205260408120805483929061077c908490612c68565b90915550506001600160a01b0382166000818152600b6020908152604091829020548251938452908301527feb2f7272b55acd6dea98f5742868e8d2221ad82acb36b2d0cdd00150290e949991015b60405180910390a15050565b3360009081526002602052604090205460ff1661082f5760405162461bcd60e51b815260206004820152601660248201527521b0b63632b91034b9903737ba1033b7bb32b93737b960511b604482015260640161074b565b8281146108705760405162461bcd60e51b815260206004820152600f60248201526e0d8cadccee8d040dad2e6dac2e8c6d608b1b604482015260640161074b565b60005b8381101561096e5782828281811061088d5761088d612c7f565b90506020020135600860008787858181106108aa576108aa612c7f565b90506020020160208101906108bf9190612acb565b6001600160a01b031681526020810191909152604001600020557fceaad6533bfb481492fb3e08ef19297f46611b8fa9de5ef4cf8dc23a56ad09ce85858381811061090c5761090c612c7f565b90506020020160208101906109219190612acb565b84848481811061093357610933612c7f565b604080516001600160a01b0390951685526020918202939093013590840152500160405180910390a18061096681612c95565b915050610873565b5050505050565b336109886000546001600160a01b031690565b6001600160a01b0316146109de5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161074b565b6109e781611ab8565b50565b3360009081526002602052604090205460ff16610a425760405162461bcd60e51b815260206004820152601660248201527521b0b63632b91034b9903737ba1033b7bb32b93737b960511b604482015260640161074b565b60098190556040518181527fc0a39f234199b125fb93713c4d067bdcebbf691087f87b79c0feb92b156ba8b6906020015b60405180910390a150565b3360009081526001602052604090205460ff16610add5760405162461bcd60e51b815260206004820152601460248201527f43616c6c6572206973206e6f7420706175736572000000000000000000000000604482015260640161074b565b610ae5611b75565b565b3360009081526002602052604090205460ff16610b3f5760405162461bcd60e51b815260206004820152601660248201527521b0b63632b91034b9903737ba1033b7bb32b93737b960511b604482015260640161074b565b828114610b805760405162461bcd60e51b815260206004820152600f60248201526e0d8cadccee8d040dad2e6dac2e8c6d608b1b604482015260640161074b565b60005b8381101561096e57828282818110610b9d57610b9d612c7f565b9050602002013560056000878785818110610bba57610bba612c7f565b9050602002016020810190610bcf9190612acb565b6001600160a01b031681526020810191909152604001600020557f608e49c22994f20b5d3496dca088b88dfd81b4a3e8cc3809ea1e10a320107e89858583818110610c1c57610c1c612c7f565b9050602002016020810190610c319190612acb565b848484818110610c4357610c43612c7f565b604080516001600160a01b0390951685526020918202939093013590840152500160405180910390a180610c7681612c95565b915050610b83565b3360009081526002602052604090205460ff16610cd65760405162461bcd60e51b815260206004820152601660248201527521b0b63632b91034b9903737ba1033b7bb32b93737b960511b604482015260640161074b565b60038190556040518181527f2664fec2ff76486ac58ed087310855b648b15b9d19f3de8529e95f7c46b7d6b390602001610a73565b33610d1e6000546001600160a01b031690565b6001600160a01b031614610d745760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161074b565b6109e781611c1b565b610ae533611c1b565b33610d996000546001600160a01b031690565b6001600160a01b031614610def5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161074b565b6001600160a01b0382166000908152600b60205260408120805483929061077c908490612cb0565b33610e2a6000546001600160a01b031690565b6001600160a01b031614610e805760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161074b565b6109e781611cd4565b3360009081526001602052604090205460ff16610ee85760405162461bcd60e51b815260206004820152601460248201527f43616c6c6572206973206e6f7420706175736572000000000000000000000000604482015260640161074b565b610ae5611d92565b600054600160a01b900460ff1615610f3d5760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015260640161074b565b6000610f4882611e1a565b6020810151815160408084015190516340c10f1960e01b81526001600160a01b039283166004820152602481019190915292935016906340c10f1990604401600060405180830381600087803b158015610fa157600080fd5b505af1158015610fb5573d6000803e3d6000fd5b505050505050565b60008054600160a01b900460ff161561100b5760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015260640161074b565b600061101a8787878787611fec565b60405163079cc67960e41b8152336004820152602481018890529091506001600160a01b038816906379cc6790906044015b600060405180830381600087803b15801561106657600080fd5b505af115801561107a573d6000803e3d6000fd5b50929998505050505050505050565b60008054600160a01b900460ff16156110d75760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015260640161074b565b60006110e68787878787611fec565b604051632770a7eb60e21b8152336004820152602481018890529091506001600160a01b03881690639dc29fac9060440161104c565b3361112f6000546001600160a01b031690565b6001600160a01b0316146111855760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161074b565b6001600160a01b0382166000818152600b6020908152604091829020849055815192835282018390527feb2f7272b55acd6dea98f5742868e8d2221ad82acb36b2d0cdd00150290e949991016107cb565b3360009081526002602052604090205460ff1661122e5760405162461bcd60e51b815260206004820152601660248201527521b0b63632b91034b9903737ba1033b7bb32b93737b960511b604482015260640161074b565b82811461126f5760405162461bcd60e51b815260206004820152600f60248201526e0d8cadccee8d040dad2e6dac2e8c6d608b1b604482015260640161074b565b60005b8381101561096e5782828281811061128c5761128c612c7f565b90506020020135600c60008787858181106112a9576112a9612c7f565b90506020020160208101906112be9190612acb565b6001600160a01b031681526020810191909152604001600020557f3796cd0b17a8734f8da819920625598e9a18be490f686725282e5383f1d0668385858381811061130b5761130b612c7f565b90506020020160208101906113209190612acb565b84848481811061133257611332612c7f565b604080516001600160a01b0390951685526020918202939093013590840152500160405180910390a18061136581612c95565b915050611272565b610ae53361228c565b336113896000546001600160a01b031690565b6001600160a01b0316146113df5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161074b565b6109e78161228c565b336113fb6000546001600160a01b031690565b6001600160a01b0316146114515760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161074b565b6001600160a01b0381166114cd5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f6464726573730000000000000000000000000000000000000000000000000000606482015260840161074b565b6109e781612345565b60008054600160a01b900460ff16156115245760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015260640161074b565b6000463060405160200161156192919091825260601b6bffffffffffffffffffffffff1916602082015263135a5b9d60e21b603482015260380190565b6040516020818303038152906040528051906020012090507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663682dbc22828c8c6040516020016115bd93929190612cc8565b6040516020818303038152906040528a8a8a8a8a8a6040518863ffffffff1660e01b81526004016115f49796959493929190612e2f565b60006040518083038186803b15801561160c57600080fd5b505afa158015611620573d6000803e3d6000fd5b5050505060006116658b8b8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506123a292505050565b6020818101518251604080850151606080870151608088015160a089015185516bffffffffffffffffffffffff1998851b8916818b015296841b88166034880152604887019490945290821b8616606886015277ffffffffffffffffffffffffffffffffffffffffffffffff1960c09190911b16607c850152608484019190915230901b90921660a48201528151808203609801815260b890910182528051908301206000818152600a9093529120549192509060ff16156117595760405162461bcd60e51b815260206004820152600d60248201526c7265636f72642065786973747360981b604482015260640161074b565b6000818152600a602052604090819020805460ff191660011790558251908301516117849190612504565b81516001600160a01b031660009081526008602052604090205480158015906117b05750808360400151115b156117d2576117cd8284602001518560000151866040015161261c565b611842565b8251602084015160408086015190516340c10f1960e01b81526001600160a01b03928316600482015260248101919091529116906340c10f1990604401600060405180830381600087803b15801561182957600080fd5b505af115801561183d573d6000803e3d6000fd5b505050505b60408084015184516001600160a01b03166000908152600b602052918220805491929091611871908490612cb0565b925050819055507f5bc84ecccfced5bb04bfc7f3efcdbe7f5cd21949ef146811b4d1967fe41f777a8284600001518560200151866040015187608001518860a00151896060015160405161190997969594939291909687526001600160a01b0395861660208801529385166040870152606086019290925267ffffffffffffffff16608085015260a08401521660c082015260e00190565b60405180910390a1509b9a5050505050505050505050565b3360009081526002602052604090205460ff166119795760405162461bcd60e51b815260206004820152601660248201527521b0b63632b91034b9903737ba1033b7bb32b93737b960511b604482015260640161074b565b8281146119ba5760405162461bcd60e51b815260206004820152600f60248201526e0d8cadccee8d040dad2e6dac2e8c6d608b1b604482015260640161074b565b60005b8381101561096e578282828181106119d7576119d7612c7f565b90506020020135600d60008787858181106119f4576119f4612c7f565b9050602002016020810190611a099190612acb565b6001600160a01b031681526020810191909152604001600020557fa3181379f6db47d9037efc6b6e8e3efe8c55ddb090b4f0512c152f97c4e47da5858583818110611a5657611a56612c7f565b9050602002016020810190611a6b9190612acb565b848484818110611a7d57611a7d612c7f565b604080516001600160a01b0390951685526020918202939093013590840152500160405180910390a180611ab081612c95565b9150506119bd565b6001600160a01b03811660009081526002602052604090205460ff1615611b215760405162461bcd60e51b815260206004820152601b60248201527f4163636f756e7420697320616c726561647920676f7665726e6f720000000000604482015260640161074b565b6001600160a01b038116600081815260026020908152604091829020805460ff1916600117905590519182527fdc5a48d79e2e147530ff63ecdbed5a5a66adb9d5cf339384d5d076da197c40b59101610a73565b600054600160a01b900460ff16611bce5760405162461bcd60e51b815260206004820152601460248201527f5061757361626c653a206e6f7420706175736564000000000000000000000000604482015260640161074b565b6000805460ff60a01b191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b6001600160a01b03811660009081526001602052604090205460ff16611c835760405162461bcd60e51b815260206004820152601560248201527f4163636f756e74206973206e6f74207061757365720000000000000000000000604482015260640161074b565b6001600160a01b038116600081815260016020908152604091829020805460ff1916905590519182527fcd265ebaf09df2871cc7bd4133404a235ba12eff2041bb89d9c714a2621c7c7e9101610a73565b6001600160a01b03811660009081526001602052604090205460ff1615611d3d5760405162461bcd60e51b815260206004820152601960248201527f4163636f756e7420697320616c72656164792070617573657200000000000000604482015260640161074b565b6001600160a01b038116600081815260016020818152604092839020805460ff191690921790915590519182527f6719d08c1888103bea251a4ed56406bd0c3e69723c8a1686e017e7bbe159b6f89101610a73565b600054600160a01b900460ff1615611ddf5760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015260640161074b565b6000805460ff60a01b1916600160a01b1790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611bfe3390565b604080516080810182526000808252602082018190529181018290526060810191909152600082815260076020908152604091829020825160808101845281546001600160a01b0390811682526001830154169281019290925260028101549282019290925260039091015460608201819052611ed95760405162461bcd60e51b815260206004820152601a60248201527f64656c61796564207472616e73666572206e6f74206578697374000000000000604482015260640161074b565b6009548160600151611eeb9190612cb0565b4211611f395760405162461bcd60e51b815260206004820152601d60248201527f64656c61796564207472616e73666572207374696c6c206c6f636b6564000000604482015260640161074b565b6000838152600760209081526040808320805473ffffffffffffffffffffffffffffffffffffffff199081168255600182018054909116905560028101849055600301929092558251908301518383015192517f3b40e5089937425d14cdd96947e5661868357e224af59bd8b24a4b8a330d442693611fde93889390929091909384526001600160a01b03928316602085015291166040830152606082015260800190565b60405180910390a192915050565b6001600160a01b0385166000908152600c602052604081205485116120535760405162461bcd60e51b815260206004820152601060248201527f616d6f756e7420746f6f20736d616c6c00000000000000000000000000000000604482015260640161074b565b6001600160a01b0386166000908152600d6020526040902054158061209057506001600160a01b0386166000908152600d60205260409020548511155b6120dc5760405162461bcd60e51b815260206004820152601060248201527f616d6f756e7420746f6f206c6172676500000000000000000000000000000000604482015260640161074b565b6001600160a01b0386166000908152600b602052604081208054879290612104908490612c68565b90915550506040516bffffffffffffffffffffffff1933606090811b8216602084015288811b821660348401526048830188905277ffffffffffffffffffffffffffffffffffffffffffffffff1960c088811b8216606886015287831b8416607086015286811b8216608486015246901b16608c84015230901b16609482015260009060a80160408051601f1981840301815291815281516020928301206000818152600a90935291205490915060ff16156121f25760405162461bcd60e51b815260206004820152600d60248201526c7265636f72642065786973747360981b604482015260640161074b565b6000818152600a6020908152604091829020805460ff1916600117905581518381526001600160a01b038a81169282019290925233928101929092526060820188905267ffffffffffffffff878116608084015290861660a0830152841660c08201527f6298d7b58f235730b3b399dc5c282f15dae8b022e5fbbf89cee21fd83c8810a39060e00160405180910390a19695505050505050565b6001600160a01b03811660009081526002602052604090205460ff166122f45760405162461bcd60e51b815260206004820152601760248201527f4163636f756e74206973206e6f7420676f7665726e6f72000000000000000000604482015260640161074b565b6001600160a01b038116600081815260026020908152604091829020805460ff1916905590519182527f1ebe834e73d60a5fec822c1e1727d34bc79f2ad977ed504581cc1822fe20fb5b9101610a73565b600080546001600160a01b0383811673ffffffffffffffffffffffffffffffffffffffff19831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6040805160c08101825260008082526020808301829052828401829052606083018290526080830182905260a0830182905283518085019094528184528301849052909190805b602083015151835110156124fc576124008361273c565b9092509050816001141561242f5761241f61241a84612776565b612833565b6001600160a01b031684526123e9565b81600214156124575761244461241a84612776565b6001600160a01b031660208501526123e9565b816003141561247b5761247161246c84612776565b612844565b60408501526123e9565b81600414156124a35761249061241a84612776565b6001600160a01b031660608501526123e9565b81600514156124c9576124b58361287b565b67ffffffffffffffff1660808501526123e9565b81600614156124ed576124e36124de84612776565b6128fd565b60a08501526123e9565b6124f78382612915565b6123e9565b505050919050565b60035461250f575050565b6001600160a01b0382166000908152600560205260409020548061253257505050565b6001600160a01b0383166000908152600460205260408120546003549091429161255c8184612ecb565b6125669190612eed565b6001600160a01b0387166000908152600660205260409020549091508111156125915784925061259e565b61259b8584612cb0565b92505b838311156125ee5760405162461bcd60e51b815260206004820152601260248201527f766f6c756d652065786365656473206361700000000000000000000000000000604482015260640161074b565b506001600160a01b039094166000908152600460209081526040808320939093556006905220929092555050565b6000848152600760205260409020600301541561267b5760405162461bcd60e51b815260206004820152601f60248201527f64656c61796564207472616e7366657220616c72656164792065786973747300604482015260640161074b565b604080516080810182526001600160a01b0380861682528481166020808401918252838501868152426060860190815260008b81526007909352918690209451855490851673ffffffffffffffffffffffffffffffffffffffff1991821617865592516001860180549190951693169290921790925551600283015551600390910155517fcbcfffe5102114216a85d3aceb14ad4b81a3935b1b5c468fadf3889eb9c5dce69061272e9086815260200190565b60405180910390a150505050565b600080600061274a8461287b565b9050612757600882612ecb565b925080600716600581111561276e5761276e612f0c565b915050915091565b606060006127838361287b565b905060008184600001516127979190612cb0565b90508360200151518111156127ab57600080fd5b8167ffffffffffffffff8111156127c4576127c4612f22565b6040519080825280601f01601f1916602001820160405280156127ee576020820181803683370190505b50602080860151865192955091818601919083010160005b85811015612828578181015183820152612821602082612cb0565b9050612806565b505050935250919050565b600061283e8261298c565b92915050565b600060208251111561285557600080fd5b602082015190508151602061286a9190612c68565b612875906008612eed565b1c919050565b602080820151825181019091015160009182805b600a8110156128f75783811a91506128a8816007612eed565b82607f16901b8517945081608016600014156128e5576128c9816001612cb0565b865187906128d8908390612cb0565b9052509395945050505050565b806128ef81612c95565b91505061288f565b50600080fd5b6000815160201461290d57600080fd5b506020015190565b600081600581111561292957612929612f0c565b141561293d576129388261287b565b505050565b600281600581111561295157612951612f0c565b14156102c85760006129628361287b565b905080836000018181516129769190612cb0565b9052506020830151518351111561293857600080fd5b6000815160141461299c57600080fd5b50602001516c01000000000000000000000000900490565b6000602082840312156129c657600080fd5b5035919050565b80356001600160a01b03811681146129e457600080fd5b919050565b600080604083850312156129fc57600080fd5b612a05836129cd565b946020939093013593505050565b60008083601f840112612a2557600080fd5b50813567ffffffffffffffff811115612a3d57600080fd5b6020830191508360208260051b8501011115612a5857600080fd5b9250929050565b60008060008060408587031215612a7557600080fd5b843567ffffffffffffffff80821115612a8d57600080fd5b612a9988838901612a13565b90965094506020870135915080821115612ab257600080fd5b50612abf87828801612a13565b95989497509550505050565b600060208284031215612add57600080fd5b612ae6826129cd565b9392505050565b803567ffffffffffffffff811681146129e457600080fd5b600080600080600060a08688031215612b1d57600080fd5b612b26866129cd565b945060208601359350612b3b60408701612aed565b9250612b49606087016129cd565b9150612b5760808701612aed565b90509295509295909350565b6000806000806000806000806080898b031215612b7f57600080fd5b883567ffffffffffffffff80821115612b9757600080fd5b818b0191508b601f830112612bab57600080fd5b813581811115612bba57600080fd5b8c6020828501011115612bcc57600080fd5b60209283019a509850908a01359080821115612be757600080fd5b612bf38c838d01612a13565b909850965060408b0135915080821115612c0c57600080fd5b612c188c838d01612a13565b909650945060608b0135915080821115612c3157600080fd5b50612c3e8b828c01612a13565b999c989b5096995094979396929594505050565b634e487b7160e01b600052601160045260246000fd5b600082821015612c7a57612c7a612c52565b500390565b634e487b7160e01b600052603260045260246000fd5b6000600019821415612ca957612ca9612c52565b5060010190565b60008219821115612cc357612cc3612c52565b500190565b838152818360208301376000910160200190815292915050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b818352600060208085019450848460051b86018460005b87811015612d8c5783830389528135601e19883603018112612d4357600080fd5b8701803567ffffffffffffffff811115612d5c57600080fd5b803603891315612d6b57600080fd5b612d788582898501612ce2565b9a87019a9450505090840190600101612d22565b5090979650505050505050565b8183526000602080850194508260005b85811015612dd5576001600160a01b03612dc2836129cd565b1687529582019590820190600101612da9565b509495945050505050565b81835260007f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115612e1257600080fd5b8260051b8083602087013760009401602001938452509192915050565b608081526000885180608084015260005b81811015612e5d576020818c0181015160a0868401015201612e40565b81811115612e6f57600060a083860101525b50601f01601f1916820182810360a09081016020850152612e93908201898b612d0b565b90508281036040840152612ea8818789612d99565b90508281036060840152612ebd818587612de0565b9a9950505050505050505050565b600082612ee857634e487b7160e01b600052601260045260246000fd5b500490565b6000816000190483118215151615612f0757612f07612c52565b500290565b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052604160045260246000fdfea26469706673582212207f0483041017bb51352e4769b343fd0edbacc1fa8e07370faab4de961b1252de64736f6c63430008090033000000000000000000000000841ce48f9446c8e281d3f1444cb859b4a6d0738c

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

000000000000000000000000841ce48f9446c8e281d3f1444cb859b4a6d0738c

-----Decoded View---------------
Arg [0] : _sigsVerifier (address): 0x841ce48f9446c8e281d3f1444cb859b4a6d0738c

-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 000000000000000000000000841ce48f9446c8e281d3f1444cb859b4a6d0738c


Deployed ByteCode Sourcemap

495:7379:87:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;622:39;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;364:14:120;;357:22;339:41;;327:2;312:18;622:39:87;;;;;;;;7700:172;;;;;;:::i;:::-;;:::i;:::-;;702:382:105;;;;;;:::i;:::-;;:::i;667:43:87:-;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;2338:25:120;;;2326:2;2311:18;667:43:87;2192:177:120;560:95:106;;;;;;:::i;:::-;;:::i;1090:143:105:-;;;;;;:::i;:::-;;:::i;562:64:108:-;;;:::i;632:102::-;;;;;;:::i;:::-;-1:-1:-1;;;;;711:16:108;688:4;711:16;;;:7;:16;;;;;;;;;632:102;654:355:109;;;;;;:::i;:::-;;:::i;765:42:87:-;;;;;;:::i;:::-;;;;;;;;;;;;;;344:50:105;;;;;;:::i;:::-;;;;;;;;;;;;;;505:143:109;;;;;;:::i;:::-;;:::i;142:26::-;;;;;;1098:84:1;1145:4;1168:7;-1:-1:-1;;;1168:7:1;;;;1098:84;;185:47:109;;;;;;:::i;:::-;;;;;;;;;;;;;;835:95:108;;;;;;:::i;:::-;;:::i;936:75::-;;;:::i;7522:172:87:-;;;;;;:::i;:::-;;:::i;717:42::-;;;;;;:::i;:::-;;;;;;;;;;;;;;199:39:108;;;;;;:::i;:::-;;;;;;;;;;;;;;;;740:89;;;;;;:::i;:::-;;:::i;496:60::-;;;:::i;1479:85:107:-;1525:7;1551:6;-1:-1:-1;;;;;1551:6:107;1479:85;;;-1:-1:-1;;;;;2723:55:120;;;2705:74;;2693:2;2678:18;1479:85:107;2559:226:120;6421:224:87;;;;;;:::i;:::-;;:::i;5085:371::-;;;;;;:::i;:::-;;:::i;4652:355::-;;;;;;:::i;:::-;;:::i;279:59:105:-;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;279:59:105;;;;;;;;;;;;;;;-1:-1:-1;;;;;3937:15:120;;;3919:34;;3989:15;;;;3984:2;3969:18;;3962:43;4021:18;;;4014:34;4079:2;4064:18;;4057:34;3845:3;3830:19;279:59:105;3627:470:120;400:26:105;;;;;;7357:159:87;;;;;;:::i;:::-;;:::i;254:50:109:-;;;;;;:::i;:::-;;;;;;;;;;;;;;6651:347:87;;;;;;:::i;:::-;;:::i;572:43::-;;;;;768:79:106;;;:::i;135:41::-;;;;;;:::i;:::-;;;;;;;;;;;;;;;;446:108;;;;;;:::i;:::-;-1:-1:-1;;;;;528:19:106;505:4;528:19;;;:9;:19;;;;;;;;;446:108;661:101;;;;;;:::i;:::-;;:::i;1916:189:107:-;;;;;;:::i;:::-;;:::i;326:51:109:-;;;;;;:::i;:::-;;;;;;;;;;;;;;2406:1610:87;;;;;;:::i;:::-;;:::i;7004:347::-;;;;;;:::i;:::-;;:::i;7700:172::-;1702:10:107;1691:7;1525;1551:6;-1:-1:-1;;;;;1551:6:107;;1479:85;1691:7;-1:-1:-1;;;;;1691:21:107;;1683:66;;;;-1:-1:-1;;;1683:66:107;;6116:2:120;1683:66:107;;;6098:21:120;;;6135:18;;;6128:30;6194:34;6174:18;;;6167:62;6246:18;;1683:66:107;;;;;;;;;-1:-1:-1;;;;;7785:16:87;::::1;;::::0;;;:8:::1;:16;::::0;;;;:26;;7805:6;;7785:16;:26:::1;::::0;7805:6;;7785:26:::1;:::i;:::-;::::0;;;-1:-1:-1;;;;;;;7848:16:87;::::1;;::::0;;;:8:::1;:16;::::0;;;;;;;;;7826:39;;6711:74:120;;;6801:18;;;6794:34;7826:39:87::1;::::0;6684:18:120;7826:39:87::1;;;;;;;;7700:172:::0;;:::o;702:382:105:-;323:10:106;505:4;528:19;;;:9;:19;;;;;;;;304:57;;;;-1:-1:-1;;;304:57:106;;7041:2:120;304:57:106;;;7023:21:120;7080:2;7060:18;;;7053:30;-1:-1:-1;;;7099:18:120;;;7092:52;7161:18;;304:57:106;6839:346:120;304:57:106;830:36:105;;::::1;822:64;;;::::0;-1:-1:-1;;;822:64:105;;7392:2:120;822:64:105::1;::::0;::::1;7374:21:120::0;7431:2;7411:18;;;7404:30;-1:-1:-1;;;7450:18:120;;;7443:45;7505:18;;822:64:105::1;7190:339:120::0;822:64:105::1;901:9;896:182;916:18:::0;;::::1;896:182;;;985:11;;997:1;985:14;;;;;;;:::i;:::-;;;;;;;955:15;:27;971:7;;979:1;971:10;;;;;;;:::i;:::-;;;;;;;;;;;;;;:::i;:::-;-1:-1:-1::0;;;;;955:27:105::1;::::0;;::::1;::::0;::::1;::::0;;;;;;-1:-1:-1;955:27:105;:44;1018:49:::1;1040:7:::0;;1048:1;1040:10;;::::1;;;;;:::i;:::-;;;;;;;;;;;;;;:::i;:::-;1052:11;;1064:1;1052:14;;;;;;;:::i;:::-;1018:49;::::0;;-1:-1:-1;;;;;6729:55:120;;;6711:74;;1052:14:105::1;::::0;;::::1;::::0;;;::::1;;6801:18:120::0;;;6794:34;-1:-1:-1;6684:18:120;1018:49:105::1;;;;;;;936:3:::0;::::1;::::0;::::1;:::i;:::-;;;;896:182;;;;702:382:::0;;;;:::o;560:95:106:-;1702:10:107;1691:7;1525;1551:6;-1:-1:-1;;;;;1551:6:107;;1479:85;1691:7;-1:-1:-1;;;;;1691:21:107;;1683:66;;;;-1:-1:-1;;;1683:66:107;;6116:2:120;1683:66:107;;;6098:21:120;;;6135:18;;;6128:30;6194:34;6174:18;;;6167:62;6246:18;;1683:66:107;5914:356:120;1683:66:107;626:22:106::1;639:8;626:12;:22::i;:::-;560:95:::0;:::o;1090:143:105:-;323:10:106;505:4;528:19;;;:9;:19;;;;;;;;304:57;;;;-1:-1:-1;;;304:57:106;;7041:2:120;304:57:106;;;7023:21:120;7080:2;7060:18;;;7053:30;-1:-1:-1;;;7099:18:120;;;7092:52;7161:18;;304:57:106;6839:346:120;304:57:106;1163:11:105::1;:21:::0;;;1199:27:::1;::::0;2338:25:120;;;1199:27:105::1;::::0;2326:2:120;2311:18;1199:27:105::1;;;;;;;;1090:143:::0;:::o;562:64:108:-;436:10;688:4;711:16;;;:7;:16;;;;;;;;419:53;;;;-1:-1:-1;;;419:53:108;;8008:2:120;419:53:108;;;7990:21:120;8047:2;8027:18;;;8020:30;8086:22;8066:18;;;8059:50;8126:18;;419:53:108;7806:344:120;419:53:108;609:10:::1;:8;:10::i;:::-;562:64::o:0;654:355:109:-;323:10:106;505:4;528:19;;;:9;:19;;;;;;;;304:57;;;;-1:-1:-1;;;304:57:106;;7041:2:120;304:57:106;;;7023:21:120;7080:2;7060:18;;;7053:30;-1:-1:-1;;;7099:18:120;;;7092:52;7161:18;;304:57:106;6839:346:120;304:57:106;776:30:109;;::::1;768:58;;;::::0;-1:-1:-1;;;768:58:109;;7392:2:120;768:58:109::1;::::0;::::1;7374:21:120::0;7431:2;7411:18;;;7404:30;-1:-1:-1;;;7450:18:120;;;7443:45;7505:18;;768:58:109::1;7190:339:120::0;768:58:109::1;841:9;836:167;856:18:::0;;::::1;836:167;;;925:5;;931:1;925:8;;;;;;;:::i;:::-;;;;;;;895:15;:27;911:7;;919:1;911:10;;;;;;;:::i;:::-;;;;;;;;;;;;;;:::i;:::-;-1:-1:-1::0;;;;;895:27:109::1;::::0;;::::1;::::0;::::1;::::0;;;;;;-1:-1:-1;895:27:109;:38;952:40:::1;971:7:::0;;979:1;971:10;;::::1;;;;;:::i;:::-;;;;;;;;;;;;;;:::i;:::-;983:5;;989:1;983:8;;;;;;;:::i;:::-;952:40;::::0;;-1:-1:-1;;;;;6729:55:120;;;6711:74;;983:8:109::1;::::0;;::::1;::::0;;;::::1;;6801:18:120::0;;;6794:34;-1:-1:-1;6684:18:120;952:40:109::1;;;;;;;876:3:::0;::::1;::::0;::::1;:::i;:::-;;;;836:167;;505:143:::0;323:10:106;505:4;528:19;;;:9;:19;;;;;;;;304:57;;;;-1:-1:-1;;;304:57:106;;7041:2:120;304:57:106;;;7023:21:120;7080:2;7060:18;;;7053:30;-1:-1:-1;;;7099:18:120;;;7092:52;7161:18;;304:57:106;6839:346:120;304:57:106;578:11:109::1;:21:::0;;;614:27:::1;::::0;2338:25:120;;;614:27:109::1;::::0;2326:2:120;2311:18;614:27:109::1;2192:177:120::0;835:95:108;1702:10:107;1691:7;1525;1551:6;-1:-1:-1;;;;;1551:6:107;;1479:85;1691:7;-1:-1:-1;;;;;1691:21:107;;1683:66;;;;-1:-1:-1;;;1683:66:107;;6116:2:120;1683:66:107;;;6098:21:120;;;6135:18;;;6128:30;6194:34;6174:18;;;6167:62;6246:18;;1683:66:107;5914:356:120;1683:66:107;901:22:108::1;915:7;901:13;:22::i;936:75::-:0;979:25;993:10;979:13;:25::i;7522:172:87:-;1702:10:107;1691:7;1525;1551:6;-1:-1:-1;;;;;1551:6:107;;1479:85;1691:7;-1:-1:-1;;;;;1691:21:107;;1683:66;;;;-1:-1:-1;;;1683:66:107;;6116:2:120;1683:66:107;;;6098:21:120;;;6135:18;;;6128:30;6194:34;6174:18;;;6167:62;6246:18;;1683:66:107;5914:356:120;1683:66:107;-1:-1:-1;;;;;7607:16:87;::::1;;::::0;;;:8:::1;:16;::::0;;;;:26;;7627:6;;7607:16;:26:::1;::::0;7627:6;;7607:26:::1;:::i;740:89:108:-:0;1702:10:107;1691:7;1525;1551:6;-1:-1:-1;;;;;1551:6:107;;1479:85;1691:7;-1:-1:-1;;;;;1691:21:107;;1683:66;;;;-1:-1:-1;;;1683:66:107;;6116:2:120;1683:66:107;;;6098:21:120;;;6135:18;;;6128:30;6194:34;6174:18;;;6167:62;6246:18;;1683:66:107;5914:356:120;1683:66:107;803:19:108::1;814:7;803:10;:19::i;496:60::-:0;436:10;688:4;711:16;;;:7;:16;;;;;;;;419:53;;;;-1:-1:-1;;;419:53:108;;8008:2:120;419:53:108;;;7990:21:120;8047:2;8027:18;;;8020:30;8086:22;8066:18;;;8059:50;8126:18;;419:53:108;7806:344:120;419:53:108;541:8:::1;:6;:8::i;6421:224:87:-:0;1145:4:1;1168:7;-1:-1:-1;;;1168:7:1;;;;1411:9;1403:38;;;;-1:-1:-1;;;1403:38:1;;8490:2:120;1403:38:1;;;8472:21:120;8529:2;8509:18;;;8502:30;-1:-1:-1;;;8548:18:120;;;8541:46;8604:18;;1403:38:1;8288:340:120;1403:38:1;6498:31:87::1;6532:27;6556:2;6532:23;:27::i;:::-;6582:14;::::0;::::1;::::0;6603:17;;6622:15:::1;::::0;;::::1;::::0;6569:69;;-1:-1:-1;;;6569:69:87;;-1:-1:-1;;;;;6729:55:120;;;6569:69:87::1;::::0;::::1;6711:74:120::0;6801:18;;;6794:34;;;;6582:14:87;;-1:-1:-1;6569:33:87::1;::::0;::::1;::::0;6684:18:120;;6569:69:87::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;6488:157;6421:224:::0;:::o;5085:371::-;5268:7;1168::1;;-1:-1:-1;;;1168:7:1;;;;1411:9;1403:38;;;;-1:-1:-1;;;1403:38:1;;8490:2:120;1403:38:1;;;8472:21:120;8529:2;8509:18;;;8502:30;-1:-1:-1;;;8548:18:120;;;8541:46;8604:18;;1403:38:1;8288:340:120;1403:38:1;5287:14:87::1;5304:54;5310:6;5318:7;5327:10;5339;5351:6;5304:5;:54::i;:::-;5368:58;::::0;-1:-1:-1;;;5368:58:87;;5406:10:::1;5368:58;::::0;::::1;6711:74:120::0;6801:18;;;6794:34;;;5287:71:87;;-1:-1:-1;;;;;;5368:37:87;::::1;::::0;::::1;::::0;6684:18:120;;5368:58:87::1;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;-1:-1:-1::0;5443:6:87;;5085:371;-1:-1:-1;;;;;;;;;5085:371:87:o;4652:355::-;4831:7;1168::1;;-1:-1:-1;;;1168:7:1;;;;1411:9;1403:38;;;;-1:-1:-1;;;1403:38:1;;8490:2:120;1403:38:1;;;8472:21:120;8529:2;8509:18;;;8502:30;-1:-1:-1;;;8548:18:120;;;8541:46;8604:18;;1403:38:1;8288:340:120;1403:38:1;4850:14:87::1;4867:54;4873:6;4881:7;4890:10;4902;4914:6;4867:5;:54::i;:::-;4931:46;::::0;-1:-1:-1;;;4931:46:87;;4957:10:::1;4931:46;::::0;::::1;6711:74:120::0;6801:18;;;6794:34;;;4850:71:87;;-1:-1:-1;;;;;;4931:25:87;::::1;::::0;::::1;::::0;6684:18:120;;4931:46:87::1;6537:297:120::0;7357:159:87;1702:10:107;1691:7;1525;1551:6;-1:-1:-1;;;;;1551:6:107;;1479:85;1691:7;-1:-1:-1;;;;;1691:21:107;;1683:66;;;;-1:-1:-1;;;1683:66:107;;6116:2:120;1683:66:107;;;6098:21:120;;;6135:18;;;6128:30;6194:34;6174:18;;;6167:62;6246:18;;1683:66:107;5914:356:120;1683:66:107;-1:-1:-1;;;;;7438:16:87;::::1;;::::0;;;:8:::1;:16;::::0;;;;;;;;:26;;;7479:30;;6711:74:120;;;6801:18;;6794:34;;;7479:30:87::1;::::0;6684:18:120;7479:30:87::1;6537:297:120::0;6651:347:87;323:10:106;505:4;528:19;;;:9;:19;;;;;;;;304:57;;;;-1:-1:-1;;;304:57:106;;7041:2:120;304:57:106;;;7023:21:120;7080:2;7060:18;;;7053:30;-1:-1:-1;;;7099:18:120;;;7092:52;7161:18;;304:57:106;6839:346:120;304:57:106;6768:33:87;;::::1;6760:61;;;::::0;-1:-1:-1;;;6760:61:87;;7392:2:120;6760:61:87::1;::::0;::::1;7374:21:120::0;7431:2;7411:18;;;7404:30;-1:-1:-1;;;7450:18:120;;;7443:45;7505:18;;6760:61:87::1;7190:339:120::0;6760:61:87::1;6836:9;6831:161;6851:18:::0;;::::1;6831:161;;;6912:8;;6921:1;6912:11;;;;;;;:::i;:::-;;;;;;;6890:7;:19;6898:7;;6906:1;6898:10;;;;;;;:::i;:::-;;;;;;;;;;;;;;:::i;:::-;-1:-1:-1::0;;;;;6890:19:87::1;::::0;;::::1;::::0;::::1;::::0;;;;;;-1:-1:-1;6890:19:87;:33;6942:39:::1;6957:7:::0;;6965:1;6957:10;;::::1;;;;;:::i;:::-;;;;;;;;;;;;;;:::i;:::-;6969:8;;6978:1;6969:11;;;;;;;:::i;:::-;6942:39;::::0;;-1:-1:-1;;;;;6729:55:120;;;6711:74;;6969:11:87::1;::::0;;::::1;::::0;;;::::1;;6801:18:120::0;;;6794:34;-1:-1:-1;6684:18:120;6942:39:87::1;;;;;;;6871:3:::0;::::1;::::0;::::1;:::i;:::-;;;;6831:161;;768:79:106::0;813:27;829:10;813:15;:27::i;661:101::-;1702:10:107;1691:7;1525;1551:6;-1:-1:-1;;;;;1551:6:107;;1479:85;1691:7;-1:-1:-1;;;;;1691:21:107;;1683:66;;;;-1:-1:-1;;;1683:66:107;;6116:2:120;1683:66:107;;;6098:21:120;;;6135:18;;;6128:30;6194:34;6174:18;;;6167:62;6246:18;;1683:66:107;5914:356:120;1683:66:107;730:25:106::1;746:8;730:15;:25::i;1916:189:107:-:0;1702:10;1691:7;1525;1551:6;-1:-1:-1;;;;;1551:6:107;;1479:85;1691:7;-1:-1:-1;;;;;1691:21:107;;1683:66;;;;-1:-1:-1;;;1683:66:107;;6116:2:120;1683:66:107;;;6098:21:120;;;6135:18;;;6128:30;6194:34;6174:18;;;6167:62;6246:18;;1683:66:107;5914:356:120;1683:66:107;-1:-1:-1;;;;;2004:22:107;::::1;1996:73;;;::::0;-1:-1:-1;;;1996:73:107;;8835:2:120;1996:73:107::1;::::0;::::1;8817:21:120::0;8874:2;8854:18;;;8847:30;8913:34;8893:18;;;8886:62;8984:8;8964:18;;;8957:36;9010:19;;1996:73:107::1;8633:402:120::0;1996:73:107::1;2079:19;2089:8;2079:9;:19::i;2406:1610:87:-:0;2596:7;1168::1;;-1:-1:-1;;;1168:7:1;;;;1411:9;1403:38;;;;-1:-1:-1;;;1403:38:1;;8490:2:120;1403:38:1;;;8472:21:120;8529:2;8509:18;;;8502:30;-1:-1:-1;;;8548:18:120;;;8541:46;8604:18;;1403:38:1;8288:340:120;1403:38:1;2615:14:87::1;2659:13;2682:4;2642:54;;;;;;;;9298:19:120::0;;;9355:2;9351:15;-1:-1:-1;;9347:53:120;9342:2;9333:12;;9326:75;-1:-1:-1;;;9426:2:120;9417:12;;9410:28;9463:2;9454:12;;9040:432;2642:54:87::1;;;;;;;;;;;;;2632:65;;;;;;2615:82;;2707:12;-1:-1:-1::0;;;;;2707:23:87::1;;2748:6;2756:8;;2731:34;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;2767:5;;2774:8;;2784:7;;2707:85;;;;;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;2802:28;2833:26;2850:8;;2833:26;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;::::0;::::1;::::0;;;;-1:-1:-1;2833:16:87::1;::::0;-1:-1:-1;;;2833:26:87:i:1;:::-;3002:15;::::0;;::::1;::::0;3035:13;;3066:14:::1;::::0;;::::1;::::0;3098:17:::1;::::0;;::::1;::::0;3133:18:::1;::::0;::::1;::::0;3169:13:::1;::::0;::::1;::::0;2968:259;;-1:-1:-1;;13634:15:120;;;13630:24;;2968:259:87;;::::1;13618:37:120::0;13689:15;;;13685:24;;13671:12;;;13664:46;13726:12;;;13719:28;;;;13781:15;;;13777:24;;13763:12;;;13756:46;-1:-1:-1;;13840:3:120;13836:16;;;;13832:89;13818:12;;;13811:111;13938:13;;;13931:29;;;;3208:4:87::1;13995:15:120::0;;13991:24;;;13976:13;;;13969:47;2968:259:87;;;;;;;;;14032:13:120;;;;2968:259:87;;2886:351;;;;::::1;::::0;-1:-1:-1;3255:15:87;;;:7:::1;:15:::0;;;;;;3002;;-1:-1:-1;2886:351:87;3255:15:::1;;:24;3247:50;;;::::0;-1:-1:-1;;;3247:50:87;;14258:2:120;3247:50:87::1;::::0;::::1;14240:21:120::0;14297:2;14277:18;;;14270:30;-1:-1:-1;;;14316:18:120;;;14309:43;14369:18;;3247:50:87::1;14056:337:120::0;3247:50:87::1;3307:15;::::0;;;:7:::1;:15;::::0;;;;;;:22;;-1:-1:-1;;3307:22:87::1;3325:4;3307:22;::::0;;3353:13;;3368:14;;::::1;::::0;3339:44:::1;::::0;3353:13;3339::::1;:44::i;:::-;3434:13:::0;;-1:-1:-1;;;;;3418:30:87::1;3393:22;3418:30:::0;;;:15:::1;:30;::::0;;;;;3462:18;;;;;:53:::1;;;3501:14;3484:7;:14;;;:31;3462:53;3458:255;;;3531:75;3551:6;3559:7;:15;;;3576:7;:13;;;3591:7;:14;;;3531:19;:75::i;:::-;3458:255;;;3650:13:::0;;3670:15:::1;::::0;::::1;::::0;3687:14:::1;::::0;;::::1;::::0;3637:65;;-1:-1:-1;;;3637:65:87;;-1:-1:-1;;;;;6729:55:120;;;3637:65:87::1;::::0;::::1;6711:74:120::0;6801:18;;;6794:34;;;;3637:32:87;::::1;::::0;::::1;::::0;6684:18:120;;3637:65:87::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;3458:255;3749:14;::::0;;::::1;::::0;3731:13;;-1:-1:-1;;;;;3722:23:87::1;;::::0;;;:8:::1;:23;::::0;;;;:41;;3749:14;;3722:23;;:41:::1;::::0;3749:14;;3722:41:::1;:::i;:::-;;;;;;;;3778:208;3796:6;3816:7;:13;;;3843:7;:15;;;3872:7;:14;;;3900:7;:18;;;3932:7;:13;;;3959:7;:17;;;3778:208;;;;;;;;;;;14711:25:120::0;;;-1:-1:-1;;;;;14833:15:120;;;14828:2;14813:18;;14806:43;14885:15;;;14880:2;14865:18;;14858:43;14932:2;14917:18;;14910:34;;;;14993:18;14981:31;14975:3;14960:19;;14953:60;15044:3;15029:19;;15022:35;15094:15;15088:3;15073:19;;15066:44;14698:3;14683:19;;14398:718;3778:208:87::1;;;;;;;;-1:-1:-1::0;4003:6:87;2406:1610;-1:-1:-1;;;;;;;;;;;2406:1610:87:o;7004:347::-;323:10:106;505:4;528:19;;;:9;:19;;;;;;;;304:57;;;;-1:-1:-1;;;304:57:106;;7041:2:120;304:57:106;;;7023:21:120;7080:2;7060:18;;;7053:30;-1:-1:-1;;;7099:18:120;;;7092:52;7161:18;;304:57:106;6839:346:120;304:57:106;7121:33:87;;::::1;7113:61;;;::::0;-1:-1:-1;;;7113:61:87;;7392:2:120;7113:61:87::1;::::0;::::1;7374:21:120::0;7431:2;7411:18;;;7404:30;-1:-1:-1;;;7450:18:120;;;7443:45;7505:18;;7113:61:87::1;7190:339:120::0;7113:61:87::1;7189:9;7184:161;7204:18:::0;;::::1;7184:161;;;7265:8;;7274:1;7265:11;;;;;;;:::i;:::-;;;;;;;7243:7;:19;7251:7;;7259:1;7251:10;;;;;;;:::i;:::-;;;;;;;;;;;;;;:::i;:::-;-1:-1:-1::0;;;;;7243:19:87::1;::::0;;::::1;::::0;::::1;::::0;;;;;;-1:-1:-1;7243:19:87;:33;7295:39:::1;7310:7:::0;;7318:1;7310:10;;::::1;;;;;:::i;:::-;;;;;;;;;;;;;;:::i;:::-;7322:8;;7331:1;7322:11;;;;;;;:::i;:::-;7295:39;::::0;;-1:-1:-1;;;;;6729:55:120;;;6711:74;;7322:11:87::1;::::0;;::::1;::::0;;;::::1;;6801:18:120::0;;;6794:34;-1:-1:-1;6684:18:120;7295:39:87::1;;;;;;;7224:3:::0;::::1;::::0;::::1;:::i;:::-;;;;7184:161;;853:200:106::0;-1:-1:-1;;;;;528:19:106;;505:4;528:19;;;:9;:19;;;;;;;;919:21;911:61;;;;-1:-1:-1;;;911:61:106;;15323:2:120;911:61:106;;;15305:21:120;15362:2;15342:18;;;15335:30;15401:29;15381:18;;;15374:57;15448:18;;911:61:106;15121:351:120;911:61:106;-1:-1:-1;;;;;982:19:106;;;;;;:9;:19;;;;;;;;;:26;;-1:-1:-1;;982:26:106;1004:4;982:26;;;1023:23;;2705:74:120;;;1023:23:106;;2678:18:120;1023:23:106;2559:226:120;2110:117:1;1145:4;1168:7;-1:-1:-1;;;1168:7:1;;;;1669:41;;;;-1:-1:-1;;;1669:41:1;;15679:2:120;1669:41:1;;;15661:21:120;15718:2;15698:18;;;15691:30;15757:22;15737:18;;;15730:50;15797:18;;1669:41:1;15477:344:120;1669:41:1;2178:5:::1;2168:15:::0;;-1:-1:-1;;;;2168:15:1::1;::::0;;2198:22:::1;719:10:16::0;2207:12:1::1;2198:22;::::0;-1:-1:-1;;;;;2723:55:120;;;2705:74;;2693:2;2678:18;2198:22:1::1;;;;;;;2110:117::o:0;1209:187:108:-;-1:-1:-1;;;;;711:16:108;;688:4;711:16;;;:7;:16;;;;;;;;1267:51;;;;-1:-1:-1;;;1267:51:108;;16028:2:120;1267:51:108;;;16010:21:120;16067:2;16047:18;;;16040:30;16106:23;16086:18;;;16079:51;16147:18;;1267:51:108;15826:345:120;1267:51:108;-1:-1:-1;;;;;1328:16:108;;1347:5;1328:16;;;:7;:16;;;;;;;;;:24;;-1:-1:-1;;1328:24:108;;;1367:22;;2705:74:120;;;1367:22:108;;2678:18:120;1367:22:108;2559:226:120;1017:186:108;-1:-1:-1;;;;;711:16:108;;688:4;711:16;;;:7;:16;;;;;;;;1080:18;1072:56;;;;-1:-1:-1;;;1072:56:108;;16378:2:120;1072:56:108;;;16360:21:120;16417:2;16397:18;;;16390:30;16456:27;16436:18;;;16429:55;16501:18;;1072:56:108;16176:349:120;1072:56:108;-1:-1:-1;;;;;1138:16:108;;;;;;1157:4;1138:16;;;;;;;;;:23;;-1:-1:-1;;1138:23:108;;;;;;;1176:20;;2705:74:120;;;1176:20:108;;2678:18:120;1176:20:108;2559:226:120;1863:115:1;1145:4;1168:7;-1:-1:-1;;;1168:7:1;;;;1411:9;1403:38;;;;-1:-1:-1;;;1403:38:1;;8490:2:120;1403:38:1;;;8472:21:120;8529:2;8509:18;;;8502:30;-1:-1:-1;;;8548:18:120;;;8541:46;8604:18;;1403:38:1;8288:340:120;1403:38:1;1922:7:::1;:14:::0;;-1:-1:-1;;;;1922:14:1::1;-1:-1:-1::0;;;1922:14:1::1;::::0;;1951:20:::1;1958:12;719:10:16::0;;640:96;1755:487:105;-1:-1:-1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1852:31:105;1886:20;;;:16;:20;;;;;;;;;1852:54;;;;;;;;;-1:-1:-1;;;;;1852:54:105;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1916:61;;;;-1:-1:-1;;;1916:61:105;;16732:2:120;1916:61:105;;;16714:21:120;16771:2;16751:18;;;16744:30;16810:28;16790:18;;;16783:56;16856:18;;1916:61:105;16530:350:120;1916:61:105;2034:11;;2013:8;:18;;;:32;;;;:::i;:::-;1995:15;:50;1987:92;;;;-1:-1:-1;;;1987:92:105;;17087:2:120;1987:92:105;;;17069:21:120;17126:2;17106:18;;;17099:30;17165:31;17145:18;;;17138:59;17214:18;;1987:92:105;16885:353:120;1987:92:105;2096:20;;;;:16;:20;;;;;;;;2089:27;;-1:-1:-1;;2089:27:105;;;;;;;;;;;;;;;;;;;;;;;;;;;2159:17;;2178:14;;;;2194:15;;;;2131:79;;;;;;2113:2;;2159:17;;2178:14;;2194:15;17474:25:120;;;-1:-1:-1;;;;;17596:15:120;;;17591:2;17576:18;;17569:43;17648:15;;17643:2;17628:18;;17621:43;17695:2;17680:18;;17673:34;17461:3;17446:19;;17243:470;2131:79:105;;;;;;;;2227:8;1755:487;-1:-1:-1;;1755:487:105:o;5462:953:87:-;-1:-1:-1;;;;;5664:15:87;;5627:7;5664:15;;;:7;:15;;;;;;5654:25;;5646:54;;;;-1:-1:-1;;;5646:54:87;;17920:2:120;5646:54:87;;;17902:21:120;17959:2;17939:18;;;17932:30;17998:18;17978;;;17971:46;18034:18;;5646:54:87;17718:340:120;5646:54:87;-1:-1:-1;;;;;5718:15:87;;;;;;:7;:15;;;;;;:20;;:50;;-1:-1:-1;;;;;;5753:15:87;;;;;;:7;:15;;;;;;5742:26;;;5718:50;5710:79;;;;-1:-1:-1;;;5710:79:87;;18265:2:120;5710:79:87;;;18247:21:120;18304:2;18284:18;;;18277:30;18343:18;18323;;;18316:46;18379:18;;5710:79:87;18063:340:120;5710:79:87;-1:-1:-1;;;;;5799:16:87;;;;;;:8;:16;;;;;:27;;5819:7;;5799:16;:27;;5819:7;;5799:27;:::i;:::-;;;;-1:-1:-1;;5938:257:87;;-1:-1:-1;;5972:10:87;18797:2:120;18793:15;;;18789:24;;5938:257:87;;;18777:37:120;18848:15;;;18844:24;;18830:12;;;18823:46;18885:12;;;18878:28;;;-1:-1:-1;;19029:3:120;19025:16;;;19021:25;;19007:12;;;19000:47;19081:15;;;19077:24;;19063:12;;;19056:46;19137:16;;;19133:25;;19118:13;;;19111:48;6136:13:87;19194:16:120;;19190:25;19175:13;;;19168:48;6176:4:87;19251:15:120;;19247:24;19232:13;;;19225:47;5836:14:87;;19288:13:120;;5938:257:87;;;-1:-1:-1;;5938:257:87;;;;;;;;;5853:352;;5938:257;5853:352;;;;6223:15;;;;:7;:15;;;;;;5853:352;;-1:-1:-1;6223:15:87;;:24;6215:50;;;;-1:-1:-1;;;6215:50:87;;14258:2:120;6215:50:87;;;14240:21:120;14297:2;14277:18;;;14270:30;-1:-1:-1;;;14316:18:120;;;14309:43;14369:18;;6215:50:87;14056:337:120;6215:50:87;6275:15;;;;:7;:15;;;;;;;;;:22;;-1:-1:-1;;6275:22:87;6293:4;6275:22;;;6312:73;;19623:25:120;;;-1:-1:-1;;;;;19745:15:120;;;19725:18;;;19718:43;;;;6333:10:87;19777:18:120;;;19770:43;;;;19844:2;19829:18;;19822:34;;;19875:18;19930:15;;;19924:3;19909:19;;19902:44;19983:15;;;19977:3;19962:19;;19955:44;20036:15;;20030:3;20015:19;;20008:44;6312:73:87;;19610:3:120;19595:19;6312:73:87;;;;;;;6402:6;5462:953;-1:-1:-1;;;;;;5462:953:87:o;1059:201:106:-;-1:-1:-1;;;;;528:19:106;;505:4;528:19;;;:9;:19;;;;;;;;1120:56;;;;-1:-1:-1;;;1120:56:106;;20265:2:120;1120:56:106;;;20247:21:120;20304:2;20284:18;;;20277:30;20343:25;20323:18;;;20316:53;20386:18;;1120:56:106;20063:347:120;1120:56:106;-1:-1:-1;;;;;1186:19:106;;1208:5;1186:19;;;:9;:19;;;;;;;;;:27;;-1:-1:-1;;1186:27:106;;;1228:25;;2705:74:120;;;1228:25:106;;2678:18:120;1228:25:106;2559:226:120;2111:169:107;2166:16;2185:6;;-1:-1:-1;;;;;2201:17:107;;;-1:-1:-1;;2201:17:107;;;;;;2233:40;;2185:6;;;;;;;2233:40;;2166:16;2233:40;2156:124;2111:169;:::o;531:976:55:-;-1:-1:-1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;566:11:52;;;-1:-1:-1;;;;712:789:55;741:5:52;;;;:12;731:7;;:22;712:789:55;;;762:12;:3;:10;:12::i;:::-;748:26;;-1:-1:-1;748:26:55;-1:-1:-1;866:3:55;873:1;866:8;862:600;;;904:27;916:14;:3;:12;:14::i;:::-;904:11;:27::i;:::-;-1:-1:-1;;;;;894:37:55;;;712:789;;862:600;956:3;963:1;956:8;952:510;;;996:27;1008:14;:3;:12;:14::i;996:27::-;-1:-1:-1;;;;;984:39:55;:9;;;:39;712:789;;952:510;1048:3;1055:1;1048:8;1044:418;;;1087:27;1099:14;:3;:12;:14::i;:::-;1087:11;:27::i;:::-;1076:8;;;:38;712:789;;1044:418;1139:3;1146:1;1139:8;1135:327;;;1181:27;1193:14;:3;:12;:14::i;1181:27::-;-1:-1:-1;;;;;1167:41:55;:11;;;:41;712:789;;1135:327;1233:3;1240:1;1233:8;1229:233;;;1283:15;:3;:13;:15::i;:::-;1261:38;;:12;;;:38;712:789;;1229:233;1324:3;1331:1;1324:8;1320:142;;;1362:27;1374:14;:3;:12;:14::i;:::-;1362:11;:27::i;:::-;1352:7;;;:37;712:789;;1320:142;1428:19;:3;1442:4;1428:13;:19::i;:::-;712:789;;;604:903;;;531:976;;;:::o;1015:685:109:-;1094:11;;1090:53;;1015:685;;:::o;1090:53::-;-1:-1:-1;;;;;1166:23:109;;1152:11;1166:23;;;:15;:23;;;;;;1203:8;1199:45;;1227:7;1015:685;;:::o;1199:45::-;-1:-1:-1;;;;;1270:20:109;;1253:14;1270:20;;;:12;:20;;;;;;1398:11;;1270:20;;1320:15;;1371:23;1398:11;1320:15;1371:23;:::i;:::-;1370:39;;;;:::i;:::-;-1:-1:-1;;;;;1423:24:109;;;;;;:16;:24;;;;;;1345:64;;-1:-1:-1;1423:41:109;-1:-1:-1;1419:136:109;;;1489:7;1480:16;;1419:136;;;1527:17;1537:7;1527:17;;:::i;:::-;;;1419:136;1582:3;1572:6;:13;;1564:44;;;;-1:-1:-1;;;1564:44:109;;21012:2:120;1564:44:109;;;20994:21:120;21051:2;21031:18;;;21024:30;21090:20;21070:18;;;21063:48;21128:18;;1564:44:109;20810:342:120;1564:44:109;-1:-1:-1;;;;;;1618:20:109;;;;;;;:12;:20;;;;;;;;:29;;;;1657:16;:24;;;:36;;;;-1:-1:-1;;1015:685:109:o;1239:458:105:-;1394:20;;;;:16;:20;;;;;:30;;;:35;1386:79;;;;-1:-1:-1;;;1386:79:105;;21359:2:120;1386:79:105;;;21341:21:120;21398:2;21378:18;;;21371:30;21437:33;21417:18;;;21410:61;21488:18;;1386:79:105;21157:355:120;1386:79:105;1498:153;;;;;;;;-1:-1:-1;;;;;1498:153:105;;;;;;;;;;;;;;;;;;;;;1625:15;1498:153;;;;;;-1:-1:-1;1475:20:105;;;:16;:20;;;;;;;:176;;;;;;;-1:-1:-1;;1475:176:105;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1666:24;;;;;1492:2;2338:25:120;;2326:2;2311:18;;2192:177;1666:24:105;;;;;;;;1239:458;;;;:::o;814:190:52:-;872:11;885:17;914:9;926:14;936:3;926:9;:14::i;:::-;914:26;-1:-1:-1;956:5:52;960:1;914:26;956:5;:::i;:::-;950:11;;991:1;995;991:5;982:15;;;;;;;;:::i;:::-;971:26;;904:100;814:190;;;:::o;2735:679::-;2795:14;2821:11;2835:14;2845:3;2835:9;:14::i;:::-;2821:28;;2859:11;2883:3;2873;:7;;;:13;;;;:::i;:::-;2859:27;;2911:3;:5;;;:12;2904:3;:19;;2896:28;;;;;;2966:3;2956:14;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;2956:14:52;-1:-1:-1;3000:5:52;;;;;3100:7;;2952:18;;-1:-1:-1;3000:5:52;3150:10;;;;3186:29;;;;2980:17;3234:151;3258:3;3254:1;:7;3234:151;;;3342:17;;;3336:24;3320:14;;;3313:48;3263:7;3268:2;3357:1;3263:7;:::i;:::-;;;3234:151;;;-1:-1:-1;;;3394:13:52;;-1:-1:-1;2735:679:52;;-1:-1:-1;2735:679:52:o;5121:107::-;5178:9;5203:18;5219:1;5203:15;:18::i;:::-;5199:22;5121:107;-1:-1:-1;;5121:107:52:o;4796:319::-;4853:9;4894:2;4882:1;:8;:14;;4874:23;;;;;;4998:2;4995:1;4991:10;4985:17;4980:22;;5066:1;:8;5061:2;:13;;;;:::i;:::-;5056:19;;:1;:19;:::i;:::-;5050:26;;4796:319;-1:-1:-1;4796:319:52:o;1775:902::-;1959:5;;;;;2019:7;;2118:19;;;;;2112:26;1836:9;;;;2296:326;2320:2;2316:1;:6;2296:326;;;2375:12;;;;-1:-1:-1;2498:5:52;2380:1;2502;2498:5;:::i;:::-;2484:1;2488:4;2484:8;2483:21;;2478:26;;;;2522:1;2526:4;2522:8;2534:1;2522:13;2518:94;;;2566:5;:1;2570;2566:5;:::i;:::-;2555:16;;:3;;:16;;;;;:::i;:::-;;;-1:-1:-1;1775:902:52;;;-1:-1:-1;;;;;1775:902:52:o;2518:94::-;2324:3;;;;:::i;:::-;;;;2296:326;;;;2631:8;;;5510:172;5567:9;5596:1;:8;5608:2;5596:14;5588:23;;;;;;-1:-1:-1;5662:2:52;5655:10;5649:17;;5510:172::o;4235:428::-;4324:15;4316:4;:23;;;;;;;;:::i;:::-;;4312:321;;;4355:14;4365:3;4355:9;:14::i;:::-;;4235:428;;:::o;4312:321::-;4398:20;4390:4;:28;;;;;;;;:::i;:::-;;4386:247;;;4434:11;4448:14;4458:3;4448:9;:14::i;:::-;4434:28;;4487:3;4476;:7;;:14;;;;;;;:::i;:::-;;;-1:-1:-1;4552:5:52;;;;:12;4541:7;;:23;;4533:32;;;;;5234:270;5298:17;5335:1;:8;5347:2;5335:14;5327:23;;;;;;-1:-1:-1;5454:2:52;5447:10;5441:17;5460:27;5437:51;;;5234:270::o;14:180:120:-;73:6;126:2;114:9;105:7;101:23;97:32;94:52;;;142:1;139;132:12;94:52;-1:-1:-1;165:23:120;;14:180;-1:-1:-1;14:180:120:o;391:196::-;459:20;;-1:-1:-1;;;;;508:54:120;;498:65;;488:93;;577:1;574;567:12;488:93;391:196;;;:::o;592:254::-;660:6;668;721:2;709:9;700:7;696:23;692:32;689:52;;;737:1;734;727:12;689:52;760:29;779:9;760:29;:::i;:::-;750:39;836:2;821:18;;;;808:32;;-1:-1:-1;;;592:254:120:o;851:367::-;914:8;924:6;978:3;971:4;963:6;959:17;955:27;945:55;;996:1;993;986:12;945:55;-1:-1:-1;1019:20:120;;1062:18;1051:30;;1048:50;;;1094:1;1091;1084:12;1048:50;1131:4;1123:6;1119:17;1107:29;;1191:3;1184:4;1174:6;1171:1;1167:14;1159:6;1155:27;1151:38;1148:47;1145:67;;;1208:1;1205;1198:12;1145:67;851:367;;;;;:::o;1223:773::-;1345:6;1353;1361;1369;1422:2;1410:9;1401:7;1397:23;1393:32;1390:52;;;1438:1;1435;1428:12;1390:52;1478:9;1465:23;1507:18;1548:2;1540:6;1537:14;1534:34;;;1564:1;1561;1554:12;1534:34;1603:70;1665:7;1656:6;1645:9;1641:22;1603:70;:::i;:::-;1692:8;;-1:-1:-1;1577:96:120;-1:-1:-1;1780:2:120;1765:18;;1752:32;;-1:-1:-1;1796:16:120;;;1793:36;;;1825:1;1822;1815:12;1793:36;;1864:72;1928:7;1917:8;1906:9;1902:24;1864:72;:::i;:::-;1223:773;;;;-1:-1:-1;1955:8:120;-1:-1:-1;;;;1223:773:120:o;2001:186::-;2060:6;2113:2;2101:9;2092:7;2088:23;2084:32;2081:52;;;2129:1;2126;2119:12;2081:52;2152:29;2171:9;2152:29;:::i;:::-;2142:39;2001:186;-1:-1:-1;;;2001:186:120:o;2790:171::-;2857:20;;2917:18;2906:30;;2896:41;;2886:69;;2951:1;2948;2941:12;2966:474;3059:6;3067;3075;3083;3091;3144:3;3132:9;3123:7;3119:23;3115:33;3112:53;;;3161:1;3158;3151:12;3112:53;3184:29;3203:9;3184:29;:::i;:::-;3174:39;;3260:2;3249:9;3245:18;3232:32;3222:42;;3283:37;3316:2;3305:9;3301:18;3283:37;:::i;:::-;3273:47;;3339:38;3373:2;3362:9;3358:18;3339:38;:::i;:::-;3329:48;;3396:38;3429:3;3418:9;3414:19;3396:38;:::i;:::-;3386:48;;2966:474;;;;;;;;:::o;4355:1554::-;4544:6;4552;4560;4568;4576;4584;4592;4600;4653:3;4641:9;4632:7;4628:23;4624:33;4621:53;;;4670:1;4667;4660:12;4621:53;4710:9;4697:23;4739:18;4780:2;4772:6;4769:14;4766:34;;;4796:1;4793;4786:12;4766:34;4834:6;4823:9;4819:22;4809:32;;4879:7;4872:4;4868:2;4864:13;4860:27;4850:55;;4901:1;4898;4891:12;4850:55;4941:2;4928:16;4967:2;4959:6;4956:14;4953:34;;;4983:1;4980;4973:12;4953:34;5030:7;5023:4;5014:6;5010:2;5006:15;5002:26;4999:39;4996:59;;;5051:1;5048;5041:12;4996:59;5082:4;5074:13;;;;-1:-1:-1;5106:6:120;-1:-1:-1;5150:20:120;;;5137:34;;5183:16;;;5180:36;;;5212:1;5209;5202:12;5180:36;5251:72;5315:7;5304:8;5293:9;5289:24;5251:72;:::i;:::-;5342:8;;-1:-1:-1;5225:98:120;-1:-1:-1;5430:2:120;5415:18;;5402:32;;-1:-1:-1;5446:16:120;;;5443:36;;;5475:1;5472;5465:12;5443:36;5514:72;5578:7;5567:8;5556:9;5552:24;5514:72;:::i;:::-;5605:8;;-1:-1:-1;5488:98:120;-1:-1:-1;5693:2:120;5678:18;;5665:32;;-1:-1:-1;5709:16:120;;;5706:36;;;5738:1;5735;5728:12;5706:36;;5777:72;5841:7;5830:8;5819:9;5815:24;5777:72;:::i;:::-;4355:1554;;;;-1:-1:-1;4355:1554:120;;-1:-1:-1;4355:1554:120;;;;;;5868:8;-1:-1:-1;;;4355:1554:120:o;6275:127::-;6336:10;6331:3;6327:20;6324:1;6317:31;6367:4;6364:1;6357:15;6391:4;6388:1;6381:15;6407:125;6447:4;6475:1;6472;6469:8;6466:34;;;6480:18;;:::i;:::-;-1:-1:-1;6517:9:120;;6407:125::o;7534:127::-;7595:10;7590:3;7586:20;7583:1;7576:31;7626:4;7623:1;7616:15;7650:4;7647:1;7640:15;7666:135;7705:3;-1:-1:-1;;7726:17:120;;7723:43;;;7746:18;;:::i;:::-;-1:-1:-1;7793:1:120;7782:13;;7666:135::o;8155:128::-;8195:3;8226:1;8222:6;8219:1;8216:13;8213:39;;;8232:18;;:::i;:::-;-1:-1:-1;8268:9:120;;8155:128::o;9477:345::-;9674:6;9669:3;9662:19;9725:6;9717;9712:2;9707:3;9703:12;9690:42;9644:3;9755:16;;9773:2;9751:25;9785:13;;;9751:25;9477:345;-1:-1:-1;;9477:345:120:o;9827:266::-;9915:6;9910:3;9903:19;9967:6;9960:5;9953:4;9948:3;9944:14;9931:43;-1:-1:-1;10019:1:120;9994:16;;;10012:4;9990:27;;;9983:38;;;;10075:2;10054:15;;;-1:-1:-1;;10050:29:120;10041:39;;;10037:50;;9827:266::o;10098:981::-;10205:6;10200:3;10193:19;10175:3;10231:4;10260:2;10255:3;10251:12;10244:19;;10285:3;10325:6;10322:1;10318:14;10313:3;10309:24;10356:5;10379:1;10389:664;10403:6;10400:1;10397:13;10389:664;;;10474:5;10468:4;10464:16;10459:3;10452:29;10533:6;10520:20;10623:2;10619:7;10611:5;10595:14;10591:26;10587:40;10567:18;10563:65;10553:93;;10642:1;10639;10632:12;10553:93;10674:30;;10733:21;;10783:18;10770:32;;10767:52;;;10815:1;10812;10805:12;10767:52;10866:8;10850:14;10846:29;10839:5;10835:41;10832:61;;;10889:1;10886;10879:12;10832:61;10914:59;10968:4;10958:8;10953:2;10944:7;10940:16;10914:59;:::i;:::-;11031:12;;;;10906:67;-1:-1:-1;;;10996:15:120;;;;10425:1;10418:9;10389:664;;;-1:-1:-1;11069:4:120;;10098:981;-1:-1:-1;;;;;;;10098:981:120:o;11084:470::-;11184:6;11179:3;11172:19;11154:3;11210:4;11239:2;11234:3;11230:12;11223:19;;11265:5;11288:1;11298:231;11312:6;11309:1;11306:13;11298:231;;;-1:-1:-1;;;;;11377:26:120;11396:6;11377:26;:::i;:::-;11373:75;11361:88;;11469:12;;;;11504:15;;;;11334:1;11327:9;11298:231;;;-1:-1:-1;11545:3:120;;11084:470;-1:-1:-1;;;;;11084:470:120:o;11559:401::-;11659:6;11654:3;11647:19;11629:3;11689:66;11681:6;11678:78;11675:98;;;11769:1;11766;11759:12;11675:98;11805:6;11802:1;11798:14;11857:8;11850:5;11843:4;11838:3;11834:14;11821:45;11934:1;11889:18;;11909:4;11885:29;11923:13;;;-1:-1:-1;11885:29:120;;11559:401;-1:-1:-1;;11559:401:120:o;11965:1303::-;12396:3;12385:9;12378:22;12359:4;12429:6;12423:13;12473:6;12467:3;12456:9;12452:19;12445:35;12498:1;12508:145;12522:6;12519:1;12516:13;12508:145;;;12636:4;12620:14;;;12616:25;;12610:32;12604:3;12585:17;;;12581:27;12574:69;12537:12;12508:145;;;12671:6;12668:1;12665:13;12662:92;;;12742:1;12736:3;12727:6;12716:9;12712:22;12708:32;12701:43;12662:92;-1:-1:-1;12813:2:120;12792:15;-1:-1:-1;;12788:29:120;12773:45;;12860:18;;;12880:3;12856:28;;;12849:4;12834:20;;12827:58;12908:74;;12969:12;;12961:6;12953;12908:74;:::i;:::-;12894:88;;13030:9;13022:6;13018:22;13013:2;13002:9;12998:18;12991:50;13064:61;13118:6;13110;13102;13064:61;:::i;:::-;13050:75;;13173:9;13165:6;13161:22;13156:2;13145:9;13141:18;13134:50;13201:61;13255:6;13247;13239;13201:61;:::i;:::-;13193:69;11965:1303;-1:-1:-1;;;;;;;;;;11965:1303:120:o;20415:217::-;20455:1;20481;20471:132;;20525:10;20520:3;20516:20;20513:1;20506:31;20560:4;20557:1;20550:15;20588:4;20585:1;20578:15;20471:132;-1:-1:-1;20617:9:120;;20415:217::o;20637:168::-;20677:7;20743:1;20739;20735:6;20731:14;20728:1;20725:21;20720:1;20713:9;20706:17;20702:45;20699:71;;;20750:18;;:::i;:::-;-1:-1:-1;20790:9:120;;20637:168::o;21517:127::-;21578:10;21573:3;21569:20;21566:1;21559:31;21609:4;21606:1;21599:15;21633:4;21630:1;21623:15;21649:127;21710:10;21705:3;21701:20;21698:1;21691:31;21741:4;21738:1;21731:15;21765:4;21762:1;21755:15

Swarm Source

ipfs://7f0483041017bb51352e4769b343fd0edbacc1fa8e07370faab4de961b1252de
Block Transaction Gas Used Reward
Age Block Fee Address BC Fee Address Voting Power Jailed Incoming
Block Uncle Number Difficulty Gas Used Reward
Loading
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.