@keep-network/tbtc-v2 1.2.0-dev.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/artifacts/.chainId +1 -1
- package/artifacts/Bank.json +40 -50
- package/artifacts/Bridge.json +32 -449
- package/artifacts/BridgeGovernance.json +24 -24
- package/artifacts/BridgeGovernanceParameters.json +10 -10
- package/artifacts/Deposit.json +13 -13
- package/artifacts/DepositSweep.json +13 -13
- package/artifacts/DonationVault.json +17 -17
- package/artifacts/Fraud.json +14 -14
- package/artifacts/LightRelay.json +38 -38
- package/artifacts/MaintainerProxy.json +47 -47
- package/artifacts/MovingFunds.json +14 -14
- package/artifacts/Redemption.json +13 -13
- package/artifacts/TBTC.json +36 -37
- package/artifacts/TBTCVault.json +47 -47
- package/artifacts/VendingMachine.json +34 -35
- package/artifacts/VendingMachineV2.json +21 -21
- package/artifacts/VendingMachineV3.json +21 -21
- package/artifacts/Wallets.json +13 -13
- package/artifacts/solcInputs/7cc3eda3cb3ff2522d18b5e7b31ea228.json +102 -0
- package/artifacts/solcInputs/802132f7da69a8a4226cb9424480847b.json +218 -0
- package/artifacts/solcInputs/887fad6b16575ba42183543c324eeb0e.json +335 -0
- package/artifacts/solcInputs/{8445e3932e9b9683df0e9fb9258d7b11.json → b0025f1f7efe4824592ac0c9793776c3.json} +0 -9
- package/artifacts/solcInputs/{cc4433405642a987910ddb374547d19a.json → fccb130292c8c7cc958ab4fa31a3e180.json} +12 -15
- package/build/contracts/GovernanceUtils.sol/GovernanceUtils.dbg.json +1 -1
- package/build/contracts/bank/Bank.sol/Bank.dbg.json +1 -1
- package/build/contracts/bank/IReceiveBalanceApproval.sol/IReceiveBalanceApproval.dbg.json +1 -1
- package/build/contracts/bridge/BitcoinTx.sol/BitcoinTx.dbg.json +1 -1
- package/build/contracts/bridge/Bridge.sol/Bridge.dbg.json +1 -1
- package/build/contracts/bridge/BridgeGovernanceParameters.sol/BridgeGovernanceParameters.dbg.json +1 -1
- package/build/contracts/bridge/BridgeState.sol/BridgeState.dbg.json +1 -1
- package/build/contracts/bridge/Deposit.sol/Deposit.dbg.json +1 -1
- package/build/contracts/bridge/DepositSweep.sol/DepositSweep.dbg.json +1 -1
- package/build/contracts/bridge/EcdsaLib.sol/EcdsaLib.dbg.json +1 -1
- package/build/contracts/bridge/Fraud.sol/Fraud.dbg.json +1 -1
- package/build/contracts/bridge/Heartbeat.sol/Heartbeat.dbg.json +1 -1
- package/build/contracts/bridge/IRelay.sol/IRelay.dbg.json +1 -1
- package/build/contracts/bridge/MovingFunds.sol/MovingFunds.dbg.json +1 -1
- package/build/contracts/bridge/Redemption.sol/OutboundTx.dbg.json +1 -1
- package/build/contracts/bridge/Redemption.sol/Redemption.dbg.json +1 -1
- package/build/contracts/bridge/VendingMachine.sol/VendingMachine.dbg.json +1 -1
- package/build/contracts/bridge/VendingMachineV2.sol/VendingMachineV2.dbg.json +1 -1
- package/build/contracts/bridge/VendingMachineV3.sol/VendingMachineV3.dbg.json +1 -1
- package/build/contracts/bridge/Wallets.sol/Wallets.dbg.json +1 -1
- package/build/contracts/l2/L2TBTC.sol/L2TBTC.dbg.json +1 -1
- package/build/contracts/l2/L2WormholeGateway.sol/IWormholeTokenBridge.dbg.json +1 -1
- package/build/contracts/l2/L2WormholeGateway.sol/L2WormholeGateway.dbg.json +1 -1
- package/build/contracts/maintainer/MaintainerProxy.sol/MaintainerProxy.dbg.json +1 -1
- package/build/contracts/relay/LightRelay.sol/ILightRelay.dbg.json +1 -1
- package/build/contracts/relay/LightRelay.sol/LightRelay.dbg.json +1 -1
- package/build/contracts/relay/LightRelay.sol/RelayUtils.dbg.json +1 -1
- package/build/contracts/token/TBTC.sol/TBTC.dbg.json +1 -1
- package/build/contracts/vault/DonationVault.sol/DonationVault.dbg.json +1 -1
- package/build/contracts/vault/IVault.sol/IVault.dbg.json +1 -1
- package/build/contracts/vault/TBTCOptimisticMinting.sol/TBTCOptimisticMinting.dbg.json +1 -1
- package/build/contracts/vault/TBTCVault.sol/TBTCVault.dbg.json +1 -1
- package/export/artifacts/@keep-network/ecdsa/contracts/EcdsaDkgValidator.sol/EcdsaDkgValidator.json +24 -24
- package/export/artifacts/@keep-network/ecdsa/contracts/WalletRegistry.sol/WalletRegistry.json +245 -245
- package/export/artifacts/@keep-network/ecdsa/contracts/libraries/EcdsaDkg.sol/EcdsaDkg.json +2 -2
- package/export/artifacts/@keep-network/ecdsa/contracts/libraries/EcdsaInactivity.sol/EcdsaInactivity.json +23 -23
- package/export/artifacts/@keep-network/random-beacon/contracts/ReimbursementPool.sol/ReimbursementPool.json +53 -53
- package/export/artifacts/@keep-network/sortition-pools/contracts/Chaosnet.sol/Chaosnet.json +21 -21
- package/export/artifacts/@keep-network/sortition-pools/contracts/Rewards.sol/Rewards.json +16 -16
- package/export/artifacts/@keep-network/sortition-pools/contracts/SortitionPool.sol/SortitionPool.json +206 -206
- package/export/artifacts/@keep-network/sortition-pools/contracts/SortitionTree.sol/SortitionTree.json +26 -26
- package/export/artifacts/@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol/ERC1967Proxy.json +46 -46
- package/export/artifacts/@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol/ProxyAdmin.json +36 -36
- package/export/artifacts/@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol/TransparentUpgradeableProxy.json +78 -78
- package/export/artifacts/@openzeppelin/contracts/token/ERC721/ERC721.sol/ERC721.json +68 -68
- package/export/artifacts/@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol/ERC20Upgradeable.json +43 -43
- package/export/artifacts/@thesis/solidity-contracts/contracts/token/ERC20WithPermit.sol/ERC20WithPermit.json +79 -79
- package/export/artifacts/@thesis/solidity-contracts/contracts/token/MisfundRecovery.sol/MisfundRecovery.json +42 -42
- package/export/artifacts/contracts/bank/Bank.sol/Bank.json +77 -77
- package/export/artifacts/contracts/bridge/Bridge.sol/Bridge.json +320 -320
- package/export/artifacts/contracts/bridge/VendingMachine.sol/VendingMachine.json +108 -108
- package/export/artifacts/contracts/bridge/VendingMachineV2.sol/VendingMachineV2.json +63 -63
- package/export/artifacts/contracts/bridge/VendingMachineV3.sol/VendingMachineV3.json +65 -65
- package/export/artifacts/contracts/l2/L2TBTC.sol/L2TBTC.json +194 -194
- package/export/artifacts/contracts/l2/L2WormholeGateway.sol/L2WormholeGateway.json +100 -100
- package/export/artifacts/contracts/maintainer/MaintainerProxy.sol/MaintainerProxy.json +149 -149
- package/export/artifacts/contracts/relay/LightRelay.sol/LightRelay.json +76 -76
- package/export/artifacts/contracts/token/TBTC.sol/TBTC.json +104 -104
- package/export/artifacts/contracts/vault/DonationVault.sol/DonationVault.json +19 -19
- package/export/artifacts/contracts/vault/TBTCVault.sol/TBTCVault.json +184 -184
- package/export/deploy/00_resolve_relay.js +83 -0
- package/export/deploy/01_deploy_tbtc_v2_token.js +70 -0
- package/export/deploy/02_deploy_vending_machine.js +84 -0
- package/export/deploy/03_transfer_vending_machine_roles.js +69 -0
- package/export/deploy/04_deploy_bank.js +73 -0
- package/export/deploy/05_deploy_bridge.js +178 -0
- package/export/{test/integration/utils/staking.js → deploy/06_deploy_tbtc_vault.js} +32 -35
- package/export/deploy/07_deploy_bridge_governance.js +87 -0
- package/export/deploy/08_deploy_maintainer_proxy.js +80 -0
- package/export/deploy/09_bank_update_bridge.js +63 -0
- package/export/deploy/10_authorize_spv_maintainer_in_bridge.js +61 -0
- package/export/deploy/11_transfer_bank_ownership.js +60 -0
- package/export/deploy/12_transfer_bridge_governance.js +63 -0
- package/export/deploy/13_transfer_bridge_governance_ownership.js +60 -0
- package/export/deploy/14_transfer_tbtc_vault_ownership.js +60 -0
- package/export/deploy/15_transfer_maintainer_proxy_ownership.js +60 -0
- package/export/deploy/16_initialize_wallet_owner.js +63 -0
- package/export/deploy/16_transfer_proxy_admin_ownership.js +73 -0
- package/export/deploy/17_authorize_maintainer_proxy_in_bridge.js +63 -0
- package/export/deploy/17_transfer_proxy_admin_ownership.js +73 -0
- package/export/deploy/18_authorize_maintainer_proxy_in_bridge.js +63 -0
- package/export/deploy/18_authorize_maintainer_proxy_in_reimbursement_pool.js +63 -0
- package/export/deploy/19_authorize_bridge_in_reimbursement_pool.js +63 -0
- package/export/deploy/19_authorize_maintainer_proxy_in_reimbursement_pool.js +63 -0
- package/export/deploy/20_authorize_bridge_in_reimbursement_pool.js +63 -0
- package/export/deploy/20_deploy_proxy_admin_with_deputy.js +80 -0
- package/export/deploy/21_transfer_reimbursement_pool_ownership.js +60 -0
- package/export/deploy/22_deploy_proxy_admin_with_deputy.js +80 -0
- package/export/deploy/24_transfer_maintainer_proxy_ownership.js +60 -0
- package/export/deploy/25_transfer_proxy_admin_ownership.js +73 -0
- package/export/deploy/26_authorize_maintainer_proxy_in_reimbursement_pool.js +70 -0
- package/export/deploy/27_authorize_bridge_in_reimbursement_pool.js +70 -0
- package/export/deploy/28_deploy_proxy_admin_with_deputy.js +80 -0
- package/export/typechain/RelayStub.js +2 -0
- package/export/typechain/TestRelay.js +2 -0
- package/export/typechain/factories/RelayStub__factory.js +546 -0
- package/export/typechain/factories/TestRelay__factory.js +168 -0
- package/export/typechain/factories/WalletRegistry__factory.js +1 -1
- package/package.json +5 -5
- package/artifacts/BLS.json +0 -223
- package/artifacts/BeaconAuthorization.json +0 -273
- package/artifacts/BeaconDkg.json +0 -241
- package/artifacts/BeaconDkgValidator.json +0 -501
- package/artifacts/BeaconInactivity.json +0 -151
- package/artifacts/BeaconSortitionPool.json +0 -1187
- package/artifacts/EcdsaDkgValidator.json +0 -517
- package/artifacts/EcdsaInactivity.json +0 -156
- package/artifacts/EcdsaSortitionPool.json +0 -1187
- package/artifacts/KeepRegistry.json +0 -99
- package/artifacts/KeepStake.json +0 -286
- package/artifacts/KeepToken.json +0 -711
- package/artifacts/KeepTokenStaking.json +0 -483
- package/artifacts/NuCypherStakingEscrow.json +0 -287
- package/artifacts/NuCypherToken.json +0 -711
- package/artifacts/RandomBeacon.json +0 -3271
- package/artifacts/RandomBeaconChaosnet.json +0 -252
- package/artifacts/RandomBeaconGovernance.json +0 -3499
- package/artifacts/ReimbursementPool.json +0 -509
- package/artifacts/T.json +0 -1148
- package/artifacts/TBTCToken.json +0 -738
- package/artifacts/TokenStaking.json +0 -2288
- package/artifacts/TokenholderGovernor.json +0 -1795
- package/artifacts/TokenholderTimelock.json +0 -1058
- package/artifacts/VendingMachineKeep.json +0 -400
- package/artifacts/VendingMachineNuCypher.json +0 -400
- package/artifacts/WalletRegistry.json +0 -1962
- package/artifacts/WalletRegistryGovernance.json +0 -2863
- package/export/artifacts/contracts/test/BankStub.sol/BankStub.json +0 -11975
- package/export/artifacts/contracts/test/BridgeStub.sol/BridgeStub.json +0 -51806
- package/export/artifacts/contracts/test/GoerliLightRelay.sol/GoerliLightRelay.json +0 -11988
- package/export/artifacts/contracts/test/HeartbeatStub.sol/HeartbeatStub.json +0 -822
- package/export/artifacts/contracts/test/LightRelayStub.sol/LightRelayStub.json +0 -12729
- package/export/artifacts/contracts/test/ReceiveApprovalStub.sol/ReceiveApprovalStub.json +0 -2160
- package/export/artifacts/contracts/test/SystemTestRelay.sol/SystemTestRelay.json +0 -3407
- package/export/artifacts/contracts/test/TestERC20.sol/TestERC20.json +0 -14263
- package/export/artifacts/contracts/test/TestERC721.sol/TestERC721.json +0 -10644
- package/export/artifacts/contracts/test/TestEcdsaLib.sol/TestEcdsaLib.json +0 -1160
- package/export/artifacts/contracts/test/WormholeBridgeStub.sol/WormholeBridgeStub.json +0 -8665
- package/export/test/integration/data/bls.js +0 -12
- package/export/test/integration/data/integration.js +0 -133
- package/export/test/integration/utils/ecdsa-wallet-registry.js +0 -370
- package/export/test/integration/utils/random-beacon.js +0 -193
|
@@ -65,28 +65,25 @@
|
|
|
65
65
|
"content": "pragma solidity 0.8.17;\n\nimport \"./Branch.sol\";\nimport \"./Position.sol\";\nimport \"./Leaf.sol\";\nimport \"./Constants.sol\";\n\ncontract SortitionTree {\n using Branch for uint256;\n using Position for uint256;\n using Leaf for uint256;\n\n // implicit tree\n // root 8\n // level2 64\n // level3 512\n // level4 4k\n // level5 32k\n // level6 256k\n // level7 2M\n uint256 internal root;\n\n // A 2-index mapping from layer => (index (0-index) => branch). For example,\n // to access the 6th branch in the 2nd layer (right below the root node; the\n // first branch layer), call branches[2][5]. Mappings are used in place of\n // arrays for efficiency. The root is the first layer, the branches occupy\n // layers 2 through 7, and layer 8 is for the leaves. Following this\n // convention, the first index in `branches` is `2`, and the last index is\n // `7`.\n mapping(uint256 => mapping(uint256 => uint256)) internal branches;\n\n // A 0-index mapping from index => leaf, acting as an array. For example, to\n // access the 42nd leaf, call leaves[41].\n mapping(uint256 => uint256) internal leaves;\n\n // the flagged (see setFlag() and unsetFlag() in Position.sol) positions\n // of all operators present in the pool\n mapping(address => uint256) internal flaggedLeafPosition;\n\n // the leaf after the rightmost occupied leaf of each stack\n uint256 internal rightmostLeaf;\n\n // the empty leaves in each stack\n // between 0 and the rightmost occupied leaf\n uint256[] internal emptyLeaves;\n\n // Each operator has an uint32 ID number\n // which is allocated when they first join the pool\n // and remains unchanged even if they leave and rejoin the pool.\n mapping(address => uint32) internal operatorID;\n\n // The idAddress array records the address corresponding to each ID number.\n // The ID number 0 is initialized with a zero address and is not used.\n address[] internal idAddress;\n\n constructor() {\n root = 0;\n rightmostLeaf = 0;\n idAddress.push();\n }\n\n /// @notice Return the ID number of the given operator address. An ID number\n /// of 0 means the operator has not been allocated an ID number yet.\n /// @param operator Address of the operator.\n /// @return the ID number of the given operator address\n function getOperatorID(address operator) public view returns (uint32) {\n return operatorID[operator];\n }\n\n /// @notice Get the operator address corresponding to the given ID number. A\n /// zero address means the ID number has not been allocated yet.\n /// @param id ID of the operator\n /// @return the address of the operator\n function getIDOperator(uint32 id) public view returns (address) {\n return idAddress.length > id ? idAddress[id] : address(0);\n }\n\n /// @notice Gets the operator addresses corresponding to the given ID\n /// numbers. A zero address means the ID number has not been allocated yet.\n /// This function works just like getIDOperator except that it allows to fetch\n /// operator addresses for multiple IDs in one call.\n /// @param ids the array of the operator ids\n /// @return an array of the associated operator addresses\n function getIDOperators(uint32[] calldata ids)\n public\n view\n returns (address[] memory)\n {\n uint256 idCount = idAddress.length;\n\n address[] memory operators = new address[](ids.length);\n for (uint256 i = 0; i < ids.length; i++) {\n uint32 id = ids[i];\n operators[i] = idCount > id ? idAddress[id] : address(0);\n }\n return operators;\n }\n\n /// @notice Checks if operator is already registered in the pool.\n /// @param operator the address of the operator\n /// @return whether or not the operator is already registered in the pool\n function isOperatorRegistered(address operator) public view returns (bool) {\n return getFlaggedLeafPosition(operator) != 0;\n }\n\n /// @notice Sum the number of operators in each trunk.\n /// @return the number of operators in the pool\n function operatorsInPool() public view returns (uint256) {\n // Get the number of leaves that might be occupied;\n // if `rightmostLeaf` equals `firstLeaf()` the tree must be empty,\n // otherwise the difference between these numbers\n // gives the number of leaves that may be occupied.\n uint256 nPossiblyUsedLeaves = rightmostLeaf;\n // Get the number of empty leaves\n // not accounted for by the `rightmostLeaf`\n uint256 nEmptyLeaves = emptyLeaves.length;\n\n return (nPossiblyUsedLeaves - nEmptyLeaves);\n }\n\n /// @notice Convenience method to return the total weight of the pool\n /// @return the total weight of the pool\n function totalWeight() public view returns (uint256) {\n return root.sumWeight();\n }\n\n /// @notice Give the operator a new ID number.\n /// Does not check if the operator already has an ID number.\n /// @param operator the address of the operator\n /// @return a new ID for that operator\n function allocateOperatorID(address operator) internal returns (uint256) {\n uint256 id = idAddress.length;\n\n require(id <= type(uint32).max, \"Pool capacity exceeded\");\n\n operatorID[operator] = uint32(id);\n idAddress.push(operator);\n return id;\n }\n\n /// @notice Inserts an operator into the sortition pool\n /// @param operator the address of an operator to insert\n /// @param weight how much weight that operator has in the pool\n function _insertOperator(address operator, uint256 weight) internal {\n require(\n !isOperatorRegistered(operator),\n \"Operator is already registered in the pool\"\n );\n\n // Fetch the operator's ID, and if they don't have one, allocate them one.\n uint256 id = getOperatorID(operator);\n if (id == 0) {\n id = allocateOperatorID(operator);\n }\n\n // Determine which leaf to insert them into\n uint256 position = getEmptyLeafPosition();\n // Record the block the operator was inserted in\n uint256 theLeaf = Leaf.make(operator, block.number, id);\n\n // Update the leaf, and propagate the weight changes all the way up to the\n // root.\n root = setLeaf(position, theLeaf, weight, root);\n\n // Without position flags,\n // the position 0x000000 would be treated as empty\n flaggedLeafPosition[operator] = position.setFlag();\n }\n\n /// @notice Remove an operator (and their weight) from the pool.\n /// @param operator the address of the operator to remove\n function _removeOperator(address operator) internal {\n uint256 flaggedPosition = getFlaggedLeafPosition(operator);\n require(flaggedPosition != 0, \"Operator is not registered in the pool\");\n uint256 unflaggedPosition = flaggedPosition.unsetFlag();\n\n // Update the leaf, and propagate the weight changes all the way up to the\n // root.\n root = removeLeaf(unflaggedPosition, root);\n removeLeafPositionRecord(operator);\n }\n\n /// @notice Update an operator's weight in the pool.\n /// @param operator the address of the operator to update\n /// @param weight the new weight\n function updateOperator(address operator, uint256 weight) internal {\n require(\n isOperatorRegistered(operator),\n \"Operator is not registered in the pool\"\n );\n\n uint256 flaggedPosition = getFlaggedLeafPosition(operator);\n uint256 unflaggedPosition = flaggedPosition.unsetFlag();\n root = updateLeaf(unflaggedPosition, weight, root);\n }\n\n /// @notice Helper method to remove a leaf position record for an operator.\n /// @param operator the address of the operator to remove the record for\n function removeLeafPositionRecord(address operator) internal {\n flaggedLeafPosition[operator] = 0;\n }\n\n /// @notice Removes the data and weight from a particular leaf.\n /// @param position the leaf index to remove\n /// @param _root the root node containing the leaf\n /// @return the updated root node\n function removeLeaf(uint256 position, uint256 _root)\n internal\n returns (uint256)\n {\n uint256 rightmostSubOne = rightmostLeaf - 1;\n bool isRightmost = position == rightmostSubOne;\n\n // Clears out the data in the leaf node, and then propagates the weight\n // changes all the way up to the root.\n uint256 newRoot = setLeaf(position, 0, 0, _root);\n\n // Infer if need to fall back on emptyLeaves yet\n if (isRightmost) {\n rightmostLeaf = rightmostSubOne;\n } else {\n emptyLeaves.push(position);\n }\n return newRoot;\n }\n\n /// @notice Updates the tree to give a particular leaf a new weight.\n /// @param position the index of the leaf to update\n /// @param weight the new weight\n /// @param _root the root node containing the leaf\n /// @return the updated root node\n function updateLeaf(\n uint256 position,\n uint256 weight,\n uint256 _root\n ) internal returns (uint256) {\n if (getLeafWeight(position) != weight) {\n return updateTree(position, weight, _root);\n } else {\n return _root;\n }\n }\n\n /// @notice Places a leaf into a particular position, with a given weight and\n /// propagates that change.\n /// @param position the index to place the leaf in\n /// @param theLeaf the new leaf to place in the position\n /// @param leafWeight the weight of the leaf\n /// @param _root the root containing the new leaf\n /// @return the updated root node\n function setLeaf(\n uint256 position,\n uint256 theLeaf,\n uint256 leafWeight,\n uint256 _root\n ) internal returns (uint256) {\n // set leaf\n leaves[position] = theLeaf;\n\n return (updateTree(position, leafWeight, _root));\n }\n\n /// @notice Propagates a weight change at a position through the tree,\n /// eventually returning the updated root.\n /// @param position the index of leaf to update\n /// @param weight the new weight of the leaf\n /// @param _root the root node containing the leaf\n /// @return the updated root node\n function updateTree(\n uint256 position,\n uint256 weight,\n uint256 _root\n ) internal returns (uint256) {\n uint256 childSlot;\n uint256 treeNode;\n uint256 newNode;\n uint256 nodeWeight = weight;\n\n uint256 parent = position;\n // set levels 7 to 2\n for (uint256 level = Constants.LEVELS; level >= 2; level--) {\n childSlot = parent.slot();\n parent = parent.parent();\n treeNode = branches[level][parent];\n newNode = treeNode.setSlot(childSlot, nodeWeight);\n branches[level][parent] = newNode;\n nodeWeight = newNode.sumWeight();\n }\n\n // set level Root\n childSlot = parent.slot();\n return _root.setSlot(childSlot, nodeWeight);\n }\n\n /// @notice Retrieves the next available empty leaf position. Tries to fill\n /// left to right first, ignoring leaf removals, and then fills\n /// most-recent-removals first.\n /// @return the position of the empty leaf\n function getEmptyLeafPosition() internal returns (uint256) {\n uint256 rLeaf = rightmostLeaf;\n bool spaceOnRight = (rLeaf + 1) < Constants.POOL_CAPACITY;\n if (spaceOnRight) {\n rightmostLeaf = rLeaf + 1;\n return rLeaf;\n } else {\n uint256 emptyLeafCount = emptyLeaves.length;\n require(emptyLeafCount > 0, \"Pool is full\");\n uint256 emptyLeaf = emptyLeaves[emptyLeafCount - 1];\n emptyLeaves.pop();\n return emptyLeaf;\n }\n }\n\n /// @notice Gets the flagged leaf position for an operator.\n /// @param operator the address of the operator\n /// @return the leaf position of that operator\n function getFlaggedLeafPosition(address operator)\n internal\n view\n returns (uint256)\n {\n return flaggedLeafPosition[operator];\n }\n\n /// @notice Gets the weight of a leaf at a particular position.\n /// @param position the index of the leaf\n /// @return the weight of the leaf at that position\n function getLeafWeight(uint256 position) internal view returns (uint256) {\n uint256 slot = position.slot();\n uint256 parent = position.parent();\n\n // A leaf's weight information is stored a 32-bit slot in the branch layer\n // directly above the leaf layer. To access it, we calculate that slot and\n // parent position, and always know the hard-coded layer index.\n uint256 node = branches[Constants.LEVELS][parent];\n return node.getSlot(slot);\n }\n\n /// @notice Picks a leaf given a random index.\n /// @param index a number in `[0, _root.totalWeight())` used to decide\n /// between leaves\n /// @param _root the root of the tree\n function pickWeightedLeaf(uint256 index, uint256 _root)\n internal\n view\n returns (uint256 leafPosition)\n {\n uint256 currentIndex = index;\n uint256 currentNode = _root;\n uint256 currentPosition = 0;\n uint256 currentSlot;\n\n require(index < currentNode.sumWeight(), \"Index exceeds weight\");\n\n // get root slot\n (currentSlot, currentIndex) = currentNode.pickWeightedSlot(currentIndex);\n\n // get slots from levels 2 to 7\n for (uint256 level = 2; level <= Constants.LEVELS; level++) {\n currentPosition = currentPosition.child(currentSlot);\n currentNode = branches[level][currentPosition];\n (currentSlot, currentIndex) = currentNode.pickWeightedSlot(currentIndex);\n }\n\n // get leaf position\n leafPosition = currentPosition.child(currentSlot);\n }\n}\n"
|
|
66
66
|
},
|
|
67
67
|
"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": {
|
|
68
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.
|
|
68
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = _setInitializedVersion(1);\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n bool isTopLevelCall = _setInitializedVersion(version);\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(version);\n }\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n _setInitializedVersion(type(uint8).max);\n }\n\n function _setInitializedVersion(uint8 version) private returns (bool) {\n // If the contract is initializing we ignore whether _initialized is set in order to support multiple\n // inheritance patterns, but we only do this in the context of a constructor, and for the lowest level\n // of initializers, because in other contexts the contract may have been reentered.\n if (_initializing) {\n require(\n version == 1 && !AddressUpgradeable.isContract(address(this)),\n \"Initializable: contract is already initialized\"\n );\n return false;\n } else {\n require(_initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n return true;\n }\n }\n}\n"
|
|
69
69
|
},
|
|
70
70
|
"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": {
|
|
71
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.
|
|
71
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n"
|
|
72
72
|
},
|
|
73
73
|
"@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol": {
|
|
74
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.
|
|
75
|
-
},
|
|
76
|
-
"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol": {
|
|
77
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary MathUpgradeable {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n"
|
|
74
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../StringsUpgradeable.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSAUpgradeable {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV\n }\n\n function _throwError(RecoverError error) private pure {\n if (error == RecoverError.NoError) {\n return; // no error: do nothing\n } else if (error == RecoverError.InvalidSignature) {\n revert(\"ECDSA: invalid signature\");\n } else if (error == RecoverError.InvalidSignatureLength) {\n revert(\"ECDSA: invalid signature length\");\n } else if (error == RecoverError.InvalidSignatureS) {\n revert(\"ECDSA: invalid signature 's' value\");\n } else if (error == RecoverError.InvalidSignatureV) {\n revert(\"ECDSA: invalid signature 'v' value\");\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature` or error string. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n *\n * Documentation for signature generation:\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n // Check the signature length\n // - case 65: r,s,v signature (standard)\n // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._\n if (signature.length == 65) {\n bytes32 r;\n bytes32 s;\n uint8 v;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n return tryRecover(hash, v, r, s);\n } else if (signature.length == 64) {\n bytes32 r;\n bytes32 vs;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n assembly {\n r := mload(add(signature, 0x20))\n vs := mload(add(signature, 0x40))\n }\n return tryRecover(hash, r, vs);\n } else {\n return (address(0), RecoverError.InvalidSignatureLength);\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, signature);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n *\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n *\n * _Available since v4.3._\n */\n function tryRecover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address, RecoverError) {\n bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n uint8 v = uint8((uint256(vs) >> 255) + 27);\n return tryRecover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n *\n * _Available since v4.2._\n */\n function recover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n * `r` and `s` signature fields separately.\n *\n * _Available since v4.3._\n */\n function tryRecover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address, RecoverError) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n return (address(0), RecoverError.InvalidSignatureS);\n }\n if (v != 27 && v != 28) {\n return (address(0), RecoverError.InvalidSignatureV);\n }\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n if (signer == address(0)) {\n return (address(0), RecoverError.InvalidSignature);\n }\n\n return (signer, RecoverError.NoError);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from `s`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", StringsUpgradeable.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n"
|
|
78
75
|
},
|
|
79
76
|
"@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol": {
|
|
80
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCastUpgradeable {\n /**\n * @dev Returns the downcasted uint248 from uint256, reverting on\n * overflow (when the input is greater than largest uint248).\n *\n * Counterpart to Solidity's `uint248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toUint248(uint256 value) internal pure returns (uint248) {\n require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n return uint248(value);\n }\n\n /**\n * @dev Returns the downcasted uint240 from uint256, reverting on\n * overflow (when the input is greater than largest uint240).\n *\n * Counterpart to Solidity's `uint240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toUint240(uint256 value) internal pure returns (uint240) {\n require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n return uint240(value);\n }\n\n /**\n * @dev Returns the downcasted uint232 from uint256, reverting on\n * overflow (when the input is greater than largest uint232).\n *\n * Counterpart to Solidity's `uint232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toUint232(uint256 value) internal pure returns (uint232) {\n require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n return uint232(value);\n }\n\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.2._\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint216 from uint256, reverting on\n * overflow (when the input is greater than largest uint216).\n *\n * Counterpart to Solidity's `uint216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toUint216(uint256 value) internal pure returns (uint216) {\n require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n return uint216(value);\n }\n\n /**\n * @dev Returns the downcasted uint208 from uint256, reverting on\n * overflow (when the input is greater than largest uint208).\n *\n * Counterpart to Solidity's `uint208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toUint208(uint256 value) internal pure returns (uint208) {\n require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n return uint208(value);\n }\n\n /**\n * @dev Returns the downcasted uint200 from uint256, reverting on\n * overflow (when the input is greater than largest uint200).\n *\n * Counterpart to Solidity's `uint200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toUint200(uint256 value) internal pure returns (uint200) {\n require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n return uint200(value);\n }\n\n /**\n * @dev Returns the downcasted uint192 from uint256, reverting on\n * overflow (when the input is greater than largest uint192).\n *\n * Counterpart to Solidity's `uint192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toUint192(uint256 value) internal pure returns (uint192) {\n require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n return uint192(value);\n }\n\n /**\n * @dev Returns the downcasted uint184 from uint256, reverting on\n * overflow (when the input is greater than largest uint184).\n *\n * Counterpart to Solidity's `uint184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toUint184(uint256 value) internal pure returns (uint184) {\n require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return uint184(value);\n }\n\n /**\n * @dev Returns the downcasted uint176 from uint256, reverting on\n * overflow (when the input is greater than largest uint176).\n *\n * Counterpart to Solidity's `uint176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toUint176(uint256 value) internal pure returns (uint176) {\n require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n return uint176(value);\n }\n\n /**\n * @dev Returns the downcasted uint168 from uint256, reverting on\n * overflow (when the input is greater than largest uint168).\n *\n * Counterpart to Solidity's `uint168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toUint168(uint256 value) internal pure returns (uint168) {\n require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n return uint168(value);\n }\n\n /**\n * @dev Returns the downcasted uint160 from uint256, reverting on\n * overflow (when the input is greater than largest uint160).\n *\n * Counterpart to Solidity's `uint160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toUint160(uint256 value) internal pure returns (uint160) {\n require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n return uint160(value);\n }\n\n /**\n * @dev Returns the downcasted uint152 from uint256, reverting on\n * overflow (when the input is greater than largest uint152).\n *\n * Counterpart to Solidity's `uint152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toUint152(uint256 value) internal pure returns (uint152) {\n require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n return uint152(value);\n }\n\n /**\n * @dev Returns the downcasted uint144 from uint256, reverting on\n * overflow (when the input is greater than largest uint144).\n *\n * Counterpart to Solidity's `uint144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toUint144(uint256 value) internal pure returns (uint144) {\n require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n return uint144(value);\n }\n\n /**\n * @dev Returns the downcasted uint136 from uint256, reverting on\n * overflow (when the input is greater than largest uint136).\n *\n * Counterpart to Solidity's `uint136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toUint136(uint256 value) internal pure returns (uint136) {\n require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n return uint136(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v2.5._\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint120 from uint256, reverting on\n * overflow (when the input is greater than largest uint120).\n *\n * Counterpart to Solidity's `uint120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toUint120(uint256 value) internal pure returns (uint120) {\n require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n return uint120(value);\n }\n\n /**\n * @dev Returns the downcasted uint112 from uint256, reverting on\n * overflow (when the input is greater than largest uint112).\n *\n * Counterpart to Solidity's `uint112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toUint112(uint256 value) internal pure returns (uint112) {\n require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n return uint112(value);\n }\n\n /**\n * @dev Returns the downcasted uint104 from uint256, reverting on\n * overflow (when the input is greater than largest uint104).\n *\n * Counterpart to Solidity's `uint104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toUint104(uint256 value) internal pure returns (uint104) {\n require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n return uint104(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.2._\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint88 from uint256, reverting on\n * overflow (when the input is greater than largest uint88).\n *\n * Counterpart to Solidity's `uint88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toUint88(uint256 value) internal pure returns (uint88) {\n require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n return uint88(value);\n }\n\n /**\n * @dev Returns the downcasted uint80 from uint256, reverting on\n * overflow (when the input is greater than largest uint80).\n *\n * Counterpart to Solidity's `uint80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toUint80(uint256 value) internal pure returns (uint80) {\n require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n return uint80(value);\n }\n\n /**\n * @dev Returns the downcasted uint72 from uint256, reverting on\n * overflow (when the input is greater than largest uint72).\n *\n * Counterpart to Solidity's `uint72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toUint72(uint256 value) internal pure returns (uint72) {\n require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n return uint72(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v2.5._\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint56 from uint256, reverting on\n * overflow (when the input is greater than largest uint56).\n *\n * Counterpart to Solidity's `uint56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toUint56(uint256 value) internal pure returns (uint56) {\n require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n return uint56(value);\n }\n\n /**\n * @dev Returns the downcasted uint48 from uint256, reverting on\n * overflow (when the input is greater than largest uint48).\n *\n * Counterpart to Solidity's `uint48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toUint48(uint256 value) internal pure returns (uint48) {\n require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return uint48(value);\n }\n\n /**\n * @dev Returns the downcasted uint40 from uint256, reverting on\n * overflow (when the input is greater than largest uint40).\n *\n * Counterpart to Solidity's `uint40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toUint40(uint256 value) internal pure returns (uint40) {\n require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n return uint40(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v2.5._\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint24 from uint256, reverting on\n * overflow (when the input is greater than largest uint24).\n *\n * Counterpart to Solidity's `uint24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toUint24(uint256 value) internal pure returns (uint24) {\n require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n return uint24(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v2.5._\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v2.5._\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n *\n * _Available since v3.0._\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int248 from int256, reverting on\n * overflow (when the input is less than smallest int248 or\n * greater than largest int248).\n *\n * Counterpart to Solidity's `int248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toInt248(int256 value) internal pure returns (int248 downcasted) {\n downcasted = int248(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n }\n\n /**\n * @dev Returns the downcasted int240 from int256, reverting on\n * overflow (when the input is less than smallest int240 or\n * greater than largest int240).\n *\n * Counterpart to Solidity's `int240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toInt240(int256 value) internal pure returns (int240 downcasted) {\n downcasted = int240(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n }\n\n /**\n * @dev Returns the downcasted int232 from int256, reverting on\n * overflow (when the input is less than smallest int232 or\n * greater than largest int232).\n *\n * Counterpart to Solidity's `int232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toInt232(int256 value) internal pure returns (int232 downcasted) {\n downcasted = int232(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n }\n\n /**\n * @dev Returns the downcasted int224 from int256, reverting on\n * overflow (when the input is less than smallest int224 or\n * greater than largest int224).\n *\n * Counterpart to Solidity's `int224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.7._\n */\n function toInt224(int256 value) internal pure returns (int224 downcasted) {\n downcasted = int224(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n }\n\n /**\n * @dev Returns the downcasted int216 from int256, reverting on\n * overflow (when the input is less than smallest int216 or\n * greater than largest int216).\n *\n * Counterpart to Solidity's `int216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toInt216(int256 value) internal pure returns (int216 downcasted) {\n downcasted = int216(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n }\n\n /**\n * @dev Returns the downcasted int208 from int256, reverting on\n * overflow (when the input is less than smallest int208 or\n * greater than largest int208).\n *\n * Counterpart to Solidity's `int208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toInt208(int256 value) internal pure returns (int208 downcasted) {\n downcasted = int208(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n }\n\n /**\n * @dev Returns the downcasted int200 from int256, reverting on\n * overflow (when the input is less than smallest int200 or\n * greater than largest int200).\n *\n * Counterpart to Solidity's `int200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toInt200(int256 value) internal pure returns (int200 downcasted) {\n downcasted = int200(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n }\n\n /**\n * @dev Returns the downcasted int192 from int256, reverting on\n * overflow (when the input is less than smallest int192 or\n * greater than largest int192).\n *\n * Counterpart to Solidity's `int192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toInt192(int256 value) internal pure returns (int192 downcasted) {\n downcasted = int192(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n }\n\n /**\n * @dev Returns the downcasted int184 from int256, reverting on\n * overflow (when the input is less than smallest int184 or\n * greater than largest int184).\n *\n * Counterpart to Solidity's `int184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toInt184(int256 value) internal pure returns (int184 downcasted) {\n downcasted = int184(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n }\n\n /**\n * @dev Returns the downcasted int176 from int256, reverting on\n * overflow (when the input is less than smallest int176 or\n * greater than largest int176).\n *\n * Counterpart to Solidity's `int176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toInt176(int256 value) internal pure returns (int176 downcasted) {\n downcasted = int176(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n }\n\n /**\n * @dev Returns the downcasted int168 from int256, reverting on\n * overflow (when the input is less than smallest int168 or\n * greater than largest int168).\n *\n * Counterpart to Solidity's `int168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toInt168(int256 value) internal pure returns (int168 downcasted) {\n downcasted = int168(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n }\n\n /**\n * @dev Returns the downcasted int160 from int256, reverting on\n * overflow (when the input is less than smallest int160 or\n * greater than largest int160).\n *\n * Counterpart to Solidity's `int160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toInt160(int256 value) internal pure returns (int160 downcasted) {\n downcasted = int160(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n }\n\n /**\n * @dev Returns the downcasted int152 from int256, reverting on\n * overflow (when the input is less than smallest int152 or\n * greater than largest int152).\n *\n * Counterpart to Solidity's `int152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toInt152(int256 value) internal pure returns (int152 downcasted) {\n downcasted = int152(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n }\n\n /**\n * @dev Returns the downcasted int144 from int256, reverting on\n * overflow (when the input is less than smallest int144 or\n * greater than largest int144).\n *\n * Counterpart to Solidity's `int144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toInt144(int256 value) internal pure returns (int144 downcasted) {\n downcasted = int144(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n }\n\n /**\n * @dev Returns the downcasted int136 from int256, reverting on\n * overflow (when the input is less than smallest int136 or\n * greater than largest int136).\n *\n * Counterpart to Solidity's `int136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toInt136(int256 value) internal pure returns (int136 downcasted) {\n downcasted = int136(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128 downcasted) {\n downcasted = int128(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n }\n\n /**\n * @dev Returns the downcasted int120 from int256, reverting on\n * overflow (when the input is less than smallest int120 or\n * greater than largest int120).\n *\n * Counterpart to Solidity's `int120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toInt120(int256 value) internal pure returns (int120 downcasted) {\n downcasted = int120(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n }\n\n /**\n * @dev Returns the downcasted int112 from int256, reverting on\n * overflow (when the input is less than smallest int112 or\n * greater than largest int112).\n *\n * Counterpart to Solidity's `int112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toInt112(int256 value) internal pure returns (int112 downcasted) {\n downcasted = int112(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n }\n\n /**\n * @dev Returns the downcasted int104 from int256, reverting on\n * overflow (when the input is less than smallest int104 or\n * greater than largest int104).\n *\n * Counterpart to Solidity's `int104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toInt104(int256 value) internal pure returns (int104 downcasted) {\n downcasted = int104(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n }\n\n /**\n * @dev Returns the downcasted int96 from int256, reverting on\n * overflow (when the input is less than smallest int96 or\n * greater than largest int96).\n *\n * Counterpart to Solidity's `int96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.7._\n */\n function toInt96(int256 value) internal pure returns (int96 downcasted) {\n downcasted = int96(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n }\n\n /**\n * @dev Returns the downcasted int88 from int256, reverting on\n * overflow (when the input is less than smallest int88 or\n * greater than largest int88).\n *\n * Counterpart to Solidity's `int88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toInt88(int256 value) internal pure returns (int88 downcasted) {\n downcasted = int88(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n }\n\n /**\n * @dev Returns the downcasted int80 from int256, reverting on\n * overflow (when the input is less than smallest int80 or\n * greater than largest int80).\n *\n * Counterpart to Solidity's `int80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toInt80(int256 value) internal pure returns (int80 downcasted) {\n downcasted = int80(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n }\n\n /**\n * @dev Returns the downcasted int72 from int256, reverting on\n * overflow (when the input is less than smallest int72 or\n * greater than largest int72).\n *\n * Counterpart to Solidity's `int72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toInt72(int256 value) internal pure returns (int72 downcasted) {\n downcasted = int72(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64 downcasted) {\n downcasted = int64(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n }\n\n /**\n * @dev Returns the downcasted int56 from int256, reverting on\n * overflow (when the input is less than smallest int56 or\n * greater than largest int56).\n *\n * Counterpart to Solidity's `int56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toInt56(int256 value) internal pure returns (int56 downcasted) {\n downcasted = int56(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n }\n\n /**\n * @dev Returns the downcasted int48 from int256, reverting on\n * overflow (when the input is less than smallest int48 or\n * greater than largest int48).\n *\n * Counterpart to Solidity's `int48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toInt48(int256 value) internal pure returns (int48 downcasted) {\n downcasted = int48(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n }\n\n /**\n * @dev Returns the downcasted int40 from int256, reverting on\n * overflow (when the input is less than smallest int40 or\n * greater than largest int40).\n *\n * Counterpart to Solidity's `int40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toInt40(int256 value) internal pure returns (int40 downcasted) {\n downcasted = int40(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32 downcasted) {\n downcasted = int32(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n }\n\n /**\n * @dev Returns the downcasted int24 from int256, reverting on\n * overflow (when the input is less than smallest int24 or\n * greater than largest int24).\n *\n * Counterpart to Solidity's `int24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toInt24(int256 value) internal pure returns (int24 downcasted) {\n downcasted = int24(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16 downcasted) {\n downcasted = int16(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8 downcasted) {\n downcasted = int8(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n *\n * _Available since v3.0._\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }\n}\n"
|
|
77
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCastUpgradeable {\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits.\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128) {\n require(value >= type(int128).min && value <= type(int128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return int128(value);\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64) {\n require(value >= type(int64).min && value <= type(int64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return int64(value);\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32) {\n require(value >= type(int32).min && value <= type(int32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return int32(value);\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16) {\n require(value >= type(int16).min && value <= type(int16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return int16(value);\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits.\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8) {\n require(value >= type(int8).min && value <= type(int8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return int8(value);\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }\n}\n"
|
|
81
78
|
},
|
|
82
79
|
"@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol": {
|
|
83
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts
|
|
80
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n}\n"
|
|
84
81
|
},
|
|
85
82
|
"@openzeppelin/contracts/access/Ownable.sol": {
|
|
86
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts
|
|
83
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor() {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n"
|
|
87
84
|
},
|
|
88
85
|
"@openzeppelin/contracts/security/ReentrancyGuard.sol": {
|
|
89
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts
|
|
86
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n constructor() {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n}\n"
|
|
90
87
|
},
|
|
91
88
|
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
|
|
92
89
|
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n"
|
|
@@ -98,13 +95,13 @@
|
|
|
98
95
|
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n"
|
|
99
96
|
},
|
|
100
97
|
"@openzeppelin/contracts/utils/cryptography/ECDSA.sol": {
|
|
101
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.
|
|
98
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Strings.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV\n }\n\n function _throwError(RecoverError error) private pure {\n if (error == RecoverError.NoError) {\n return; // no error: do nothing\n } else if (error == RecoverError.InvalidSignature) {\n revert(\"ECDSA: invalid signature\");\n } else if (error == RecoverError.InvalidSignatureLength) {\n revert(\"ECDSA: invalid signature length\");\n } else if (error == RecoverError.InvalidSignatureS) {\n revert(\"ECDSA: invalid signature 's' value\");\n } else if (error == RecoverError.InvalidSignatureV) {\n revert(\"ECDSA: invalid signature 'v' value\");\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature` or error string. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n *\n * Documentation for signature generation:\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n // Check the signature length\n // - case 65: r,s,v signature (standard)\n // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._\n if (signature.length == 65) {\n bytes32 r;\n bytes32 s;\n uint8 v;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n return tryRecover(hash, v, r, s);\n } else if (signature.length == 64) {\n bytes32 r;\n bytes32 vs;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n assembly {\n r := mload(add(signature, 0x20))\n vs := mload(add(signature, 0x40))\n }\n return tryRecover(hash, r, vs);\n } else {\n return (address(0), RecoverError.InvalidSignatureLength);\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, signature);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n *\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n *\n * _Available since v4.3._\n */\n function tryRecover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address, RecoverError) {\n bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n uint8 v = uint8((uint256(vs) >> 255) + 27);\n return tryRecover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n *\n * _Available since v4.2._\n */\n function recover(\n bytes32 hash,\n bytes32 r,\n bytes32 vs\n ) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n * `r` and `s` signature fields separately.\n *\n * _Available since v4.3._\n */\n function tryRecover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address, RecoverError) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n return (address(0), RecoverError.InvalidSignatureS);\n }\n if (v != 27 && v != 28) {\n return (address(0), RecoverError.InvalidSignatureV);\n }\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n if (signer == address(0)) {\n return (address(0), RecoverError.InvalidSignature);\n }\n\n return (signer, RecoverError.NoError);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(\n bytes32 hash,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", hash));\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from `s`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x01\", domainSeparator, structHash));\n }\n}\n"
|
|
102
99
|
},
|
|
103
100
|
"@openzeppelin/contracts/utils/math/Math.sol": {
|
|
104
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n"
|
|
101
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a >= b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a / b + (a % b == 0 ? 0 : 1);\n }\n}\n"
|
|
105
102
|
},
|
|
106
103
|
"@openzeppelin/contracts/utils/Strings.sol": {
|
|
107
|
-
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts
|
|
104
|
+
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n}\n"
|
|
108
105
|
},
|
|
109
106
|
"@thesis/solidity-contracts/contracts/token/IApproveAndCall.sol": {
|
|
110
107
|
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.4;\n\n/// @notice An interface that should be implemented by tokens supporting\n/// `approveAndCall`/`receiveApproval` pattern.\ninterface IApproveAndCall {\n /// @notice Executes `receiveApproval` function on spender as specified in\n /// `IReceiveApproval` interface. Approves spender to withdraw from\n /// the caller multiple times, up to the `amount`. If this\n /// function is called again, it overwrites the current allowance\n /// with `amount`. Reverts if the approval reverted or if\n /// `receiveApproval` call on the spender reverted.\n function approveAndCall(\n address spender,\n uint256 amount,\n bytes memory extraData\n ) external returns (bool);\n}\n"
|
|
@@ -125,7 +122,7 @@
|
|
|
125
122
|
"content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity 0.8.17;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\nimport {ValidateSPV} from \"@keep-network/bitcoin-spv-sol/contracts/ValidateSPV.sol\";\n\nimport \"./BridgeState.sol\";\n\n/// @title Bitcoin transaction\n/// @notice Allows to reference Bitcoin raw transaction in Solidity.\n/// @dev See https://developer.bitcoin.org/reference/transactions.html#raw-transaction-format\n///\n/// Raw Bitcoin transaction data:\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|--------------|------------------------|---------------------------|\n/// | 4 | version | int32_t (LE) | TX version number |\n/// | varies | tx_in_count | compactSize uint (LE) | Number of TX inputs |\n/// | varies | tx_in | txIn[] | TX inputs |\n/// | varies | tx_out_count | compactSize uint (LE) | Number of TX outputs |\n/// | varies | tx_out | txOut[] | TX outputs |\n/// | 4 | lock_time | uint32_t (LE) | Unix time or block number |\n///\n//\n/// Non-coinbase transaction input (txIn):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|------------------|------------------------|---------------------------------------------|\n/// | 36 | previous_output | outpoint | The previous outpoint being spent |\n/// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the signature script |\n/// | varies | signature_script | char[] | The signature script, empty for P2WSH |\n/// | 4 | sequence | uint32_t (LE) | Sequence number |\n///\n///\n/// The reference to transaction being spent (outpoint):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |-------|-------|---------------|------------------------------------------|\n/// | 32 | hash | char[32] | Hash of the transaction to spend |\n/// | 4 | index | uint32_t (LE) | Index of the specific output from the TX |\n///\n///\n/// Transaction output (txOut):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|-----------------|-----------------------|--------------------------------------|\n/// | 8 | value | int64_t (LE) | Number of satoshis to spend |\n/// | 1+ | pk_script_bytes | compactSize uint (LE) | Number of bytes in the pubkey script |\n/// | varies | pk_script | char[] | Pubkey script |\n///\n/// compactSize uint format:\n///\n/// | Value | Bytes | Format |\n/// |-----------------------------------------|-------|----------------------------------------------|\n/// | >= 0 && <= 252 | 1 | uint8_t |\n/// | >= 253 && <= 0xffff | 3 | 0xfd followed by the number as uint16_t (LE) |\n/// | >= 0x10000 && <= 0xffffffff | 5 | 0xfe followed by the number as uint32_t (LE) |\n/// | >= 0x100000000 && <= 0xffffffffffffffff | 9 | 0xff followed by the number as uint64_t (LE) |\n///\n/// (*) compactSize uint is often references as VarInt)\n///\n/// Coinbase transaction input (txIn):\n///\n/// | Bytes | Name | BTC type | Description |\n/// |--------|------------------|------------------------|---------------------------------------------|\n/// | 32 | hash | char[32] | A 32-byte 0x0 null (no previous_outpoint) |\n/// | 4 | index | uint32_t (LE) | 0xffffffff (no previous_outpoint) |\n/// | varies | script_bytes | compactSize uint (LE) | The number of bytes in the coinbase script |\n/// | varies | height | char[] | The block height of this block (BIP34) (*) |\n/// | varies | coinbase_script | none | Arbitrary data, max 100 bytes |\n/// | 4 | sequence | uint32_t (LE) | Sequence number\n///\n/// (*) Uses script language: starts with a data-pushing opcode that indicates how many bytes to push to\n/// the stack followed by the block height as a little-endian unsigned integer. This script must be as\n/// short as possible, otherwise it may be rejected. The data-pushing opcode will be 0x03 and the total\n/// size four bytes until block 16,777,216 about 300 years from now.\nlibrary BitcoinTx {\n using BTCUtils for bytes;\n using BTCUtils for uint256;\n using BytesLib for bytes;\n using ValidateSPV for bytes;\n using ValidateSPV for bytes32;\n\n /// @notice Represents Bitcoin transaction data.\n struct Info {\n /// @notice Bitcoin transaction version.\n /// @dev `version` from raw Bitcoin transaction data.\n /// Encoded as 4-bytes signed integer, little endian.\n bytes4 version;\n /// @notice All Bitcoin transaction inputs, prepended by the number of\n /// transaction inputs.\n /// @dev `tx_in_count | tx_in` from raw Bitcoin transaction data.\n ///\n /// The number of transaction inputs encoded as compactSize\n /// unsigned integer, little-endian.\n ///\n /// Note that some popular block explorers reverse the order of\n /// bytes from `outpoint`'s `hash` and display it as big-endian.\n /// Solidity code of Bridge expects hashes in little-endian, just\n /// like they are represented in a raw Bitcoin transaction.\n bytes inputVector;\n /// @notice All Bitcoin transaction outputs prepended by the number of\n /// transaction outputs.\n /// @dev `tx_out_count | tx_out` from raw Bitcoin transaction data.\n ///\n /// The number of transaction outputs encoded as a compactSize\n /// unsigned integer, little-endian.\n bytes outputVector;\n /// @notice Bitcoin transaction locktime.\n ///\n /// @dev `lock_time` from raw Bitcoin transaction data.\n /// Encoded as 4-bytes unsigned integer, little endian.\n bytes4 locktime;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents data needed to perform a Bitcoin SPV proof.\n struct Proof {\n /// @notice The merkle proof of transaction inclusion in a block.\n bytes merkleProof;\n /// @notice Transaction index in the block (0-indexed).\n uint256 txIndexInBlock;\n /// @notice Single byte-string of 80-byte bitcoin headers,\n /// lowest height first.\n bytes bitcoinHeaders;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents info about an unspent transaction output.\n struct UTXO {\n /// @notice Hash of the transaction the output belongs to.\n /// @dev Byte order corresponds to the Bitcoin internal byte order.\n bytes32 txHash;\n /// @notice Index of the transaction output (0-indexed).\n uint32 txOutputIndex;\n /// @notice Value of the transaction output.\n uint64 txOutputValue;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents Bitcoin signature in the R/S/V format.\n struct RSVSignature {\n /// @notice Signature r value.\n bytes32 r;\n /// @notice Signature s value.\n bytes32 s;\n /// @notice Signature recovery value.\n uint8 v;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Validates the SPV proof of the Bitcoin transaction.\n /// Reverts in case the validation or proof verification fail.\n /// @param txInfo Bitcoin transaction data.\n /// @param proof Bitcoin proof data.\n /// @return txHash Proven 32-byte transaction hash.\n function validateProof(\n BridgeState.Storage storage self,\n Info calldata txInfo,\n Proof calldata proof\n ) internal view returns (bytes32 txHash) {\n require(\n txInfo.inputVector.validateVin(),\n \"Invalid input vector provided\"\n );\n require(\n txInfo.outputVector.validateVout(),\n \"Invalid output vector provided\"\n );\n\n txHash = abi\n .encodePacked(\n txInfo.version,\n txInfo.inputVector,\n txInfo.outputVector,\n txInfo.locktime\n )\n .hash256View();\n\n require(\n txHash.prove(\n proof.bitcoinHeaders.extractMerkleRootLE(),\n proof.merkleProof,\n proof.txIndexInBlock\n ),\n \"Tx merkle proof is not valid for provided header and tx hash\"\n );\n\n evaluateProofDifficulty(self, proof.bitcoinHeaders);\n\n return txHash;\n }\n\n /// @notice Evaluates the given Bitcoin proof difficulty against the actual\n /// Bitcoin chain difficulty provided by the relay oracle.\n /// Reverts in case the evaluation fails.\n /// @param bitcoinHeaders Bitcoin headers chain being part of the SPV\n /// proof. Used to extract the observed proof difficulty.\n function evaluateProofDifficulty(\n BridgeState.Storage storage self,\n bytes memory bitcoinHeaders\n ) internal view {\n IRelay relay = self.relay;\n uint256 currentEpochDifficulty = relay.getCurrentEpochDifficulty();\n uint256 previousEpochDifficulty = relay.getPrevEpochDifficulty();\n\n uint256 requestedDiff = 0;\n uint256 firstHeaderDiff = bitcoinHeaders\n .extractTarget()\n .calculateDifficulty();\n\n if (firstHeaderDiff == currentEpochDifficulty) {\n requestedDiff = currentEpochDifficulty;\n } else if (firstHeaderDiff == previousEpochDifficulty) {\n requestedDiff = previousEpochDifficulty;\n } else {\n revert(\"Not at current or previous difficulty\");\n }\n\n uint256 observedDiff = bitcoinHeaders.validateHeaderChain();\n\n require(\n observedDiff != ValidateSPV.getErrBadLength(),\n \"Invalid length of the headers chain\"\n );\n require(\n observedDiff != ValidateSPV.getErrInvalidChain(),\n \"Invalid headers chain\"\n );\n require(\n observedDiff != ValidateSPV.getErrLowWork(),\n \"Insufficient work in a header\"\n );\n\n require(\n observedDiff >= requestedDiff * self.txProofDifficultyFactor,\n \"Insufficient accumulated difficulty in header chain\"\n );\n }\n\n /// @notice Extracts public key hash from the provided P2PKH or P2WPKH output.\n /// Reverts if the validation fails.\n /// @param output The transaction output.\n /// @return pubKeyHash 20-byte public key hash the output locks funds on.\n /// @dev Requirements:\n /// - The output must be of P2PKH or P2WPKH type and lock the funds\n /// on a 20-byte public key hash.\n function extractPubKeyHash(BridgeState.Storage storage, bytes memory output)\n internal\n pure\n returns (bytes20 pubKeyHash)\n {\n bytes memory pubKeyHashBytes = output.extractHash();\n\n require(\n pubKeyHashBytes.length == 20,\n \"Output's public key hash must have 20 bytes\"\n );\n\n pubKeyHash = pubKeyHashBytes.slice20(0);\n\n // The output consists of an 8-byte value and a variable length script.\n // To extract just the script, we ignore the first 8 bytes.\n uint256 scriptLen = output.length - 8;\n\n // The P2PKH script is 26 bytes long.\n // The P2WPKH script is 23 bytes long.\n // A valid script must have one of these lengths,\n // and we can identify the expected script type by the length.\n require(\n scriptLen == 26 || scriptLen == 23,\n \"Output must be P2PKH or P2WPKH\"\n );\n\n if (scriptLen == 26) {\n // Compare to the expected P2PKH script.\n bytes26 script = bytes26(output.slice32(8));\n\n require(\n script == makeP2PKHScript(pubKeyHash),\n \"Invalid P2PKH script\"\n );\n }\n\n if (scriptLen == 23) {\n // Compare to the expected P2WPKH script.\n bytes23 script = bytes23(output.slice32(8));\n\n require(\n script == makeP2WPKHScript(pubKeyHash),\n \"Invalid P2WPKH script\"\n );\n }\n\n return pubKeyHash;\n }\n\n /// @notice Build the P2PKH script from the given public key hash.\n /// @param pubKeyHash The 20-byte public key hash.\n /// @return The P2PKH script.\n /// @dev The P2PKH script has the following byte format:\n /// <0x1976a914> <20-byte PKH> <0x88ac>. According to\n /// https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n /// - 0x19: Byte length of the entire script\n /// - 0x76: OP_DUP\n /// - 0xa9: OP_HASH160\n /// - 0x14: Byte length of the public key hash\n /// - 0x88: OP_EQUALVERIFY\n /// - 0xac: OP_CHECKSIG\n /// which matches the P2PKH structure as per:\n /// https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash\n function makeP2PKHScript(bytes20 pubKeyHash)\n internal\n pure\n returns (bytes26)\n {\n bytes26 P2PKHScriptMask = hex\"1976a914000000000000000000000000000000000000000088ac\";\n\n return ((bytes26(pubKeyHash) >> 32) | P2PKHScriptMask);\n }\n\n /// @notice Build the P2WPKH script from the given public key hash.\n /// @param pubKeyHash The 20-byte public key hash.\n /// @return The P2WPKH script.\n /// @dev The P2WPKH script has the following format:\n /// <0x160014> <20-byte PKH>. According to\n /// https://en.bitcoin.it/wiki/Script#Opcodes this translates to:\n /// - 0x16: Byte length of the entire script\n /// - 0x00: OP_0\n /// - 0x14: Byte length of the public key hash\n /// which matches the P2WPKH structure as per:\n /// https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#P2WPKH\n function makeP2WPKHScript(bytes20 pubKeyHash)\n internal\n pure\n returns (bytes23)\n {\n bytes23 P2WPKHScriptMask = hex\"1600140000000000000000000000000000000000000000\";\n\n return ((bytes23(pubKeyHash) >> 24) | P2WPKHScriptMask);\n }\n}\n"
|
|
126
123
|
},
|
|
127
124
|
"contracts/bridge/Bridge.sol": {
|
|
128
|
-
"content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity 0.8.17;\n\nimport \"@keep-network/random-beacon/contracts/Governable.sol\";\nimport \"@keep-network/random-beacon/contracts/ReimbursementPool.sol\";\nimport {IWalletOwner as EcdsaWalletOwner} from \"@keep-network/ecdsa/contracts/api/IWalletOwner.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Deposit.sol\";\nimport \"./DepositSweep.sol\";\nimport \"./Redemption.sol\";\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./Wallets.sol\";\nimport \"./Fraud.sol\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/IReceiveBalanceApproval.sol\";\nimport \"../bank/Bank.sol\";\n\n/// @title Bitcoin Bridge\n/// @notice Bridge manages BTC deposit and redemption flow and is increasing and\n/// decreasing balances in the Bank as a result of BTC deposit and\n/// redemption operations performed by depositors and redeemers.\n///\n/// Depositors send BTC funds to the most recently created off-chain\n/// ECDSA wallet of the bridge using pay-to-script-hash (P2SH) or\n/// pay-to-witness-script-hash (P2WSH) containing hashed information\n/// about the depositor’s Ethereum address. Then, the depositor reveals\n/// their Ethereum address along with their deposit blinding factor,\n/// refund public key hash and refund locktime to the Bridge on Ethereum\n/// chain. The off-chain ECDSA wallet listens for these sorts of\n/// messages and when it gets one, it checks the Bitcoin network to make\n/// sure the deposit lines up. If it does, the off-chain ECDSA wallet\n/// may decide to pick the deposit transaction for sweeping, and when\n/// the sweep operation is confirmed on the Bitcoin network, the ECDSA\n/// wallet informs the Bridge about the sweep increasing appropriate\n/// balances in the Bank.\n/// @dev Bridge is an upgradeable component of the Bank. The order of\n/// functionalities in this contract is: deposit, sweep, redemption,\n/// moving funds, wallet lifecycle, frauds, parameters.\ncontract Bridge is\n Governable,\n EcdsaWalletOwner,\n Initializable,\n IReceiveBalanceApproval\n{\n using BridgeState for BridgeState.Storage;\n using Deposit for BridgeState.Storage;\n using DepositSweep for BridgeState.Storage;\n using Redemption for BridgeState.Storage;\n using MovingFunds for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using Fraud for BridgeState.Storage;\n\n BridgeState.Storage internal self;\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address indexed depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 indexed walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n event RedemptionRequested(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript,\n address indexed redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event MovingFundsCommitmentSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsTimeoutReset(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 indexed walletPubKeyHash);\n\n event MovedFundsSwept(\n bytes20 indexed walletPubKeyHash,\n bytes32 sweepTxHash\n );\n\n event MovedFundsSweepTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex\n );\n\n event NewWalletRequested();\n\n event NewWalletRegistered(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosing(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosed(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletTerminated(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event FraudChallengeSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event FraudChallengeDefeatTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event VaultStatusUpdated(address indexed vault, bool isTrusted);\n\n event SpvMaintainerStatusUpdated(\n address indexed spvMaintainer,\n bool isTrusted\n );\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint96 fraudChallengeDepositAmount,\n uint32 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint32 fraudNotifierRewardMultiplier\n );\n\n event TreasuryUpdated(address treasury);\n\n modifier onlySpvMaintainer() {\n require(\n self.isSpvMaintainer[msg.sender],\n \"Caller is not SPV maintainer\"\n );\n _;\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor() {\n _disableInitializers();\n }\n\n /// @dev Initializes upgradable contract on deployment.\n /// @param _bank Address of the Bank the Bridge belongs to.\n /// @param _relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @param _treasury Address where the deposit and redemption treasury fees\n /// will be sent to.\n /// @param _ecdsaWalletRegistry Address of the ECDSA Wallet Registry contract.\n /// @param _reimbursementPool Address of the Reimbursement Pool contract.\n /// @param _txProofDifficultyFactor The number of confirmations on the Bitcoin\n /// chain required to successfully evaluate an SPV proof.\n function initialize(\n address _bank,\n address _relay,\n address _treasury,\n address _ecdsaWalletRegistry,\n address payable _reimbursementPool,\n uint96 _txProofDifficultyFactor\n ) external initializer {\n require(_bank != address(0), \"Bank address cannot be zero\");\n self.bank = Bank(_bank);\n\n require(_relay != address(0), \"Relay address cannot be zero\");\n self.relay = IRelay(_relay);\n\n require(\n _ecdsaWalletRegistry != address(0),\n \"ECDSA Wallet Registry address cannot be zero\"\n );\n self.ecdsaWalletRegistry = EcdsaWalletRegistry(_ecdsaWalletRegistry);\n\n require(\n _reimbursementPool != address(0),\n \"Reimbursement Pool address cannot be zero\"\n );\n self.reimbursementPool = ReimbursementPool(_reimbursementPool);\n\n require(_treasury != address(0), \"Treasury address cannot be zero\");\n self.treasury = _treasury;\n\n self.txProofDifficultyFactor = _txProofDifficultyFactor;\n\n //\n // All parameters set in the constructor are initial ones, used at the\n // moment contracts were deployed for the first time. Parameters are\n // governable and values assigned in the constructor do not need to\n // reflect the current ones. Keep in mind the initial parameters are\n // pretty forgiving and valid only for the early stage of the network.\n //\n\n self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.depositTxMaxFee = 100000; // 100000 satoshi = 0.001 BTC\n self.depositRevealAheadPeriod = 15 days;\n self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionTxMaxFee = 100000; // 100000 satoshi = 0.001 BTC\n self.redemptionTxMaxTotalFee = 1000000; // 1000000 satoshi = 0.01 BTC\n self.redemptionTimeout = 5 days;\n self.redemptionTimeoutSlashingAmount = 100 * 1e18; // 100 T\n self.redemptionTimeoutNotifierRewardMultiplier = 100; // 100%\n self.movingFundsTxMaxTotalFee = 100000; // 100000 satoshi = 0.001 BTC\n self.movingFundsDustThreshold = 200000; // 200000 satoshi = 0.002 BTC\n self.movingFundsTimeoutResetDelay = 6 days;\n self.movingFundsTimeout = 7 days;\n self.movingFundsTimeoutSlashingAmount = 100 * 1e18; // 100 T\n self.movingFundsTimeoutNotifierRewardMultiplier = 100; //100%\n self.movingFundsCommitmentGasOffset = 15000;\n self.movedFundsSweepTxMaxTotalFee = 100000; // 100000 satoshi = 0.001 BTC\n self.movedFundsSweepTimeout = 7 days;\n self.movedFundsSweepTimeoutSlashingAmount = 100 * 1e18; // 100 T\n self.movedFundsSweepTimeoutNotifierRewardMultiplier = 100; //100%\n self.fraudChallengeDepositAmount = 5 ether;\n self.fraudChallengeDefeatTimeout = 7 days;\n self.fraudSlashingAmount = 100 * 1e18; // 100 T\n self.fraudNotifierRewardMultiplier = 100; // 100%\n self.walletCreationPeriod = 1 weeks;\n self.walletCreationMinBtcBalance = 1e8; // 1 BTC\n self.walletCreationMaxBtcBalance = 100e8; // 100 BTC\n self.walletClosureMinBtcBalance = 5 * 1e7; // 0.5 BTC\n self.walletMaxAge = 26 weeks; // ~6 months\n self.walletMaxBtcTransfer = 10e8; // 10 BTC\n self.walletClosingPeriod = 40 days;\n\n _transferGovernance(msg.sender);\n }\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`.\n /// @param reveal Deposit reveal data, see `RevealInfo struct.\n /// @dev Requirements:\n /// - This function must be called by the same Ethereum address as the\n /// one used in the P2(W)SH BTC deposit transaction as a depositor,\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet,\n /// - `reveal.vault` must be 0x0 or point to a trusted vault,\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BitcoinTx.Info calldata fundingTx,\n Deposit.DepositRevealInfo calldata reveal\n ) external {\n self.revealDeposit(fundingTx, reveal);\n }\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data.\n /// @param sweepProof Bitcoin sweep proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @param vault Optional address of the vault where all swept deposits\n /// should be routed to. All deposits swept as part of the transaction\n /// must have their `vault` parameters set to the same address.\n /// If this parameter is set to an address of a trusted vault, swept\n /// deposits are routed to that vault.\n /// If this parameter is set to the zero address or to an address\n /// of a non-trusted vault, swept deposits are not routed to a\n /// vault but depositors' balances are increased in the Bank\n /// individually.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash,\n /// - All revealed deposits that are swept by `sweepTx` must have\n /// their `vault` parameters set to the same address as the address\n /// passed in the `vault` function parameter,\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitDepositSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo,\n address vault\n ) external onlySpvMaintainer {\n self.submitDepositSweepProof(sweepTx, sweepProof, mainUtxo, vault);\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script. Handles the\n /// simplest case in which the redeemer's balance is decreased in\n /// the Bank.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key).\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC.\n /// @param amount Requested amount in satoshi. This is also the Bank balance\n /// that is taken from the `balanceOwner` upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain,\n /// - `redeemerOutputScript` must be a proper Bitcoin script,\n /// - `redeemerOutputScript` cannot have wallet PKH as payload,\n /// - `amount` must be above or equal the `redemptionDustThreshold`,\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time,\n /// - Wallet must have enough Bitcoin balance to process the request,\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n self.requestRedemption(\n walletPubKeyHash,\n mainUtxo,\n msg.sender,\n redeemerOutputScript,\n amount\n );\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script. Used by\n /// `Bank.approveBalanceAndCall`. Can handle more complex cases\n /// where balance owner may be someone else than the redeemer.\n /// For example, vault redeeming its balance for some depositor.\n /// @param balanceOwner The address of the Bank balance owner whose balance\n /// is getting redeemed.\n /// @param amount Requested amount in satoshi. This is also the Bank balance\n /// that is taken from the `balanceOwner` upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @param redemptionData ABI-encoded redemption data:\n /// [\n /// address redeemer,\n /// bytes20 walletPubKeyHash,\n /// bytes32 mainUtxoTxHash,\n /// uint32 mainUtxoTxOutputIndex,\n /// uint64 mainUtxoTxOutputValue,\n /// bytes redeemerOutputScript\n /// ]\n ///\n /// - redeemer: The Ethereum address of the redeemer who will be able\n /// to claim Bank balance if anything goes wrong during the redemption.\n /// In the most basic case, when someone redeems their balance\n /// from the Bank, `balanceOwner` is the same as `redeemer`.\n /// However, when a Vault is redeeming part of its balance for some\n /// redeemer address (for example, someone who has earlier deposited\n /// into that Vault), `balanceOwner` is the Vault, and `redeemer` is\n /// the address for which the vault is redeeming its balance to,\n /// - walletPubKeyHash: The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key),\n /// - mainUtxoTxHash: Data of the wallet's main UTXO TX hash, as\n /// currently known on the Ethereum chain,\n /// - mainUtxoTxOutputIndex: Data of the wallet's main UTXO output\n /// index, as currently known on Ethereum chain,\n /// - mainUtxoTxOutputValue: Data of the wallet's main UTXO output\n /// value, as currently known on Ethereum chain,\n /// - redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC.\n /// @dev Requirements:\n /// - The caller must be the Bank,\n /// - Wallet behind `walletPubKeyHash` must be live,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain,\n /// - `redeemerOutputScript` must be a proper Bitcoin script,\n /// - `redeemerOutputScript` cannot have wallet PKH as payload,\n /// - `amount` must be above or equal the `redemptionDustThreshold`,\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time,\n /// - Wallet must have enough Bitcoin balance to process the request.\n ///\n /// Note on upgradeability:\n /// Bridge is an upgradeable contract deployed behind\n /// a TransparentUpgradeableProxy. Accepting redemption data as bytes\n /// provides great flexibility. The Bridge is just like any other\n /// contract with a balance approved in the Bank and can be upgraded\n /// to another version without being bound to a particular interface\n /// forever. This flexibility comes with the cost - developers\n /// integrating their vaults and dApps with `Bridge` using\n /// `approveBalanceAndCall` need to pay extra attention to\n /// `redemptionData` and adjust the code in case the expected structure\n /// of `redemptionData` changes.\n function receiveBalanceApproval(\n address balanceOwner,\n uint256 amount,\n bytes calldata redemptionData\n ) external override {\n require(msg.sender == address(self.bank), \"Caller is not the bank\");\n\n self.requestRedemption(\n balanceOwner,\n SafeCastUpgradeable.toUint64(amount),\n redemptionData\n );\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data.\n /// @param redemptionProof Bitcoin redemption proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance,\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external onlySpvMaintainer {\n self.submitRedemptionProof(\n redemptionTx,\n redemptionProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.\n /// The results of calling this function:\n /// - The pending redemptions value for the wallet will be decreased\n /// by the requested amount (minus treasury fee),\n /// - The tokens taken from the redeemer on redemption request will\n /// be returned to the redeemer,\n /// - The request will be moved from pending redemptions to\n /// timed-out redemptions,\n /// - If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed and the notifier will be\n /// rewarded,\n /// - If the state of wallet is `Live`, the wallet will be closed or\n /// marked as `MovingFunds` (depending on the presence or absence\n /// of the wallet's main UTXO) and the wallet will no longer be\n /// marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH).\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Terminated state,\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs,\n bytes calldata redeemerOutputScript\n ) external {\n self.notifyRedemptionTimeout(\n walletPubKeyHash,\n walletMembersIDs,\n redeemerOutputScript\n );\n }\n\n /// @notice Submits the moving funds target wallets commitment.\n /// Once all requirements are met, that function registers the\n /// target wallets commitment and opens the way for moving funds\n /// proof submission.\n /// The caller is reimbursed for the transaction costs.\n /// @param walletPubKeyHash 20-byte public key hash of the source wallet.\n /// @param walletMainUtxo Data of the source wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletMembersIDs Identifiers of the source wallet signing group\n /// members.\n /// @param walletMemberIndex Position of the caller in the source wallet\n /// signing group members list.\n /// @param targetWallets List of 20-byte public key hashes of the target\n /// wallets that the source wallet commits to move the funds to.\n /// @dev Requirements:\n /// - The source wallet must be in the MovingFunds state,\n /// - The source wallet must not have pending redemption requests,\n /// - The source wallet must not have pending moved funds sweep requests,\n /// - The source wallet must not have submitted its commitment already,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given source wallet in the ECDSA registry. Those IDs are\n /// not directly stored in the contract for gas efficiency purposes\n /// but they can be read from appropriate `DkgResultSubmitted`\n /// and `DkgResultApproved` events,\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length],\n /// - The caller must be the member of the source wallet signing group\n /// at the position indicated by `walletMemberIndex` parameter,\n /// - The `walletMainUtxo` components must point to the recent main\n /// UTXO of the source wallet, as currently known on the Ethereum\n /// chain,\n /// - Source wallet BTC balance must be greater than zero,\n /// - At least one Live wallet must exist in the system,\n /// - Submitted target wallets count must match the expected count\n /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`\n /// where `N > 0`,\n /// - Each target wallet must be not equal to the source wallet,\n /// - Each target wallet must follow the expected order i.e. all\n /// target wallets 20-byte public key hashes represented as numbers\n /// must form a strictly increasing sequence without duplicates,\n /// - Each target wallet must be in Live state.\n function submitMovingFundsCommitment(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo,\n uint32[] calldata walletMembersIDs,\n uint256 walletMemberIndex,\n bytes20[] calldata targetWallets\n ) external {\n uint256 gasStart = gasleft();\n\n self.submitMovingFundsCommitment(\n walletPubKeyHash,\n walletMainUtxo,\n walletMembersIDs,\n walletMemberIndex,\n targetWallets\n );\n\n self.reimbursementPool.refund(\n (gasStart - gasleft()) + self.movingFundsCommitmentGasOffset,\n msg.sender\n );\n }\n\n /// @notice Resets the moving funds timeout for the given wallet if the\n /// target wallet commitment cannot be submitted due to a lack\n /// of live wallets in the system.\n /// @param walletPubKeyHash 20-byte public key hash of the moving funds wallet.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The target wallets commitment must not be already submitted for\n /// the given moving funds wallet,\n /// - Live wallets count must be zero,\n /// - The moving funds timeout reset delay must be elapsed.\n function resetMovingFundsTimeout(bytes20 walletPubKeyHash) external {\n self.resetMovingFundsTimeout(walletPubKeyHash);\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data.\n /// @param movingFundsProof Bitcoin moving funds proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction.\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment,\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input,\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state,\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external onlySpvMaintainer {\n self.submitMovingFundsProof(\n movingFundsTx,\n movingFundsProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies about a timed out moving funds process. Terminates\n /// the wallet and slashes signing group members as a result.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The moving funds timeout must be actually exceeded,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovingFundsTimeout(\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovingFundsTimeout(walletPubKeyHash, walletMembersIDs);\n }\n\n /// @notice Notifies about a moving funds wallet whose BTC balance is\n /// below the moving funds dust threshold. Ends the moving funds\n /// process and begins wallet closing immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known\n /// on the Ethereum chain.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If the wallet has no main UTXO, this parameter can be empty as it\n /// is ignored,\n /// - The wallet BTC balance must be below the moving funds threshold.\n function notifyMovingFundsBelowDust(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.notifyMovingFundsBelowDust(walletPubKeyHash, mainUtxo);\n }\n\n /// @notice Used by the wallet to prove the BTC moved funds sweep\n /// transaction and to make the necessary state changes. Moved\n /// funds sweep is only accepted if it satisfies SPV proof.\n ///\n /// The function validates the sweep transaction structure by\n /// checking if it actually spends the moved funds UTXO and the\n /// sweeping wallet's main UTXO (optionally), and if it locks the\n /// value on the sweeping wallet's 20-byte public key hash using a\n /// reasonable transaction fee. If all preconditions are\n /// met, this function updates the sweeping wallet main UTXO, thus\n /// their BTC balance.\n ///\n /// It is possible to prove the given sweep transaction only\n /// one time.\n /// @param sweepTx Bitcoin sweep funds transaction data.\n /// @param sweepProof Bitcoin sweep funds proof data.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with\n /// the first input pointing to a moved funds sweep request targeted\n /// to the wallet, and optionally, the second input pointing to the\n /// wallet's main UTXO, if the sweeping wallet has a main UTXO set.\n /// There should be only one output locking funds on the sweeping\n /// wallet 20-byte public key hash,\n /// - `sweepProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the sweeping wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored,\n /// - The sweeping wallet must be in the Live or MovingFunds state,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movedFundsSweepTxMaxTotalFee` governable parameter.\n function submitMovedFundsSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external onlySpvMaintainer {\n self.submitMovedFundsSweepProof(sweepTx, sweepProof, mainUtxo);\n }\n\n /// @notice Notifies about a timed out moved funds sweep process. If the\n /// wallet is not terminated yet, that function terminates\n /// the wallet and slashes signing group members as a result.\n /// Marks the given sweep request as TimedOut.\n /// @param movingFundsTxHash 32-byte hash of the moving funds transaction\n /// that caused the sweep request to be created.\n /// @param movingFundsTxOutputIndex Index of the moving funds transaction\n /// output that is subject of the sweep request.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The moved funds sweep request must be in the Pending state,\n /// - The moved funds sweep timeout must be actually exceeded,\n /// - The wallet must be either in the Live or MovingFunds or\n /// Terminated state,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovedFundsSweepTimeout(\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovedFundsSweepTimeout(\n movingFundsTxHash,\n movingFundsTxOutputIndex,\n walletMembersIDs\n );\n }\n\n /// @notice Requests creation of a new wallet. This function just\n /// forms a request and the creation process is performed\n /// asynchronously. Once a wallet is created, the ECDSA Wallet\n /// Registry will notify this contract by calling the\n /// `__ecdsaWalletCreatedCallback` function.\n /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @dev Requirements:\n /// - `activeWalletMainUtxo` components must point to the recent main\n /// UTXO of the given active wallet, as currently known on the\n /// Ethereum chain. If there is no active wallet at the moment, or\n /// the active wallet has no main UTXO, this parameter can be\n /// empty as it is ignored,\n /// - Wallet creation must not be in progress,\n /// - If the active wallet is set, one of the following\n /// conditions must be true:\n /// - The active wallet BTC balance is above the minimum threshold\n /// and the active wallet is old enough, i.e. the creation period\n /// was elapsed since its creation time,\n /// - The active wallet BTC balance is above the maximum threshold.\n function requestNewWallet(BitcoinTx.UTXO calldata activeWalletMainUtxo)\n external\n {\n self.requestNewWallet(activeWalletMainUtxo);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a new ECDSA wallet is created.\n /// @param ecdsaWalletID Wallet's unique identifier.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Given wallet data must not belong to an already registered wallet.\n function __ecdsaWalletCreatedCallback(\n bytes32 ecdsaWalletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.registerNewWallet(ecdsaWalletID, publicKeyX, publicKeyY);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a wallet heartbeat failure is detected.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Wallet must be in Live state.\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.notifyWalletHeartbeatFailed(publicKeyX, publicKeyY);\n }\n\n /// @notice Notifies that the wallet is either old enough or has too few\n /// satoshi left and qualifies to be closed.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - Wallet must not be set as the current active wallet,\n /// - Wallet must exceed the wallet maximum age OR the wallet BTC\n /// balance must be lesser than the minimum threshold. If the latter\n /// case is true, the `walletMainUtxo` components must point to the\n /// recent main UTXO of the given wallet, as currently known on the\n /// Ethereum chain. If the wallet has no main UTXO, this parameter\n /// can be empty as it is ignored since the wallet balance is\n /// assumed to be zero,\n /// - Wallet must be in Live state.\n function notifyWalletCloseable(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) external {\n self.notifyWalletCloseable(walletPubKeyHash, walletMainUtxo);\n }\n\n /// @notice Notifies about the end of the closing period for the given wallet.\n /// Closes the wallet ultimately and notifies the ECDSA registry\n /// about this fact.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The wallet must be in the Closing state,\n /// - The wallet closing period must have elapsed.\n function notifyWalletClosingPeriodElapsed(bytes20 walletPubKeyHash)\n external\n {\n self.notifyWalletClosingPeriodElapsed(walletPubKeyHash);\n }\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @param signature Bitcoin signature in the R/S/V format.\n /// @dev Requirements:\n /// - Wallet behind `walletPublicKey` must be in Live or MovingFunds\n /// or Closing state,\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit,\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// which was calculated from `preimageSha256`,\n /// - Wallet can be challenged for the given signature only once.\n function submitFraudChallenge(\n bytes calldata walletPublicKey,\n bytes memory preimageSha256,\n BitcoinTx.RSVSignature calldata signature\n ) external payable {\n self.submitFraudChallenge(walletPublicKey, preimageSha256, signature);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet if\n /// the transaction that spends the UTXO follows the protocol rules.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during input signing.\n /// The fraud challenge defeat attempt will only succeed if the\n /// inputs in the preimage are considered honestly spent by the\n /// wallet. Therefore the transaction spending the UTXO must be\n /// proven in the Bridge before a challenge defeat is called.\n /// If successfully defeated, the fraud challenge is marked as\n /// resolved and the amount of ether deposited by the challenger is\n /// sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference.\n /// @param witness Flag indicating whether the preimage was produced for a\n /// witness input. True for witness, false for non-witness input.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`\n /// must identify an open fraud challenge,\n /// - the preimage must be a valid preimage of a transaction generated\n /// according to the protocol rules and already proved in the Bridge,\n /// - before a defeat attempt is made the transaction that spends the\n /// given UTXO must be proven in the Bridge.\n function defeatFraudChallenge(\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n self.defeatFraudChallenge(walletPublicKey, preimage, witness);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet by\n /// proving the sighash and signature were produced for an off-chain\n /// wallet heartbeat message following a strict format.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during heartbeat message\n /// signing. The fraud challenge defeat attempt will only succeed if\n /// the signed message follows a strict format required for\n /// heartbeat messages. If successfully defeated, the fraud\n /// challenge is marked as resolved and the amount of ether\n /// deposited by the challenger is sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param heartbeatMessage Off-chain heartbeat message meeting the heartbeat\n /// message format requirements which produces sighash used to\n /// generate the ECDSA signature that is the subject of the fraud\n /// claim.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as\n /// `hash256(heartbeatMessage)` must identify an open fraud challenge,\n /// - `heartbeatMessage` must follow a strict format of heartbeat\n /// messages.\n function defeatFraudChallengeWithHeartbeat(\n bytes calldata walletPublicKey,\n bytes calldata heartbeatMessage\n ) external {\n self.defeatFraudChallengeWithHeartbeat(\n walletPublicKey,\n heartbeatMessage\n );\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after\n /// a fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state,\n /// - The `walletPublicKey` and `sighash` calculated from\n /// `preimageSha256` must identify an open fraud challenge,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported.\n function notifyFraudChallengeDefeatTimeout(\n bytes calldata walletPublicKey,\n uint32[] calldata walletMembersIDs,\n bytes memory preimageSha256\n ) external {\n self.notifyFraudChallengeDefeatTimeout(\n walletPublicKey,\n walletMembersIDs,\n preimageSha256\n );\n }\n\n /// @notice Allows the Governance to mark the given vault address as trusted\n /// or no longer trusted. Vaults are not trusted by default.\n /// Trusted vault must meet the following criteria:\n /// - `IVault.receiveBalanceIncrease` must have a known, low gas\n /// cost,\n /// - `IVault.receiveBalanceIncrease` must never revert.\n /// @dev Without restricting reveal only to trusted vaults, malicious\n /// vaults not meeting the criteria would be able to nuke sweep proof\n /// transactions executed by ECDSA wallet with deposits routed to\n /// them.\n /// @param vault The address of the vault.\n /// @param isTrusted flag indicating whether the vault is trusted or not.\n /// @dev Can only be called by the Governance.\n function setVaultStatus(address vault, bool isTrusted)\n external\n onlyGovernance\n {\n self.isVaultTrusted[vault] = isTrusted;\n emit VaultStatusUpdated(vault, isTrusted);\n }\n\n /// @notice Allows the Governance to mark the given address as trusted\n /// or no longer trusted SPV maintainer. Addresses are not trusted\n /// as SPV maintainers by default.\n /// @dev The SPV proof does not check whether the transaction is a part of\n /// the Bitcoin mainnet, it only checks whether the transaction has been\n /// mined performing the required amount of work as on Bitcoin mainnet.\n /// The possibility of submitting SPV proofs is limited to trusted SPV\n /// maintainers. The system expects transaction confirmations with the\n /// required work accumulated, so trusted SPV maintainers can not prove\n /// the transaction without providing the required Bitcoin proof of work.\n /// Trusted maintainers address the issue of an economic game between\n /// tBTC and Bitcoin mainnet where large Bitcoin mining pools can decide\n /// to use their hash power to mine fake Bitcoin blocks to prove them in\n /// tBTC instead of receiving Bitcoin miner rewards.\n /// @param spvMaintainer The address of the SPV maintainer.\n /// @param isTrusted flag indicating whether the address is trusted or not.\n /// @dev Can only be called by the Governance.\n function setSpvMaintainerStatus(address spvMaintainer, bool isTrusted)\n external\n onlyGovernance\n {\n self.isSpvMaintainer[spvMaintainer] = isTrusted;\n emit SpvMaintainerStatusUpdated(spvMaintainer, isTrusted);\n }\n\n /// @notice Updates parameters of deposits.\n /// @param depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor.\n /// @param depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @param depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @param depositRevealAheadPeriod New value of the deposit reveal ahead\n /// period parameter in seconds. It defines the length of the period\n /// that must be preserved between the deposit reveal time and the\n /// deposit refund locktime.\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero,\n /// - Deposit dust threshold must be greater than deposit TX max fee,\n /// - Deposit transaction max fee must be greater than zero.\n function updateDepositParameters(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n ) external onlyGovernance {\n self.updateDepositParameters(\n depositDustThreshold,\n depositTreasuryFeeDivisor,\n depositTxMaxFee,\n depositRevealAheadPeriod\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param redemptionTxMaxTotalFee New value of the redemption transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single redemption\n /// transaction. This is a _total_ max fee for the entire redemption\n /// transaction.\n /// @param redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked balance is returned to the\n /// redeemer in full amount.\n /// @param redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\n /// - Redemption dust threshold must be greater than the redemption TX\n /// max fee,\n /// - Redemption transaction max fee must be greater than zero,\n /// - Redemption transaction max total fee must be greater than or\n /// equal to the redemption transaction per-request max fee,\n /// - Redemption timeout must be greater than zero,\n /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTxMaxTotalFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param movingFundsDustThreshold New value of the moving funds dust\n /// threshold. It is the minimal satoshi amount that makes sense to\n /// be transferred during the moving funds process. Moving funds\n /// wallets having their BTC balance below that value can begin\n /// closing immediately as transferring such a low value may not be\n /// possible due to BTC network fees.\n /// @param movingFundsTimeoutResetDelay New value of the moving funds\n /// timeout reset delay in seconds. It is the time after which the\n /// moving funds timeout can be reset in case the target wallet\n /// commitment cannot be submitted due to a lack of live wallets\n /// in the system. It is counted from the moment when the wallet\n /// was requested to move their funds and switched to the MovingFunds\n /// state or from the moment the timeout was reset the last time.\n /// @param movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @param movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param movingFundsCommitmentGasOffset New value of the gas offset for\n /// moving funds target wallet commitment transaction gas costs\n /// reimbursement.\n /// @param movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout reset delay must be greater than zero,\n /// - Moving funds timeout must be greater than the moving funds\n /// timeout reset delay,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested.\n /// @param walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\n /// @param walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @param walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n // to a single target wallet during the moving funds process.\n /// @param walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges.\n /// @dev Requirements:\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance,\n /// - Wallet maximum BTC transfer must be greater than zero,\n /// - Wallet closing period must be greater than zero.\n function updateWalletParameters(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) external onlyGovernance {\n self.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit.\n /// @param fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero.\n /// @param fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud.\n /// @param fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n uint96 fraudChallengeDepositAmount,\n uint32 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint32 fraudNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateFraudParameters(\n fraudChallengeDepositAmount,\n fraudChallengeDefeatTimeout,\n fraudSlashingAmount,\n fraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates treasury address. The treasury receives the system fees.\n /// @param treasury New value of the treasury address.\n /// @dev The treasury address must not be 0x0.\n // slither-disable-next-line shadowing-local\n function updateTreasury(address treasury) external onlyGovernance {\n self.updateTreasury(treasury);\n }\n\n /// @notice Collection of all revealed deposits indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex).\n /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)\n /// and fundingOutputIndex an uint32. This mapping may contain valid\n /// and invalid deposits and the wallet is responsible for\n /// validating them before attempting to execute a sweep.\n function deposits(uint256 depositKey)\n external\n view\n returns (Deposit.DepositRequest memory)\n {\n return self.deposits[depositKey];\n }\n\n /// @notice Collection of all pending redemption requests indexed by\n /// redemption key built as\n /// `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.\n /// The walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and `redeemerOutputScript` is a Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC as requested by the redeemer. Requests are added\n /// to this mapping by the `requestRedemption` method (duplicates\n /// not allowed) and are removed by one of the following methods:\n /// - `submitRedemptionProof` in case the request was handled\n /// successfully,\n /// - `notifyRedemptionTimeout` in case the request was reported\n /// to be timed out.\n function pendingRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.pendingRedemptions[redemptionKey];\n }\n\n /// @notice Collection of all timed out redemptions requests indexed by\n /// redemption key built as\n /// `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.\n /// The walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and `redeemerOutputScript` is the Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n /// out request.\n /// Only one method can add to this mapping:\n /// - `notifyRedemptionTimeout` which puts the redemption key\n /// to this mapping based on a timed out request stored\n /// previously in `pendingRedemptions` mapping.\n /// Only one method can remove entries from this mapping:\n /// - `submitRedemptionProof` in case the timed out redemption\n /// request was a part of the proven transaction.\n function timedOutRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.timedOutRedemptions[redemptionKey];\n }\n\n /// @notice Collection of main UTXOs that are honestly spent indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash\n /// is bytes32 (ordered as in Bitcoin internally) and\n /// fundingOutputIndex an uint32. A main UTXO is considered honestly\n /// spent if it was used as an input of a transaction that have been\n /// proven in the Bridge.\n function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {\n return self.spentMainUTXOs[utxoKey];\n }\n\n /// @notice Gets details about a registered wallet.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key).\n /// @return Wallet details.\n function wallets(bytes20 walletPubKeyHash)\n external\n view\n returns (Wallets.Wallet memory)\n {\n return self.registeredWallets[walletPubKeyHash];\n }\n\n /// @notice Gets the public key hash of the active wallet.\n /// @return The 20-byte public key hash (computed using Bitcoin HASH160\n /// over the compressed ECDSA public key) of the active wallet.\n /// Returns bytes20(0) if there is no active wallet at the moment.\n function activeWalletPubKeyHash() external view returns (bytes20) {\n return self.activeWalletPubKeyHash;\n }\n\n /// @notice Gets the live wallets count.\n /// @return The current count of wallets being in the Live state.\n function liveWalletsCount() external view returns (uint32) {\n return self.liveWalletsCount;\n }\n\n /// @notice Returns the fraud challenge identified by the given key built\n /// as keccak256(walletPublicKey|sighash).\n function fraudChallenges(uint256 challengeKey)\n external\n view\n returns (Fraud.FraudChallenge memory)\n {\n return self.fraudChallenges[challengeKey];\n }\n\n /// @notice Collection of all moved funds sweep requests indexed by\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n /// internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n /// is actually an UTXO representing the moved funds and is supposed\n /// to be swept with the current main UTXO of the recipient wallet.\n /// @param requestKey Request key built as\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// @return Details of the moved funds sweep request.\n function movedFundsSweepRequests(uint256 requestKey)\n external\n view\n returns (MovingFunds.MovedFundsSweepRequest memory)\n {\n return self.movedFundsSweepRequests[requestKey];\n }\n\n /// @notice Indicates if the vault with the given address is trusted or not.\n /// Depositors can route their revealed deposits only to trusted\n /// vaults and have trusted vaults notified about new deposits as\n /// soon as these deposits get swept. Vaults not trusted by the\n /// Bridge can still be used by Bank balance owners on their own\n /// responsibility - anyone can approve their Bank balance to any\n /// address.\n function isVaultTrusted(address vault) external view returns (bool) {\n return self.isVaultTrusted[vault];\n }\n\n /// @notice Returns the current values of Bridge deposit parameters.\n /// @return depositDustThreshold The minimal amount that can be requested\n /// to deposit. Value of this parameter must take into account the\n /// value of `depositTreasuryFeeDivisor` and `depositTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the depositor.\n /// @return depositTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each deposit and transferred to the treasury upon\n /// sweep proof submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @return depositTxMaxFee Maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @return depositRevealAheadPeriod Defines the length of the period that\n /// must be preserved between the deposit reveal time and the\n /// deposit refund locktime. For example, if the deposit become\n /// refundable on August 1st, and the ahead period is 7 days, the\n /// latest moment for deposit reveal is July 25th. Value in seconds.\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n )\n {\n depositDustThreshold = self.depositDustThreshold;\n depositTreasuryFeeDivisor = self.depositTreasuryFeeDivisor;\n depositTxMaxFee = self.depositTxMaxFee;\n depositRevealAheadPeriod = self.depositRevealAheadPeriod;\n }\n\n /// @notice Returns the current values of Bridge redemption parameters.\n /// @return redemptionDustThreshold The minimal amount that can be requested\n /// for redemption. Value of this parameter must take into account\n /// the value of `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the redeemer.\n /// @return redemptionTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each redemption request and transferred to the\n /// treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @return redemptionTxMaxFee Maximum amount of BTC transaction fee that\n /// can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction\n /// fee is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @return redemptionTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single redemption\n /// transaction. This is a _total_ max fee for the entire redemption\n /// transaction.\n /// @return redemptionTimeout Time after which the redemption request can be\n /// reported as timed out. It is counted from the moment when the\n /// redemption request was created via `requestRedemption` call.\n /// Reported timed out requests are cancelled and locked balance is\n /// returned to the redeemer in full amount.\n /// @return redemptionTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a redemption timeout.\n /// @return redemptionTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// redemption timeout receives. The value is in the range [0, 100].\n function redemptionParameters()\n external\n view\n returns (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n )\n {\n redemptionDustThreshold = self.redemptionDustThreshold;\n redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;\n redemptionTxMaxFee = self.redemptionTxMaxFee;\n redemptionTxMaxTotalFee = self.redemptionTxMaxTotalFee;\n redemptionTimeout = self.redemptionTimeout;\n redemptionTimeoutSlashingAmount = self.redemptionTimeoutSlashingAmount;\n redemptionTimeoutNotifierRewardMultiplier = self\n .redemptionTimeoutNotifierRewardMultiplier;\n }\n\n /// @notice Returns the current values of Bridge moving funds between\n /// wallets parameters.\n /// @return movingFundsTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @return movingFundsDustThreshold The minimal satoshi amount that makes\n /// sense to be transferred during the moving funds process. Moving\n /// funds wallets having their BTC balance below that value can\n /// begin closing immediately as transferring such a low value may\n /// not be possible due to BTC network fees.\n /// @return movingFundsTimeoutResetDelay Time after which the moving funds\n /// timeout can be reset in case the target wallet commitment\n /// cannot be submitted due to a lack of live wallets in the system.\n /// It is counted from the moment when the wallet was requested to\n /// move their funds and switched to the MovingFunds state or from\n /// the moment the timeout was reset the last time. Value in seconds\n /// This value should be lower than the value of the\n /// `movingFundsTimeout`.\n /// @return movingFundsTimeout Time after which the moving funds process\n /// can be reported as timed out. It is counted from the moment\n /// when the wallet was requested to move their funds and switched\n /// to the MovingFunds state. Value in seconds.\n /// @return movingFundsTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moving funds timeout.\n /// @return movingFundsTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// moving funds timeout receives. The value is in the range [0, 100].\n /// @return movingFundsCommitmentGasOffset The gas offset used for the\n /// moving funds target wallet commitment transaction cost\n /// reimbursement.\n /// @return movedFundsSweepTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moved funds\n /// sweep transaction. This is a _total_ max fee for the entire\n /// moved funds sweep transaction.\n /// @return movedFundsSweepTimeout Time after which the moved funds sweep\n /// process can be reported as timed out. It is counted from the\n /// moment when the wallet was requested to sweep the received funds.\n /// Value in seconds.\n /// @return movedFundsSweepTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moved funds sweep timeout.\n /// @return movedFundsSweepTimeoutNotifierRewardMultiplier The percentage\n /// of the notifier reward from the staking contract the notifier\n /// of a moved funds sweep timeout receives. The value is in the\n /// range [0, 100].\n function movingFundsParameters()\n external\n view\n returns (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n )\n {\n movingFundsTxMaxTotalFee = self.movingFundsTxMaxTotalFee;\n movingFundsDustThreshold = self.movingFundsDustThreshold;\n movingFundsTimeoutResetDelay = self.movingFundsTimeoutResetDelay;\n movingFundsTimeout = self.movingFundsTimeout;\n movingFundsTimeoutSlashingAmount = self\n .movingFundsTimeoutSlashingAmount;\n movingFundsTimeoutNotifierRewardMultiplier = self\n .movingFundsTimeoutNotifierRewardMultiplier;\n movingFundsCommitmentGasOffset = self.movingFundsCommitmentGasOffset;\n movedFundsSweepTxMaxTotalFee = self.movedFundsSweepTxMaxTotalFee;\n movedFundsSweepTimeout = self.movedFundsSweepTimeout;\n movedFundsSweepTimeoutSlashingAmount = self\n .movedFundsSweepTimeoutSlashingAmount;\n movedFundsSweepTimeoutNotifierRewardMultiplier = self\n .movedFundsSweepTimeoutNotifierRewardMultiplier;\n }\n\n /// @return walletCreationPeriod Determines how frequently a new wallet\n /// creation can be requested. Value in seconds.\n /// @return walletCreationMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletCreationMaxBtcBalance The maximum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletClosureMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet closure.\n /// @return walletMaxAge The maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @return walletMaxBtcTransfer The maximum BTC amount in satoshi than\n /// can be transferred to a single target wallet during the moving\n /// funds process.\n /// @return walletClosingPeriod Determines the length of the wallet closing\n /// period, i.e. the period when the wallet remains in the Closing\n /// state and can be subject of deposit fraud challenges. Value\n /// in seconds.\n function walletParameters()\n external\n view\n returns (\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n )\n {\n walletCreationPeriod = self.walletCreationPeriod;\n walletCreationMinBtcBalance = self.walletCreationMinBtcBalance;\n walletCreationMaxBtcBalance = self.walletCreationMaxBtcBalance;\n walletClosureMinBtcBalance = self.walletClosureMinBtcBalance;\n walletMaxAge = self.walletMaxAge;\n walletMaxBtcTransfer = self.walletMaxBtcTransfer;\n walletClosingPeriod = self.walletClosingPeriod;\n }\n\n /// @notice Returns the current values of Bridge fraud parameters.\n /// @return fraudChallengeDepositAmount The amount of ETH in wei the party\n /// challenging the wallet for fraud needs to deposit.\n /// @return fraudChallengeDefeatTimeout The amount of time the wallet has to\n /// defeat a fraud challenge.\n /// @return fraudSlashingAmount The amount slashed from each wallet member\n /// for committing a fraud.\n /// @return fraudNotifierRewardMultiplier The percentage of the notifier\n /// reward from the staking contract the notifier of a fraud\n /// receives. The value is in the range [0, 100].\n function fraudParameters()\n external\n view\n returns (\n uint96 fraudChallengeDepositAmount,\n uint32 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint32 fraudNotifierRewardMultiplier\n )\n {\n fraudChallengeDepositAmount = self.fraudChallengeDepositAmount;\n fraudChallengeDefeatTimeout = self.fraudChallengeDefeatTimeout;\n fraudSlashingAmount = self.fraudSlashingAmount;\n fraudNotifierRewardMultiplier = self.fraudNotifierRewardMultiplier;\n }\n\n /// @notice Returns the addresses of contracts Bridge is interacting with.\n /// @return bank Address of the Bank the Bridge belongs to.\n /// @return relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @return ecdsaWalletRegistry Address of the ECDSA Wallet Registry.\n /// @return reimbursementPool Address of the Reimbursement Pool.\n function contractReferences()\n external\n view\n returns (\n Bank bank,\n IRelay relay,\n EcdsaWalletRegistry ecdsaWalletRegistry,\n ReimbursementPool reimbursementPool\n )\n {\n bank = self.bank;\n relay = self.relay;\n ecdsaWalletRegistry = self.ecdsaWalletRegistry;\n reimbursementPool = self.reimbursementPool;\n }\n\n /// @notice Address where the deposit treasury fees will be sent to.\n /// Treasury takes part in the operators rewarding process.\n function treasury() external view returns (address) {\n return self.treasury;\n }\n\n /// @notice The number of confirmations on the Bitcoin chain required to\n /// successfully evaluate an SPV proof.\n function txProofDifficultyFactor() external view returns (uint256) {\n return self.txProofDifficultyFactor;\n }\n}\n"
|
|
125
|
+
"content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity 0.8.17;\n\nimport \"@keep-network/random-beacon/contracts/Governable.sol\";\nimport \"@keep-network/random-beacon/contracts/ReimbursementPool.sol\";\nimport {IWalletOwner as EcdsaWalletOwner} from \"@keep-network/ecdsa/contracts/api/IWalletOwner.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Deposit.sol\";\nimport \"./DepositSweep.sol\";\nimport \"./Redemption.sol\";\nimport \"./BitcoinTx.sol\";\nimport \"./EcdsaLib.sol\";\nimport \"./Wallets.sol\";\nimport \"./Fraud.sol\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/IReceiveBalanceApproval.sol\";\nimport \"../bank/Bank.sol\";\n\n/// @title Bitcoin Bridge\n/// @notice Bridge manages BTC deposit and redemption flow and is increasing and\n/// decreasing balances in the Bank as a result of BTC deposit and\n/// redemption operations performed by depositors and redeemers.\n///\n/// Depositors send BTC funds to the most recently created off-chain\n/// ECDSA wallet of the bridge using pay-to-script-hash (P2SH) or\n/// pay-to-witness-script-hash (P2WSH) containing hashed information\n/// about the depositor’s Ethereum address. Then, the depositor reveals\n/// their Ethereum address along with their deposit blinding factor,\n/// refund public key hash and refund locktime to the Bridge on Ethereum\n/// chain. The off-chain ECDSA wallet listens for these sorts of\n/// messages and when it gets one, it checks the Bitcoin network to make\n/// sure the deposit lines up. If it does, the off-chain ECDSA wallet\n/// may decide to pick the deposit transaction for sweeping, and when\n/// the sweep operation is confirmed on the Bitcoin network, the ECDSA\n/// wallet informs the Bridge about the sweep increasing appropriate\n/// balances in the Bank.\n/// @dev Bridge is an upgradeable component of the Bank. The order of\n/// functionalities in this contract is: deposit, sweep, redemption,\n/// moving funds, wallet lifecycle, frauds, parameters.\ncontract Bridge is\n Governable,\n EcdsaWalletOwner,\n Initializable,\n IReceiveBalanceApproval\n{\n using BridgeState for BridgeState.Storage;\n using Deposit for BridgeState.Storage;\n using DepositSweep for BridgeState.Storage;\n using Redemption for BridgeState.Storage;\n using MovingFunds for BridgeState.Storage;\n using Wallets for BridgeState.Storage;\n using Fraud for BridgeState.Storage;\n\n BridgeState.Storage internal self;\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address indexed depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 indexed walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n event DepositsSwept(bytes20 walletPubKeyHash, bytes32 sweepTxHash);\n\n event RedemptionRequested(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript,\n address indexed redeemer,\n uint64 requestedAmount,\n uint64 treasuryFee,\n uint64 txMaxFee\n );\n\n event RedemptionsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 redemptionTxHash\n );\n\n event RedemptionTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes redeemerOutputScript\n );\n\n event WalletMovingFunds(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event MovingFundsCommitmentSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes20[] targetWallets,\n address submitter\n );\n\n event MovingFundsTimeoutReset(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsCompleted(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash\n );\n\n event MovingFundsTimedOut(bytes20 indexed walletPubKeyHash);\n\n event MovingFundsBelowDustReported(bytes20 indexed walletPubKeyHash);\n\n event MovedFundsSwept(\n bytes20 indexed walletPubKeyHash,\n bytes32 sweepTxHash\n );\n\n event MovedFundsSweepTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex\n );\n\n event NewWalletRequested();\n\n event NewWalletRegistered(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosing(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletClosed(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event WalletTerminated(\n bytes32 indexed ecdsaWalletID,\n bytes20 indexed walletPubKeyHash\n );\n\n event FraudChallengeSubmitted(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash,\n uint8 v,\n bytes32 r,\n bytes32 s\n );\n\n event FraudChallengeDefeated(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event FraudChallengeDefeatTimedOut(\n bytes20 indexed walletPubKeyHash,\n bytes32 sighash\n );\n\n event VaultStatusUpdated(address indexed vault, bool isTrusted);\n\n event SpvMaintainerStatusUpdated(\n address indexed spvMaintainer,\n bool isTrusted\n );\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint96 fraudChallengeDepositAmount,\n uint32 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint32 fraudNotifierRewardMultiplier\n );\n\n event TreasuryUpdated(address treasury);\n\n modifier onlySpvMaintainer() {\n require(\n self.isSpvMaintainer[msg.sender],\n \"Caller is not SPV maintainer\"\n );\n _;\n }\n\n /// @custom:oz-upgrades-unsafe-allow constructor\n constructor() {\n _disableInitializers();\n }\n\n /// @dev Initializes upgradable contract on deployment.\n /// @param _bank Address of the Bank the Bridge belongs to.\n /// @param _relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @param _treasury Address where the deposit and redemption treasury fees\n /// will be sent to.\n /// @param _ecdsaWalletRegistry Address of the ECDSA Wallet Registry contract.\n /// @param _reimbursementPool Address of the Reimbursement Pool contract.\n /// @param _txProofDifficultyFactor The number of confirmations on the Bitcoin\n /// chain required to successfully evaluate an SPV proof.\n function initialize(\n address _bank,\n address _relay,\n address _treasury,\n address _ecdsaWalletRegistry,\n address payable _reimbursementPool,\n uint96 _txProofDifficultyFactor\n ) external initializer {\n require(_bank != address(0), \"Bank address cannot be zero\");\n self.bank = Bank(_bank);\n\n require(_relay != address(0), \"Relay address cannot be zero\");\n self.relay = IRelay(_relay);\n\n require(\n _ecdsaWalletRegistry != address(0),\n \"ECDSA Wallet Registry address cannot be zero\"\n );\n self.ecdsaWalletRegistry = EcdsaWalletRegistry(_ecdsaWalletRegistry);\n\n require(\n _reimbursementPool != address(0),\n \"Reimbursement Pool address cannot be zero\"\n );\n self.reimbursementPool = ReimbursementPool(_reimbursementPool);\n\n require(_treasury != address(0), \"Treasury address cannot be zero\");\n self.treasury = _treasury;\n\n self.txProofDifficultyFactor = _txProofDifficultyFactor;\n\n //\n // All parameters set in the constructor are initial ones, used at the\n // moment contracts were deployed for the first time. Parameters are\n // governable and values assigned in the constructor do not need to\n // reflect the current ones. Keep in mind the initial parameters are\n // pretty forgiving and valid only for the early stage of the network.\n //\n\n self.depositDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.depositTxMaxFee = 100000; // 100000 satoshi = 0.001 BTC\n self.depositRevealAheadPeriod = 15 days;\n self.depositTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionDustThreshold = 1000000; // 1000000 satoshi = 0.01 BTC\n self.redemptionTreasuryFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005\n self.redemptionTxMaxFee = 100000; // 100000 satoshi = 0.001 BTC\n self.redemptionTxMaxTotalFee = 1000000; // 1000000 satoshi = 0.01 BTC\n self.redemptionTimeout = 5 days;\n self.redemptionTimeoutSlashingAmount = 100 * 1e18; // 100 T\n self.redemptionTimeoutNotifierRewardMultiplier = 100; // 100%\n self.movingFundsTxMaxTotalFee = 100000; // 100000 satoshi = 0.001 BTC\n self.movingFundsDustThreshold = 200000; // 200000 satoshi = 0.002 BTC\n self.movingFundsTimeoutResetDelay = 6 days;\n self.movingFundsTimeout = 7 days;\n self.movingFundsTimeoutSlashingAmount = 100 * 1e18; // 100 T\n self.movingFundsTimeoutNotifierRewardMultiplier = 100; //100%\n self.movingFundsCommitmentGasOffset = 15000;\n self.movedFundsSweepTxMaxTotalFee = 100000; // 100000 satoshi = 0.001 BTC\n self.movedFundsSweepTimeout = 7 days;\n self.movedFundsSweepTimeoutSlashingAmount = 100 * 1e18; // 100 T\n self.movedFundsSweepTimeoutNotifierRewardMultiplier = 100; //100%\n self.fraudChallengeDepositAmount = 5 ether;\n self.fraudChallengeDefeatTimeout = 7 days;\n self.fraudSlashingAmount = 100 * 1e18; // 100 T\n self.fraudNotifierRewardMultiplier = 100; // 100%\n self.walletCreationPeriod = 1 weeks;\n self.walletCreationMinBtcBalance = 1e8; // 1 BTC\n self.walletCreationMaxBtcBalance = 100e8; // 100 BTC\n self.walletClosureMinBtcBalance = 5 * 1e7; // 0.5 BTC\n self.walletMaxAge = 26 weeks; // ~6 months\n self.walletMaxBtcTransfer = 10e8; // 10 BTC\n self.walletClosingPeriod = 40 days;\n\n _transferGovernance(msg.sender);\n }\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`.\n /// @param reveal Deposit reveal data, see `RevealInfo struct.\n /// @dev Requirements:\n /// - This function must be called by the same Ethereum address as the\n /// one used in the P2(W)SH BTC deposit transaction as a depositor,\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet,\n /// - `reveal.vault` must be 0x0 or point to a trusted vault,\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BitcoinTx.Info calldata fundingTx,\n Deposit.DepositRevealInfo calldata reveal\n ) external {\n self.revealDeposit(fundingTx, reveal);\n }\n\n /// @notice Used by the wallet to prove the BTC deposit sweep transaction\n /// and to update Bank balances accordingly. Sweep is only accepted\n /// if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by first\n /// computing the Bitcoin fee for the sweep transaction. The fee is\n /// divided evenly between all swept deposits. Each depositor\n /// receives a balance in the bank equal to the amount inferred\n /// during the reveal transaction, minus their fee share.\n ///\n /// It is possible to prove the given sweep only one time.\n /// @param sweepTx Bitcoin sweep transaction data.\n /// @param sweepProof Bitcoin sweep proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain. If no main UTXO exists for the given wallet,\n /// this parameter is ignored.\n /// @param vault Optional address of the vault where all swept deposits\n /// should be routed to. All deposits swept as part of the transaction\n /// must have their `vault` parameters set to the same address.\n /// If this parameter is set to an address of a trusted vault, swept\n /// deposits are routed to that vault.\n /// If this parameter is set to the zero address or to an address\n /// of a non-trusted vault, swept deposits are not routed to a\n /// vault but depositors' balances are increased in the Bank\n /// individually.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with 1..n\n /// inputs. If the wallet has no main UTXO, all n inputs should\n /// correspond to P2(W)SH revealed deposits UTXOs. If the wallet has\n /// an existing main UTXO, one of the n inputs must point to that\n /// main UTXO and remaining n-1 inputs should correspond to P2(W)SH\n /// revealed deposits UTXOs. That transaction must have only\n /// one P2(W)PKH output locking funds on the 20-byte wallet public\n /// key hash,\n /// - All revealed deposits that are swept by `sweepTx` must have\n /// their `vault` parameters set to the same address as the address\n /// passed in the `vault` function parameter,\n /// - `sweepProof` components must match the expected structure. See\n /// `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored.\n function submitDepositSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo,\n address vault\n ) external onlySpvMaintainer {\n self.submitDepositSweepProof(sweepTx, sweepProof, mainUtxo, vault);\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script. Handles the\n /// simplest case in which the redeemer's balance is decreased in\n /// the Bank.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key).\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC.\n /// @param amount Requested amount in satoshi. This is also the Bank balance\n /// that is taken from the `balanceOwner` upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @dev Requirements:\n /// - Wallet behind `walletPubKeyHash` must be live,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain,\n /// - `redeemerOutputScript` must be a proper Bitcoin script,\n /// - `redeemerOutputScript` cannot have wallet PKH as payload,\n /// - `amount` must be above or equal the `redemptionDustThreshold`,\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time,\n /// - Wallet must have enough Bitcoin balance to process the request,\n /// - Redeemer must make an allowance in the Bank that the Bridge\n /// contract can spend the given `amount`.\n function requestRedemption(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes calldata redeemerOutputScript,\n uint64 amount\n ) external {\n self.requestRedemption(\n walletPubKeyHash,\n mainUtxo,\n msg.sender,\n redeemerOutputScript,\n amount\n );\n }\n\n /// @notice Requests redemption of the given amount from the specified\n /// wallet to the redeemer Bitcoin output script. Used by\n /// `Bank.approveBalanceAndCall`. Can handle more complex cases\n /// where balance owner may be someone else than the redeemer.\n /// For example, vault redeeming its balance for some depositor.\n /// @param balanceOwner The address of the Bank balance owner whose balance\n /// is getting redeemed.\n /// @param amount Requested amount in satoshi. This is also the Bank balance\n /// that is taken from the `balanceOwner` upon request.\n /// Once the request is handled, the actual amount of BTC locked\n /// on the redeemer output script will be always lower than this value\n /// since the treasury and Bitcoin transaction fees must be incurred.\n /// The minimal amount satisfying the request can be computed as:\n /// `amount - (amount / redemptionTreasuryFeeDivisor) - redemptionTxMaxFee`.\n /// Fees values are taken at the moment of request creation.\n /// @param redemptionData ABI-encoded redemption data:\n /// [\n /// address redeemer,\n /// bytes20 walletPubKeyHash,\n /// bytes32 mainUtxoTxHash,\n /// uint32 mainUtxoTxOutputIndex,\n /// uint64 mainUtxoTxOutputValue,\n /// bytes redeemerOutputScript\n /// ]\n ///\n /// - redeemer: The Ethereum address of the redeemer who will be able\n /// to claim Bank balance if anything goes wrong during the redemption.\n /// In the most basic case, when someone redeems their balance\n /// from the Bank, `balanceOwner` is the same as `redeemer`.\n /// However, when a Vault is redeeming part of its balance for some\n /// redeemer address (for example, someone who has earlier deposited\n /// into that Vault), `balanceOwner` is the Vault, and `redeemer` is\n /// the address for which the vault is redeeming its balance to,\n /// - walletPubKeyHash: The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key),\n /// - mainUtxoTxHash: Data of the wallet's main UTXO TX hash, as\n /// currently known on the Ethereum chain,\n /// - mainUtxoTxOutputIndex: Data of the wallet's main UTXO output\n /// index, as currently known on Ethereum chain,\n /// - mainUtxoTxOutputValue: Data of the wallet's main UTXO output\n /// value, as currently known on Ethereum chain,\n /// - redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC.\n /// @dev Requirements:\n /// - The caller must be the Bank,\n /// - Wallet behind `walletPubKeyHash` must be live,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain,\n /// - `redeemerOutputScript` must be a proper Bitcoin script,\n /// - `redeemerOutputScript` cannot have wallet PKH as payload,\n /// - `amount` must be above or equal the `redemptionDustThreshold`,\n /// - Given `walletPubKeyHash` and `redeemerOutputScript` pair can be\n /// used for only one pending request at the same time,\n /// - Wallet must have enough Bitcoin balance to process the request.\n ///\n /// Note on upgradeability:\n /// Bridge is an upgradeable contract deployed behind\n /// a TransparentUpgradeableProxy. Accepting redemption data as bytes\n /// provides great flexibility. The Bridge is just like any other\n /// contract with a balance approved in the Bank and can be upgraded\n /// to another version without being bound to a particular interface\n /// forever. This flexibility comes with the cost - developers\n /// integrating their vaults and dApps with `Bridge` using\n /// `approveBalanceAndCall` need to pay extra attention to\n /// `redemptionData` and adjust the code in case the expected structure\n /// of `redemptionData` changes.\n function receiveBalanceApproval(\n address balanceOwner,\n uint256 amount,\n bytes calldata redemptionData\n ) external override {\n require(msg.sender == address(self.bank), \"Caller is not the bank\");\n\n self.requestRedemption(\n balanceOwner,\n SafeCastUpgradeable.toUint64(amount),\n redemptionData\n );\n }\n\n /// @notice Used by the wallet to prove the BTC redemption transaction\n /// and to make the necessary bookkeeping. Redemption is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function is performing Bank balance updates by burning\n /// the total redeemed Bitcoin amount from Bridge balance and\n /// transferring the treasury fee sum to the treasury address.\n ///\n /// It is possible to prove the given redemption only one time.\n /// @param redemptionTx Bitcoin redemption transaction data.\n /// @param redemptionProof Bitcoin redemption proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet which\n /// performed the redemption transaction.\n /// @dev Requirements:\n /// - `redemptionTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `redemptionTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs handling existing pending\n /// redemption requests or pointing to reported timed out requests.\n /// There can be also 1 optional output representing the\n /// change and pointing back to the 20-byte wallet public key hash.\n /// The change should be always present if the redeemed value sum\n /// is lower than the total wallet's BTC balance,\n /// - `redemptionProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input.\n /// Other remarks:\n /// - Putting the change output as the first transaction output can\n /// save some gas because the output processing loop begins each\n /// iteration by checking whether the given output is the change\n /// thus uses some gas for making the comparison. Once the change\n /// is identified, that check is omitted in further iterations.\n function submitRedemptionProof(\n BitcoinTx.Info calldata redemptionTx,\n BitcoinTx.Proof calldata redemptionProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external onlySpvMaintainer {\n self.submitRedemptionProof(\n redemptionTx,\n redemptionProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies that there is a pending redemption request associated\n /// with the given wallet, that has timed out. The redemption\n /// request is identified by the key built as\n /// `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.\n /// The results of calling this function:\n /// - The pending redemptions value for the wallet will be decreased\n /// by the requested amount (minus treasury fee),\n /// - The tokens taken from the redeemer on redemption request will\n /// be returned to the redeemer,\n /// - The request will be moved from pending redemptions to\n /// timed-out redemptions,\n /// - If the state of the wallet is `Live` or `MovingFunds`, the\n /// wallet operators will be slashed and the notifier will be\n /// rewarded,\n /// - If the state of wallet is `Live`, the wallet will be closed or\n /// marked as `MovingFunds` (depending on the presence or absence\n /// of the wallet's main UTXO) and the wallet will no longer be\n /// marked as the active wallet (if it was marked as such).\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param redeemerOutputScript The redeemer's length-prefixed output\n /// script (P2PKH, P2WPKH, P2SH or P2WSH).\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Terminated state,\n /// - The redemption request identified by `walletPubKeyHash` and\n /// `redeemerOutputScript` must exist,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time defined by `redemptionTimeout` must have\n /// passed since the redemption was requested (the request must be\n /// timed-out).\n function notifyRedemptionTimeout(\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs,\n bytes calldata redeemerOutputScript\n ) external {\n self.notifyRedemptionTimeout(\n walletPubKeyHash,\n walletMembersIDs,\n redeemerOutputScript\n );\n }\n\n /// @notice Submits the moving funds target wallets commitment.\n /// Once all requirements are met, that function registers the\n /// target wallets commitment and opens the way for moving funds\n /// proof submission.\n /// The caller is reimbursed for the transaction costs.\n /// @param walletPubKeyHash 20-byte public key hash of the source wallet.\n /// @param walletMainUtxo Data of the source wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @param walletMembersIDs Identifiers of the source wallet signing group\n /// members.\n /// @param walletMemberIndex Position of the caller in the source wallet\n /// signing group members list.\n /// @param targetWallets List of 20-byte public key hashes of the target\n /// wallets that the source wallet commits to move the funds to.\n /// @dev Requirements:\n /// - The source wallet must be in the MovingFunds state,\n /// - The source wallet must not have pending redemption requests,\n /// - The source wallet must not have pending moved funds sweep requests,\n /// - The source wallet must not have submitted its commitment already,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given source wallet in the ECDSA registry. Those IDs are\n /// not directly stored in the contract for gas efficiency purposes\n /// but they can be read from appropriate `DkgResultSubmitted`\n /// and `DkgResultApproved` events,\n /// - The `walletMemberIndex` must be in range [1, walletMembersIDs.length],\n /// - The caller must be the member of the source wallet signing group\n /// at the position indicated by `walletMemberIndex` parameter,\n /// - The `walletMainUtxo` components must point to the recent main\n /// UTXO of the source wallet, as currently known on the Ethereum\n /// chain,\n /// - Source wallet BTC balance must be greater than zero,\n /// - At least one Live wallet must exist in the system,\n /// - Submitted target wallets count must match the expected count\n /// `N = min(liveWalletsCount, ceil(walletBtcBalance / walletMaxBtcTransfer))`\n /// where `N > 0`,\n /// - Each target wallet must be not equal to the source wallet,\n /// - Each target wallet must follow the expected order i.e. all\n /// target wallets 20-byte public key hashes represented as numbers\n /// must form a strictly increasing sequence without duplicates,\n /// - Each target wallet must be in Live state.\n function submitMovingFundsCommitment(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo,\n uint32[] calldata walletMembersIDs,\n uint256 walletMemberIndex,\n bytes20[] calldata targetWallets\n ) external {\n uint256 gasStart = gasleft();\n\n self.submitMovingFundsCommitment(\n walletPubKeyHash,\n walletMainUtxo,\n walletMembersIDs,\n walletMemberIndex,\n targetWallets\n );\n\n self.reimbursementPool.refund(\n (gasStart - gasleft()) + self.movingFundsCommitmentGasOffset,\n msg.sender\n );\n }\n\n /// @notice Resets the moving funds timeout for the given wallet if the\n /// target wallet commitment cannot be submitted due to a lack\n /// of live wallets in the system.\n /// @param walletPubKeyHash 20-byte public key hash of the moving funds wallet.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The target wallets commitment must not be already submitted for\n /// the given moving funds wallet,\n /// - Live wallets count must be zero,\n /// - The moving funds timeout reset delay must be elapsed.\n function resetMovingFundsTimeout(bytes20 walletPubKeyHash) external {\n self.resetMovingFundsTimeout(walletPubKeyHash);\n }\n\n /// @notice Used by the wallet to prove the BTC moving funds transaction\n /// and to make the necessary state changes. Moving funds is only\n /// accepted if it satisfies SPV proof.\n ///\n /// The function validates the moving funds transaction structure\n /// by checking if it actually spends the main UTXO of the declared\n /// wallet and locks the value on the pre-committed target wallets\n /// using a reasonable transaction fee. If all preconditions are\n /// met, this functions closes the source wallet.\n ///\n /// It is possible to prove the given moving funds transaction only\n /// one time.\n /// @param movingFundsTx Bitcoin moving funds transaction data.\n /// @param movingFundsProof Bitcoin moving funds proof data.\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known on\n /// the Ethereum chain.\n /// @param walletPubKeyHash 20-byte public key hash (computed using Bitcoin\n /// HASH160 over the compressed ECDSA public key) of the wallet\n /// which performed the moving funds transaction.\n /// @dev Requirements:\n /// - `movingFundsTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `movingFundsTx` should represent a Bitcoin transaction with\n /// exactly 1 input that refers to the wallet's main UTXO. That\n /// transaction should have 1..n outputs corresponding to the\n /// pre-committed target wallets. Outputs must be ordered in the\n /// same way as their corresponding target wallets are ordered\n /// within the target wallets commitment,\n /// - `movingFundsProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// Additionally, the recent main UTXO on Ethereum must be set,\n /// - `walletPubKeyHash` must be connected with the main UTXO used\n /// as transaction single input,\n /// - The wallet that `walletPubKeyHash` points to must be in the\n /// MovingFunds state,\n /// - The target wallets commitment must be submitted by the wallet\n /// that `walletPubKeyHash` points to,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movingFundsTxMaxTotalFee` governable parameter.\n function submitMovingFundsProof(\n BitcoinTx.Info calldata movingFundsTx,\n BitcoinTx.Proof calldata movingFundsProof,\n BitcoinTx.UTXO calldata mainUtxo,\n bytes20 walletPubKeyHash\n ) external onlySpvMaintainer {\n self.submitMovingFundsProof(\n movingFundsTx,\n movingFundsProof,\n mainUtxo,\n walletPubKeyHash\n );\n }\n\n /// @notice Notifies about a timed out moving funds process. Terminates\n /// the wallet and slashes signing group members as a result.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The moving funds timeout must be actually exceeded,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovingFundsTimeout(\n bytes20 walletPubKeyHash,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovingFundsTimeout(walletPubKeyHash, walletMembersIDs);\n }\n\n /// @notice Notifies about a moving funds wallet whose BTC balance is\n /// below the moving funds dust threshold. Ends the moving funds\n /// process and begins wallet closing immediately.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet\n /// @param mainUtxo Data of the wallet's main UTXO, as currently known\n /// on the Ethereum chain.\n /// @dev Requirements:\n /// - The wallet must be in the MovingFunds state,\n /// - The `mainUtxo` components must point to the recent main UTXO\n /// of the given wallet, as currently known on the Ethereum chain.\n /// If the wallet has no main UTXO, this parameter can be empty as it\n /// is ignored,\n /// - The wallet BTC balance must be below the moving funds threshold.\n function notifyMovingFundsBelowDust(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata mainUtxo\n ) external {\n self.notifyMovingFundsBelowDust(walletPubKeyHash, mainUtxo);\n }\n\n /// @notice Used by the wallet to prove the BTC moved funds sweep\n /// transaction and to make the necessary state changes. Moved\n /// funds sweep is only accepted if it satisfies SPV proof.\n ///\n /// The function validates the sweep transaction structure by\n /// checking if it actually spends the moved funds UTXO and the\n /// sweeping wallet's main UTXO (optionally), and if it locks the\n /// value on the sweeping wallet's 20-byte public key hash using a\n /// reasonable transaction fee. If all preconditions are\n /// met, this function updates the sweeping wallet main UTXO, thus\n /// their BTC balance.\n ///\n /// It is possible to prove the given sweep transaction only\n /// one time.\n /// @param sweepTx Bitcoin sweep funds transaction data.\n /// @param sweepProof Bitcoin sweep funds proof data.\n /// @param mainUtxo Data of the sweeping wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - `sweepTx` components must match the expected structure. See\n /// `BitcoinTx.Info` docs for reference. Their values must exactly\n /// correspond to appropriate Bitcoin transaction fields to produce\n /// a provable transaction hash,\n /// - The `sweepTx` should represent a Bitcoin transaction with\n /// the first input pointing to a moved funds sweep request targeted\n /// to the wallet, and optionally, the second input pointing to the\n /// wallet's main UTXO, if the sweeping wallet has a main UTXO set.\n /// There should be only one output locking funds on the sweeping\n /// wallet 20-byte public key hash,\n /// - `sweepProof` components must match the expected structure.\n /// See `BitcoinTx.Proof` docs for reference. The `bitcoinHeaders`\n /// field must contain a valid number of block headers, not less\n /// than the `txProofDifficultyFactor` contract constant,\n /// - `mainUtxo` components must point to the recent main UTXO\n /// of the sweeping wallet, as currently known on the Ethereum chain.\n /// If there is no main UTXO, this parameter is ignored,\n /// - The sweeping wallet must be in the Live or MovingFunds state,\n /// - The total Bitcoin transaction fee must be lesser or equal\n /// to `movedFundsSweepTxMaxTotalFee` governable parameter.\n function submitMovedFundsSweepProof(\n BitcoinTx.Info calldata sweepTx,\n BitcoinTx.Proof calldata sweepProof,\n BitcoinTx.UTXO calldata mainUtxo\n ) external onlySpvMaintainer {\n self.submitMovedFundsSweepProof(sweepTx, sweepProof, mainUtxo);\n }\n\n /// @notice Notifies about a timed out moved funds sweep process. If the\n /// wallet is not terminated yet, that function terminates\n /// the wallet and slashes signing group members as a result.\n /// Marks the given sweep request as TimedOut.\n /// @param movingFundsTxHash 32-byte hash of the moving funds transaction\n /// that caused the sweep request to be created.\n /// @param movingFundsTxOutputIndex Index of the moving funds transaction\n /// output that is subject of the sweep request.\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @dev Requirements:\n /// - The moved funds sweep request must be in the Pending state,\n /// - The moved funds sweep timeout must be actually exceeded,\n /// - The wallet must be either in the Live or MovingFunds or\n /// Terminated state,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract.\n function notifyMovedFundsSweepTimeout(\n bytes32 movingFundsTxHash,\n uint32 movingFundsTxOutputIndex,\n uint32[] calldata walletMembersIDs\n ) external {\n self.notifyMovedFundsSweepTimeout(\n movingFundsTxHash,\n movingFundsTxOutputIndex,\n walletMembersIDs\n );\n }\n\n /// @notice Requests creation of a new wallet. This function just\n /// forms a request and the creation process is performed\n /// asynchronously. Once a wallet is created, the ECDSA Wallet\n /// Registry will notify this contract by calling the\n /// `__ecdsaWalletCreatedCallback` function.\n /// @param activeWalletMainUtxo Data of the active wallet's main UTXO, as\n /// currently known on the Ethereum chain.\n /// @dev Requirements:\n /// - `activeWalletMainUtxo` components must point to the recent main\n /// UTXO of the given active wallet, as currently known on the\n /// Ethereum chain. If there is no active wallet at the moment, or\n /// the active wallet has no main UTXO, this parameter can be\n /// empty as it is ignored,\n /// - Wallet creation must not be in progress,\n /// - If the active wallet is set, one of the following\n /// conditions must be true:\n /// - The active wallet BTC balance is above the minimum threshold\n /// and the active wallet is old enough, i.e. the creation period\n /// was elapsed since its creation time,\n /// - The active wallet BTC balance is above the maximum threshold.\n function requestNewWallet(BitcoinTx.UTXO calldata activeWalletMainUtxo)\n external\n {\n self.requestNewWallet(activeWalletMainUtxo);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a new ECDSA wallet is created.\n /// @param ecdsaWalletID Wallet's unique identifier.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Given wallet data must not belong to an already registered wallet.\n function __ecdsaWalletCreatedCallback(\n bytes32 ecdsaWalletID,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.registerNewWallet(ecdsaWalletID, publicKeyX, publicKeyY);\n }\n\n /// @notice A callback function that is called by the ECDSA Wallet Registry\n /// once a wallet heartbeat failure is detected.\n /// @param publicKeyX Wallet's public key's X coordinate.\n /// @param publicKeyY Wallet's public key's Y coordinate.\n /// @dev Requirements:\n /// - The only caller authorized to call this function is `registry`,\n /// - Wallet must be in Live state.\n function __ecdsaWalletHeartbeatFailedCallback(\n bytes32,\n bytes32 publicKeyX,\n bytes32 publicKeyY\n ) external override {\n self.notifyWalletHeartbeatFailed(publicKeyX, publicKeyY);\n }\n\n /// @notice Notifies that the wallet is either old enough or has too few\n /// satoshi left and qualifies to be closed.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @param walletMainUtxo Data of the wallet's main UTXO, as currently\n /// known on the Ethereum chain.\n /// @dev Requirements:\n /// - Wallet must not be set as the current active wallet,\n /// - Wallet must exceed the wallet maximum age OR the wallet BTC\n /// balance must be lesser than the minimum threshold. If the latter\n /// case is true, the `walletMainUtxo` components must point to the\n /// recent main UTXO of the given wallet, as currently known on the\n /// Ethereum chain. If the wallet has no main UTXO, this parameter\n /// can be empty as it is ignored since the wallet balance is\n /// assumed to be zero,\n /// - Wallet must be in Live state.\n function notifyWalletCloseable(\n bytes20 walletPubKeyHash,\n BitcoinTx.UTXO calldata walletMainUtxo\n ) external {\n self.notifyWalletCloseable(walletPubKeyHash, walletMainUtxo);\n }\n\n /// @notice Notifies about the end of the closing period for the given wallet.\n /// Closes the wallet ultimately and notifies the ECDSA registry\n /// about this fact.\n /// @param walletPubKeyHash 20-byte public key hash of the wallet.\n /// @dev Requirements:\n /// - The wallet must be in the Closing state,\n /// - The wallet closing period must have elapsed.\n function notifyWalletClosingPeriodElapsed(bytes20 walletPubKeyHash)\n external\n {\n self.notifyWalletClosingPeriodElapsed(walletPubKeyHash);\n }\n\n /// @notice Submits a fraud challenge indicating that a UTXO being under\n /// wallet control was unlocked by the wallet but was not used\n /// according to the protocol rules. That means the wallet signed\n /// a transaction input pointing to that UTXO and there is a unique\n /// sighash and signature pair associated with that input. This\n /// function uses those parameters to create a fraud accusation that\n /// proves a given transaction input unlocking the given UTXO was\n /// actually signed by the wallet. This function cannot determine\n /// whether the transaction was actually broadcast and the input was\n /// consumed in a fraudulent way so it just opens a challenge period\n /// during which the wallet can defeat the challenge by submitting\n /// proof of a transaction that consumes the given input according\n /// to protocol rules. To prevent spurious allegations, the caller\n /// must deposit ETH that is returned back upon justified fraud\n /// challenge or confiscated otherwise.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @param signature Bitcoin signature in the R/S/V format.\n /// @dev Requirements:\n /// - Wallet behind `walletPublicKey` must be in Live or MovingFunds\n /// or Closing state,\n /// - The challenger must send appropriate amount of ETH used as\n /// fraud challenge deposit,\n /// - The signature (represented by r, s and v) must be generated by\n /// the wallet behind `walletPubKey` during signing of `sighash`\n /// which was calculated from `preimageSha256`,\n /// - Wallet can be challenged for the given signature only once.\n function submitFraudChallenge(\n bytes calldata walletPublicKey,\n bytes memory preimageSha256,\n BitcoinTx.RSVSignature calldata signature\n ) external payable {\n self.submitFraudChallenge(walletPublicKey, preimageSha256, signature);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet if\n /// the transaction that spends the UTXO follows the protocol rules.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during input signing.\n /// The fraud challenge defeat attempt will only succeed if the\n /// inputs in the preimage are considered honestly spent by the\n /// wallet. Therefore the transaction spending the UTXO must be\n /// proven in the Bridge before a challenge defeat is called.\n /// If successfully defeated, the fraud challenge is marked as\n /// resolved and the amount of ether deposited by the challenger is\n /// sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param preimage The preimage which produces sighash used to generate the\n /// ECDSA signature that is the subject of the fraud claim. It is a\n /// serialized subset of the transaction. The exact subset used as\n /// the preimage depends on the transaction input the signature is\n /// produced for. See BIP-143 for reference.\n /// @param witness Flag indicating whether the preimage was produced for a\n /// witness input. True for witness, false for non-witness input.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as `hash256(preimage)`\n /// must identify an open fraud challenge,\n /// - the preimage must be a valid preimage of a transaction generated\n /// according to the protocol rules and already proved in the Bridge,\n /// - before a defeat attempt is made the transaction that spends the\n /// given UTXO must be proven in the Bridge.\n function defeatFraudChallenge(\n bytes calldata walletPublicKey,\n bytes calldata preimage,\n bool witness\n ) external {\n self.defeatFraudChallenge(walletPublicKey, preimage, witness);\n }\n\n /// @notice Allows to defeat a pending fraud challenge against a wallet by\n /// proving the sighash and signature were produced for an off-chain\n /// wallet heartbeat message following a strict format.\n /// In order to defeat the challenge the same `walletPublicKey` and\n /// signature (represented by `r`, `s` and `v`) must be provided as\n /// were used to calculate the sighash during heartbeat message\n /// signing. The fraud challenge defeat attempt will only succeed if\n /// the signed message follows a strict format required for\n /// heartbeat messages. If successfully defeated, the fraud\n /// challenge is marked as resolved and the amount of ether\n /// deposited by the challenger is sent to the treasury.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param heartbeatMessage Off-chain heartbeat message meeting the heartbeat\n /// message format requirements which produces sighash used to\n /// generate the ECDSA signature that is the subject of the fraud\n /// claim.\n /// @dev Requirements:\n /// - `walletPublicKey` and `sighash` calculated as\n /// `hash256(heartbeatMessage)` must identify an open fraud challenge,\n /// - `heartbeatMessage` must follow a strict format of heartbeat\n /// messages.\n function defeatFraudChallengeWithHeartbeat(\n bytes calldata walletPublicKey,\n bytes calldata heartbeatMessage\n ) external {\n self.defeatFraudChallengeWithHeartbeat(\n walletPublicKey,\n heartbeatMessage\n );\n }\n\n /// @notice Notifies about defeat timeout for the given fraud challenge.\n /// Can be called only if there was a fraud challenge identified by\n /// the provided `walletPublicKey` and `sighash` and it was not\n /// defeated on time. The amount of time that needs to pass after\n /// a fraud challenge is reported is indicated by the\n /// `challengeDefeatTimeout`. After a successful fraud challenge\n /// defeat timeout notification the fraud challenge is marked as\n /// resolved, the stake of each operator is slashed, the ether\n /// deposited is returned to the challenger and the challenger is\n /// rewarded.\n /// @param walletPublicKey The public key of the wallet in the uncompressed\n /// and unprefixed format (64 bytes).\n /// @param walletMembersIDs Identifiers of the wallet signing group members.\n /// @param preimageSha256 The hash that was generated by applying SHA-256\n /// one time over the preimage used during input signing. The preimage\n /// is a serialized subset of the transaction and its structure\n /// depends on the transaction input (see BIP-143 for reference).\n /// Notice that applying SHA-256 over the `preimageSha256` results\n /// in `sighash`. The path from `preimage` to `sighash` looks like\n /// this:\n /// preimage -> (SHA-256) -> preimageSha256 -> (SHA-256) -> sighash.\n /// @dev Requirements:\n /// - The wallet must be in the Live or MovingFunds or Closing or\n /// Terminated state,\n /// - The `walletPublicKey` and `sighash` calculated from\n /// `preimageSha256` must identify an open fraud challenge,\n /// - The expression `keccak256(abi.encode(walletMembersIDs))` must\n /// be exactly the same as the hash stored under `membersIdsHash`\n /// for the given `walletID`. Those IDs are not directly stored\n /// in the contract for gas efficiency purposes but they can be\n /// read from appropriate `DkgResultSubmitted` and `DkgResultApproved`\n /// events of the `WalletRegistry` contract,\n /// - The amount of time indicated by `challengeDefeatTimeout` must pass\n /// after the challenge was reported.\n function notifyFraudChallengeDefeatTimeout(\n bytes calldata walletPublicKey,\n uint32[] calldata walletMembersIDs,\n bytes memory preimageSha256\n ) external {\n self.notifyFraudChallengeDefeatTimeout(\n walletPublicKey,\n walletMembersIDs,\n preimageSha256\n );\n }\n\n /// @notice Allows the Governance to mark the given vault address as trusted\n /// or no longer trusted. Vaults are not trusted by default.\n /// Trusted vault must meet the following criteria:\n /// - `IVault.receiveBalanceIncrease` must have a known, low gas\n /// cost,\n /// - `IVault.receiveBalanceIncrease` must never revert.\n /// @dev Without restricting reveal only to trusted vaults, malicious\n /// vaults not meeting the criteria would be able to nuke sweep proof\n /// transactions executed by ECDSA wallet with deposits routed to\n /// them.\n /// @param vault The address of the vault.\n /// @param isTrusted flag indicating whether the vault is trusted or not.\n /// @dev Can only be called by the Governance.\n function setVaultStatus(address vault, bool isTrusted)\n external\n onlyGovernance\n {\n self.isVaultTrusted[vault] = isTrusted;\n emit VaultStatusUpdated(vault, isTrusted);\n }\n\n /// @notice Allows the Governance to mark the given address as trusted\n /// or no longer trusted SPV maintainer. Addresses are not trusted\n /// as SPV maintainers by default.\n /// @dev The SPV proof does not check whether the transaction is a part of\n /// the Bitcoin mainnet, it only checks whether the transaction has been\n /// mined performing the required amount of work as on Bitcoin mainnet.\n /// The possibility of submitting SPV proofs is limited to trusted SPV\n /// maintainers. The system expects transaction confirmations with the\n /// required work accumulated, so trusted SPV maintainers can not prove\n /// the transaction without providing the required Bitcoin proof of work.\n /// Trusted maintainers address the issue of an economic game between\n /// tBTC and Bitcoin mainnet where large Bitcoin mining pools can decide\n /// to use their hash power to mine fake Bitcoin blocks to prove them in\n /// tBTC instead of receiving Bitcoin miner rewards.\n /// @param spvMaintainer The address of the SPV maintainer.\n /// @param isTrusted flag indicating whether the address is trusted or not.\n /// @dev Can only be called by the Governance.\n function setSpvMaintainerStatus(address spvMaintainer, bool isTrusted)\n external\n onlyGovernance\n {\n self.isSpvMaintainer[spvMaintainer] = isTrusted;\n emit SpvMaintainerStatusUpdated(spvMaintainer, isTrusted);\n }\n\n /// @notice Updates parameters of deposits.\n /// @param depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor.\n /// @param depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @param depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @param depositRevealAheadPeriod New value of the deposit reveal ahead\n /// period parameter in seconds. It defines the length of the period\n /// that must be preserved between the deposit reveal time and the\n /// deposit refund locktime.\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero,\n /// - Deposit dust threshold must be greater than deposit TX max fee,\n /// - Deposit transaction max fee must be greater than zero.\n function updateDepositParameters(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n ) external onlyGovernance {\n self.updateDepositParameters(\n depositDustThreshold,\n depositTreasuryFeeDivisor,\n depositTxMaxFee,\n depositRevealAheadPeriod\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param redemptionTxMaxTotalFee New value of the redemption transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single redemption\n /// transaction. This is a _total_ max fee for the entire redemption\n /// transaction.\n /// @param redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked balance is returned to the\n /// redeemer in full amount.\n /// @param redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\n /// - Redemption dust threshold must be greater than the redemption TX\n /// max fee,\n /// - Redemption transaction max fee must be greater than zero,\n /// - Redemption transaction max total fee must be greater than or\n /// equal to the redemption transaction per-request max fee,\n /// - Redemption timeout must be greater than zero,\n /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTxMaxTotalFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param movingFundsDustThreshold New value of the moving funds dust\n /// threshold. It is the minimal satoshi amount that makes sense to\n /// be transferred during the moving funds process. Moving funds\n /// wallets having their BTC balance below that value can begin\n /// closing immediately as transferring such a low value may not be\n /// possible due to BTC network fees.\n /// @param movingFundsTimeoutResetDelay New value of the moving funds\n /// timeout reset delay in seconds. It is the time after which the\n /// moving funds timeout can be reset in case the target wallet\n /// commitment cannot be submitted due to a lack of live wallets\n /// in the system. It is counted from the moment when the wallet\n /// was requested to move their funds and switched to the MovingFunds\n /// state or from the moment the timeout was reset the last time.\n /// @param movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @param movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param movingFundsCommitmentGasOffset New value of the gas offset for\n /// moving funds target wallet commitment transaction gas costs\n /// reimbursement.\n /// @param movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout reset delay must be greater than zero,\n /// - Moving funds timeout must be greater than the moving funds\n /// timeout reset delay,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested.\n /// @param walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\n /// @param walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @param walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n // to a single target wallet during the moving funds process.\n /// @param walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges.\n /// @dev Requirements:\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance,\n /// - Wallet closure BTC balance must be greater than zero,\n /// - Wallet maximum BTC transfer must be greater than zero,\n /// - Wallet closing period must be greater than zero.\n function updateWalletParameters(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) external onlyGovernance {\n self.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit.\n /// @param fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero.\n /// @param fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud.\n /// @param fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n uint96 fraudChallengeDepositAmount,\n uint32 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint32 fraudNotifierRewardMultiplier\n ) external onlyGovernance {\n self.updateFraudParameters(\n fraudChallengeDepositAmount,\n fraudChallengeDefeatTimeout,\n fraudSlashingAmount,\n fraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates treasury address. The treasury receives the system fees.\n /// @param treasury New value of the treasury address.\n /// @dev The treasury address must not be 0x0.\n // slither-disable-next-line shadowing-local\n function updateTreasury(address treasury) external onlyGovernance {\n self.updateTreasury(treasury);\n }\n\n /// @notice Collection of all revealed deposits indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex).\n /// The fundingTxHash is bytes32 (ordered as in Bitcoin internally)\n /// and fundingOutputIndex an uint32. This mapping may contain valid\n /// and invalid deposits and the wallet is responsible for\n /// validating them before attempting to execute a sweep.\n function deposits(uint256 depositKey)\n external\n view\n returns (Deposit.DepositRequest memory)\n {\n return self.deposits[depositKey];\n }\n\n /// @notice Collection of all pending redemption requests indexed by\n /// redemption key built as\n /// `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.\n /// The walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and `redeemerOutputScript` is a Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n /// redeemed BTC as requested by the redeemer. Requests are added\n /// to this mapping by the `requestRedemption` method (duplicates\n /// not allowed) and are removed by one of the following methods:\n /// - `submitRedemptionProof` in case the request was handled\n /// successfully,\n /// - `notifyRedemptionTimeout` in case the request was reported\n /// to be timed out.\n function pendingRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.pendingRedemptions[redemptionKey];\n }\n\n /// @notice Collection of all timed out redemptions requests indexed by\n /// redemption key built as\n /// `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.\n /// The walletPubKeyHash is the 20-byte wallet's public key hash\n /// (computed using Bitcoin HASH160 over the compressed ECDSA\n /// public key) and `redeemerOutputScript` is the Bitcoin script\n /// (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n /// out request.\n /// Only one method can add to this mapping:\n /// - `notifyRedemptionTimeout` which puts the redemption key\n /// to this mapping based on a timed out request stored\n /// previously in `pendingRedemptions` mapping.\n /// Only one method can remove entries from this mapping:\n /// - `submitRedemptionProof` in case the timed out redemption\n /// request was a part of the proven transaction.\n function timedOutRedemptions(uint256 redemptionKey)\n external\n view\n returns (Redemption.RedemptionRequest memory)\n {\n return self.timedOutRedemptions[redemptionKey];\n }\n\n /// @notice Collection of main UTXOs that are honestly spent indexed by\n /// keccak256(fundingTxHash | fundingOutputIndex). The fundingTxHash\n /// is bytes32 (ordered as in Bitcoin internally) and\n /// fundingOutputIndex an uint32. A main UTXO is considered honestly\n /// spent if it was used as an input of a transaction that have been\n /// proven in the Bridge.\n function spentMainUTXOs(uint256 utxoKey) external view returns (bool) {\n return self.spentMainUTXOs[utxoKey];\n }\n\n /// @notice Gets details about a registered wallet.\n /// @param walletPubKeyHash The 20-byte wallet public key hash (computed\n /// using Bitcoin HASH160 over the compressed ECDSA public key).\n /// @return Wallet details.\n function wallets(bytes20 walletPubKeyHash)\n external\n view\n returns (Wallets.Wallet memory)\n {\n return self.registeredWallets[walletPubKeyHash];\n }\n\n /// @notice Gets the public key hash of the active wallet.\n /// @return The 20-byte public key hash (computed using Bitcoin HASH160\n /// over the compressed ECDSA public key) of the active wallet.\n /// Returns bytes20(0) if there is no active wallet at the moment.\n function activeWalletPubKeyHash() external view returns (bytes20) {\n return self.activeWalletPubKeyHash;\n }\n\n /// @notice Gets the live wallets count.\n /// @return The current count of wallets being in the Live state.\n function liveWalletsCount() external view returns (uint32) {\n return self.liveWalletsCount;\n }\n\n /// @notice Returns the fraud challenge identified by the given key built\n /// as keccak256(walletPublicKey|sighash).\n function fraudChallenges(uint256 challengeKey)\n external\n view\n returns (Fraud.FraudChallenge memory)\n {\n return self.fraudChallenges[challengeKey];\n }\n\n /// @notice Collection of all moved funds sweep requests indexed by\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n /// internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n /// is actually an UTXO representing the moved funds and is supposed\n /// to be swept with the current main UTXO of the recipient wallet.\n /// @param requestKey Request key built as\n /// `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n /// @return Details of the moved funds sweep request.\n function movedFundsSweepRequests(uint256 requestKey)\n external\n view\n returns (MovingFunds.MovedFundsSweepRequest memory)\n {\n return self.movedFundsSweepRequests[requestKey];\n }\n\n /// @notice Indicates if the vault with the given address is trusted or not.\n /// Depositors can route their revealed deposits only to trusted\n /// vaults and have trusted vaults notified about new deposits as\n /// soon as these deposits get swept. Vaults not trusted by the\n /// Bridge can still be used by Bank balance owners on their own\n /// responsibility - anyone can approve their Bank balance to any\n /// address.\n function isVaultTrusted(address vault) external view returns (bool) {\n return self.isVaultTrusted[vault];\n }\n\n /// @notice Returns the current values of Bridge deposit parameters.\n /// @return depositDustThreshold The minimal amount that can be requested\n /// to deposit. Value of this parameter must take into account the\n /// value of `depositTreasuryFeeDivisor` and `depositTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the depositor.\n /// @return depositTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each deposit and transferred to the treasury upon\n /// sweep proof submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @return depositTxMaxFee Maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @return depositRevealAheadPeriod Defines the length of the period that\n /// must be preserved between the deposit reveal time and the\n /// deposit refund locktime. For example, if the deposit become\n /// refundable on August 1st, and the ahead period is 7 days, the\n /// latest moment for deposit reveal is July 25th. Value in seconds.\n function depositParameters()\n external\n view\n returns (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n )\n {\n depositDustThreshold = self.depositDustThreshold;\n depositTreasuryFeeDivisor = self.depositTreasuryFeeDivisor;\n depositTxMaxFee = self.depositTxMaxFee;\n depositRevealAheadPeriod = self.depositRevealAheadPeriod;\n }\n\n /// @notice Returns the current values of Bridge redemption parameters.\n /// @return redemptionDustThreshold The minimal amount that can be requested\n /// for redemption. Value of this parameter must take into account\n /// the value of `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n /// parameters in order to make requests that can incur the\n /// treasury and transaction fee and still satisfy the redeemer.\n /// @return redemptionTreasuryFeeDivisor Divisor used to compute the treasury\n /// fee taken from each redemption request and transferred to the\n /// treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @return redemptionTxMaxFee Maximum amount of BTC transaction fee that\n /// can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction\n /// fee is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @return redemptionTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single redemption\n /// transaction. This is a _total_ max fee for the entire redemption\n /// transaction.\n /// @return redemptionTimeout Time after which the redemption request can be\n /// reported as timed out. It is counted from the moment when the\n /// redemption request was created via `requestRedemption` call.\n /// Reported timed out requests are cancelled and locked balance is\n /// returned to the redeemer in full amount.\n /// @return redemptionTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a redemption timeout.\n /// @return redemptionTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// redemption timeout receives. The value is in the range [0, 100].\n function redemptionParameters()\n external\n view\n returns (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n )\n {\n redemptionDustThreshold = self.redemptionDustThreshold;\n redemptionTreasuryFeeDivisor = self.redemptionTreasuryFeeDivisor;\n redemptionTxMaxFee = self.redemptionTxMaxFee;\n redemptionTxMaxTotalFee = self.redemptionTxMaxTotalFee;\n redemptionTimeout = self.redemptionTimeout;\n redemptionTimeoutSlashingAmount = self.redemptionTimeoutSlashingAmount;\n redemptionTimeoutNotifierRewardMultiplier = self\n .redemptionTimeoutNotifierRewardMultiplier;\n }\n\n /// @notice Returns the current values of Bridge moving funds between\n /// wallets parameters.\n /// @return movingFundsTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @return movingFundsDustThreshold The minimal satoshi amount that makes\n /// sense to be transferred during the moving funds process. Moving\n /// funds wallets having their BTC balance below that value can\n /// begin closing immediately as transferring such a low value may\n /// not be possible due to BTC network fees.\n /// @return movingFundsTimeoutResetDelay Time after which the moving funds\n /// timeout can be reset in case the target wallet commitment\n /// cannot be submitted due to a lack of live wallets in the system.\n /// It is counted from the moment when the wallet was requested to\n /// move their funds and switched to the MovingFunds state or from\n /// the moment the timeout was reset the last time. Value in seconds\n /// This value should be lower than the value of the\n /// `movingFundsTimeout`.\n /// @return movingFundsTimeout Time after which the moving funds process\n /// can be reported as timed out. It is counted from the moment\n /// when the wallet was requested to move their funds and switched\n /// to the MovingFunds state. Value in seconds.\n /// @return movingFundsTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moving funds timeout.\n /// @return movingFundsTimeoutNotifierRewardMultiplier The percentage of the\n /// notifier reward from the staking contract the notifier of a\n /// moving funds timeout receives. The value is in the range [0, 100].\n /// @return movingFundsCommitmentGasOffset The gas offset used for the\n /// moving funds target wallet commitment transaction cost\n /// reimbursement.\n /// @return movedFundsSweepTxMaxTotalFee Maximum amount of the total BTC\n /// transaction fee that is acceptable in a single moved funds\n /// sweep transaction. This is a _total_ max fee for the entire\n /// moved funds sweep transaction.\n /// @return movedFundsSweepTimeout Time after which the moved funds sweep\n /// process can be reported as timed out. It is counted from the\n /// moment when the wallet was requested to sweep the received funds.\n /// Value in seconds.\n /// @return movedFundsSweepTimeoutSlashingAmount The amount of stake slashed\n /// from each member of a wallet for a moved funds sweep timeout.\n /// @return movedFundsSweepTimeoutNotifierRewardMultiplier The percentage\n /// of the notifier reward from the staking contract the notifier\n /// of a moved funds sweep timeout receives. The value is in the\n /// range [0, 100].\n function movingFundsParameters()\n external\n view\n returns (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n )\n {\n movingFundsTxMaxTotalFee = self.movingFundsTxMaxTotalFee;\n movingFundsDustThreshold = self.movingFundsDustThreshold;\n movingFundsTimeoutResetDelay = self.movingFundsTimeoutResetDelay;\n movingFundsTimeout = self.movingFundsTimeout;\n movingFundsTimeoutSlashingAmount = self\n .movingFundsTimeoutSlashingAmount;\n movingFundsTimeoutNotifierRewardMultiplier = self\n .movingFundsTimeoutNotifierRewardMultiplier;\n movingFundsCommitmentGasOffset = self.movingFundsCommitmentGasOffset;\n movedFundsSweepTxMaxTotalFee = self.movedFundsSweepTxMaxTotalFee;\n movedFundsSweepTimeout = self.movedFundsSweepTimeout;\n movedFundsSweepTimeoutSlashingAmount = self\n .movedFundsSweepTimeoutSlashingAmount;\n movedFundsSweepTimeoutNotifierRewardMultiplier = self\n .movedFundsSweepTimeoutNotifierRewardMultiplier;\n }\n\n /// @return walletCreationPeriod Determines how frequently a new wallet\n /// creation can be requested. Value in seconds.\n /// @return walletCreationMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletCreationMaxBtcBalance The maximum BTC threshold in satoshi\n /// that is used to decide about wallet creation.\n /// @return walletClosureMinBtcBalance The minimum BTC threshold in satoshi\n /// that is used to decide about wallet closure.\n /// @return walletMaxAge The maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @return walletMaxBtcTransfer The maximum BTC amount in satoshi than\n /// can be transferred to a single target wallet during the moving\n /// funds process.\n /// @return walletClosingPeriod Determines the length of the wallet closing\n /// period, i.e. the period when the wallet remains in the Closing\n /// state and can be subject of deposit fraud challenges. Value\n /// in seconds.\n function walletParameters()\n external\n view\n returns (\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n )\n {\n walletCreationPeriod = self.walletCreationPeriod;\n walletCreationMinBtcBalance = self.walletCreationMinBtcBalance;\n walletCreationMaxBtcBalance = self.walletCreationMaxBtcBalance;\n walletClosureMinBtcBalance = self.walletClosureMinBtcBalance;\n walletMaxAge = self.walletMaxAge;\n walletMaxBtcTransfer = self.walletMaxBtcTransfer;\n walletClosingPeriod = self.walletClosingPeriod;\n }\n\n /// @notice Returns the current values of Bridge fraud parameters.\n /// @return fraudChallengeDepositAmount The amount of ETH in wei the party\n /// challenging the wallet for fraud needs to deposit.\n /// @return fraudChallengeDefeatTimeout The amount of time the wallet has to\n /// defeat a fraud challenge.\n /// @return fraudSlashingAmount The amount slashed from each wallet member\n /// for committing a fraud.\n /// @return fraudNotifierRewardMultiplier The percentage of the notifier\n /// reward from the staking contract the notifier of a fraud\n /// receives. The value is in the range [0, 100].\n function fraudParameters()\n external\n view\n returns (\n uint96 fraudChallengeDepositAmount,\n uint32 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint32 fraudNotifierRewardMultiplier\n )\n {\n fraudChallengeDepositAmount = self.fraudChallengeDepositAmount;\n fraudChallengeDefeatTimeout = self.fraudChallengeDefeatTimeout;\n fraudSlashingAmount = self.fraudSlashingAmount;\n fraudNotifierRewardMultiplier = self.fraudNotifierRewardMultiplier;\n }\n\n /// @notice Returns the addresses of contracts Bridge is interacting with.\n /// @return bank Address of the Bank the Bridge belongs to.\n /// @return relay Address of the Bitcoin relay providing the current Bitcoin\n /// network difficulty.\n /// @return ecdsaWalletRegistry Address of the ECDSA Wallet Registry.\n /// @return reimbursementPool Address of the Reimbursement Pool.\n function contractReferences()\n external\n view\n returns (\n Bank bank,\n IRelay relay,\n EcdsaWalletRegistry ecdsaWalletRegistry,\n ReimbursementPool reimbursementPool\n )\n {\n bank = self.bank;\n relay = self.relay;\n ecdsaWalletRegistry = self.ecdsaWalletRegistry;\n reimbursementPool = self.reimbursementPool;\n }\n\n /// @notice Address where the deposit treasury fees will be sent to.\n /// Treasury takes part in the operators rewarding process.\n function treasury() external view returns (address) {\n return self.treasury;\n }\n\n /// @notice The number of confirmations on the Bitcoin chain required to\n /// successfully evaluate an SPV proof.\n function txProofDifficultyFactor() external view returns (uint256) {\n return self.txProofDifficultyFactor;\n }\n}\n"
|
|
129
126
|
},
|
|
130
127
|
"contracts/bridge/BridgeGovernance.sol": {
|
|
131
128
|
"content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity 0.8.17;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"./BridgeGovernanceParameters.sol\";\n\nimport \"./Bridge.sol\";\n\n/// @title Bridge Governance\n/// @notice Owns the `Bridge` contract and is responsible for updating\n/// its governable parameters in respect to governance delay individual\n/// for each parameter. The other responsibility is marking a vault\n/// address as trusted or no longer trusted.\ncontract BridgeGovernance is Ownable {\n using BridgeGovernanceParameters for BridgeGovernanceParameters.DepositData;\n using BridgeGovernanceParameters for BridgeGovernanceParameters.RedemptionData;\n using BridgeGovernanceParameters for BridgeGovernanceParameters.MovingFundsData;\n using BridgeGovernanceParameters for BridgeGovernanceParameters.WalletData;\n using BridgeGovernanceParameters for BridgeGovernanceParameters.FraudData;\n using BridgeGovernanceParameters for BridgeGovernanceParameters.TreasuryData;\n\n BridgeGovernanceParameters.DepositData internal depositData;\n BridgeGovernanceParameters.RedemptionData internal redemptionData;\n BridgeGovernanceParameters.MovingFundsData internal movingFundsData;\n BridgeGovernanceParameters.WalletData internal walletData;\n BridgeGovernanceParameters.FraudData internal fraudData;\n BridgeGovernanceParameters.TreasuryData internal treasuryData;\n\n Bridge internal bridge;\n\n // Array is used to mitigate the problem with the contract size limit.\n // governanceDelays[0] -> governanceDelay\n // governanceDelays[1] -> newGovernanceDelay\n // governanceDelays[2] -> governanceDelayChangeInitiated\n uint256[3] public governanceDelays;\n\n uint256 public bridgeGovernanceTransferChangeInitiated;\n address internal newBridgeGovernance;\n\n // We skip emitting event on *Update to go down with the contract size\n // limit. The reason why we leave *Started but not including *Updated is\n // because Bridge governance transferred event can also be read from the\n // Governable bridge contract 'GovernanceTransferred(old, new)'.\n event BridgeGovernanceTransferStarted(\n address newBridgeGovernance,\n uint256 timestamp\n );\n\n event DepositDustThresholdUpdateStarted(\n uint64 newDepositDustThreshold,\n uint256 timestamp\n );\n event DepositDustThresholdUpdated(uint64 depositDustThreshold);\n\n event DepositTreasuryFeeDivisorUpdateStarted(\n uint64 depositTreasuryFeeDivisor,\n uint256 timestamp\n );\n event DepositTreasuryFeeDivisorUpdated(uint64 depositTreasuryFeeDivisor);\n\n event DepositTxMaxFeeUpdateStarted(\n uint64 newDepositTxMaxFee,\n uint256 timestamp\n );\n event DepositTxMaxFeeUpdated(uint64 depositTxMaxFee);\n\n event DepositRevealAheadPeriodUpdateStarted(\n uint32 newDepositRevealAheadPeriod,\n uint256 timestamp\n );\n event DepositRevealAheadPeriodUpdated(uint32 depositRevealAheadPeriod);\n\n event RedemptionDustThresholdUpdateStarted(\n uint64 newRedemptionDustThreshold,\n uint256 timestamp\n );\n event RedemptionDustThresholdUpdated(uint64 redemptionDustThreshold);\n\n event RedemptionTreasuryFeeDivisorUpdateStarted(\n uint64 newRedemptionTreasuryFeeDivisor,\n uint256 timestamp\n );\n event RedemptionTreasuryFeeDivisorUpdated(\n uint64 redemptionTreasuryFeeDivisor\n );\n\n event RedemptionTxMaxFeeUpdateStarted(\n uint64 newRedemptionTxMaxFee,\n uint256 timestamp\n );\n event RedemptionTxMaxFeeUpdated(uint64 redemptionTxMaxFee);\n\n event RedemptionTxMaxTotalFeeUpdateStarted(\n uint64 newRedemptionTxMaxTotalFee,\n uint256 timestamp\n );\n event RedemptionTxMaxTotalFeeUpdated(uint64 redemptionTxMaxTotalFee);\n\n event RedemptionTimeoutUpdateStarted(\n uint32 newRedemptionTimeout,\n uint256 timestamp\n );\n event RedemptionTimeoutUpdated(uint32 redemptionTimeout);\n\n event RedemptionTimeoutSlashingAmountUpdateStarted(\n uint96 newRedemptionTimeoutSlashingAmount,\n uint256 timestamp\n );\n event RedemptionTimeoutSlashingAmountUpdated(\n uint96 redemptionTimeoutSlashingAmount\n );\n\n event RedemptionTimeoutNotifierRewardMultiplierUpdateStarted(\n uint32 newRedemptionTimeoutNotifierRewardMultiplier,\n uint256 timestamp\n );\n event RedemptionTimeoutNotifierRewardMultiplierUpdated(\n uint32 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsTxMaxTotalFeeUpdateStarted(\n uint64 newMovingFundsTxMaxTotalFee,\n uint256 timestamp\n );\n event MovingFundsTxMaxTotalFeeUpdated(uint64 movingFundsTxMaxTotalFee);\n\n event MovingFundsDustThresholdUpdateStarted(\n uint64 newMovingFundsDustThreshold,\n uint256 timestamp\n );\n event MovingFundsDustThresholdUpdated(uint64 movingFundsDustThreshold);\n\n event MovingFundsTimeoutResetDelayUpdateStarted(\n uint32 newMovingFundsTimeoutResetDelay,\n uint256 timestamp\n );\n event MovingFundsTimeoutResetDelayUpdated(\n uint32 movingFundsTimeoutResetDelay\n );\n\n event MovingFundsTimeoutUpdateStarted(\n uint32 newMovingFundsTimeout,\n uint256 timestamp\n );\n event MovingFundsTimeoutUpdated(uint32 movingFundsTimeout);\n\n event MovingFundsTimeoutSlashingAmountUpdateStarted(\n uint96 newMovingFundsTimeoutSlashingAmount,\n uint256 timestamp\n );\n event MovingFundsTimeoutSlashingAmountUpdated(\n uint96 movingFundsTimeoutSlashingAmount\n );\n\n event MovingFundsTimeoutNotifierRewardMultiplierUpdateStarted(\n uint32 newMovingFundsTimeoutNotifierRewardMultiplier,\n uint256 timestamp\n );\n event MovingFundsTimeoutNotifierRewardMultiplierUpdated(\n uint32 movingFundsTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsCommitmentGasOffsetUpdateStarted(\n uint16 newMovingFundsCommitmentGasOffset,\n uint256 timestamp\n );\n event MovingFundsCommitmentGasOffsetUpdated(\n uint16 movingFundsCommitmentGasOffset\n );\n\n event MovedFundsSweepTxMaxTotalFeeUpdateStarted(\n uint64 newMovedFundsSweepTxMaxTotalFee,\n uint256 timestamp\n );\n event MovedFundsSweepTxMaxTotalFeeUpdated(\n uint64 movedFundsSweepTxMaxTotalFee\n );\n\n event MovedFundsSweepTimeoutUpdateStarted(\n uint32 newMovedFundsSweepTimeout,\n uint256 timestamp\n );\n event MovedFundsSweepTimeoutUpdated(uint32 movedFundsSweepTimeout);\n\n event MovedFundsSweepTimeoutSlashingAmountUpdateStarted(\n uint96 newMovedFundsSweepTimeoutSlashingAmount,\n uint256 timestamp\n );\n event MovedFundsSweepTimeoutSlashingAmountUpdated(\n uint96 movedFundsSweepTimeoutSlashingAmount\n );\n\n event MovedFundsSweepTimeoutNotifierRewardMultiplierUpdateStarted(\n uint32 newMovedFundsSweepTimeoutNotifierRewardMultiplier,\n uint256 timestamp\n );\n event MovedFundsSweepTimeoutNotifierRewardMultiplierUpdated(\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletCreationPeriodUpdateStarted(\n uint32 newWalletCreationPeriod,\n uint256 timestamp\n );\n event WalletCreationPeriodUpdated(uint32 walletCreationPeriod);\n\n event WalletCreationMinBtcBalanceUpdateStarted(\n uint64 newWalletCreationMinBtcBalance,\n uint256 timestamp\n );\n event WalletCreationMinBtcBalanceUpdated(\n uint64 walletCreationMinBtcBalance\n );\n\n event WalletCreationMaxBtcBalanceUpdateStarted(\n uint64 newWalletCreationMaxBtcBalance,\n uint256 timestamp\n );\n event WalletCreationMaxBtcBalanceUpdated(\n uint64 walletCreationMaxBtcBalance\n );\n\n event WalletClosureMinBtcBalanceUpdateStarted(\n uint64 newWalletClosureMinBtcBalance,\n uint256 timestamp\n );\n event WalletClosureMinBtcBalanceUpdated(uint64 walletClosureMinBtcBalance);\n\n event WalletMaxAgeUpdateStarted(uint32 newWalletMaxAge, uint256 timestamp);\n event WalletMaxAgeUpdated(uint32 walletMaxAge);\n\n event WalletMaxBtcTransferUpdateStarted(\n uint64 newWalletMaxBtcTransfer,\n uint256 timestamp\n );\n event WalletMaxBtcTransferUpdated(uint64 walletMaxBtcTransfer);\n\n event WalletClosingPeriodUpdateStarted(\n uint32 newWalletClosingPeriod,\n uint256 timestamp\n );\n event WalletClosingPeriodUpdated(uint32 walletClosingPeriod);\n\n event FraudChallengeDepositAmountUpdateStarted(\n uint96 newFraudChallengeDepositAmount,\n uint256 timestamp\n );\n event FraudChallengeDepositAmountUpdated(\n uint96 fraudChallengeDepositAmount\n );\n\n event FraudChallengeDefeatTimeoutUpdateStarted(\n uint32 newFraudChallengeDefeatTimeout,\n uint256 timestamp\n );\n event FraudChallengeDefeatTimeoutUpdated(\n uint32 fraudChallengeDefeatTimeout\n );\n\n event FraudSlashingAmountUpdateStarted(\n uint96 newFraudSlashingAmount,\n uint256 timestamp\n );\n event FraudSlashingAmountUpdated(uint96 fraudSlashingAmount);\n\n event FraudNotifierRewardMultiplierUpdateStarted(\n uint32 newFraudNotifierRewardMultiplier,\n uint256 timestamp\n );\n event FraudNotifierRewardMultiplierUpdated(\n uint32 fraudNotifierRewardMultiplier\n );\n\n event TreasuryUpdateStarted(address newTreasury, uint256 timestamp);\n event TreasuryUpdated(address treasury);\n\n constructor(Bridge _bridge, uint256 _governanceDelay) {\n bridge = _bridge;\n governanceDelays[0] = _governanceDelay;\n }\n\n /// @notice Allows the Governance to mark the given vault address as trusted\n /// or no longer trusted. Vaults are not trusted by default.\n /// Trusted vault must meet the following criteria:\n /// - `IVault.receiveBalanceIncrease` must have a known, low gas\n /// cost,\n /// - `IVault.receiveBalanceIncrease` must never revert.\n /// @param vault The address of the vault.\n /// @param isTrusted flag indicating whether the vault is trusted or not.\n function setVaultStatus(address vault, bool isTrusted) external onlyOwner {\n bridge.setVaultStatus(vault, isTrusted);\n }\n\n /// @notice Allows the Governance to mark the given address as trusted\n /// or no longer trusted SPV maintainer. Addresses are not trusted\n /// as SPV maintainers by default.\n /// @param spvMaintainer The address of the SPV maintainer.\n /// @param isTrusted flag indicating whether the address is trusted or not.\n function setSpvMaintainerStatus(address spvMaintainer, bool isTrusted)\n external\n onlyOwner\n {\n bridge.setSpvMaintainerStatus(spvMaintainer, isTrusted);\n }\n\n /// @notice Begins the governance delay update process.\n /// @dev Can be called only by the contract owner. The event that informs about\n /// the start of the governance delay was skipped on purpose to trim\n /// the contract size. All the params inside of the `governanceDelays`\n /// array are public and can be easily fetched.\n /// @param _newGovernanceDelay New governance delay\n function beginGovernanceDelayUpdate(uint256 _newGovernanceDelay)\n external\n onlyOwner\n {\n governanceDelays[1] = _newGovernanceDelay;\n /* solhint-disable not-rely-on-time */\n governanceDelays[2] = block.timestamp;\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the governance delay update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses. Updated event was skipped on purpose to trim the\n /// contract size. All the params inside of the `governanceDelays`\n /// array are public and can be easily fetched.\n function finalizeGovernanceDelayUpdate() external onlyOwner {\n require(governanceDelays[2] > 0, \"Change not initiated\");\n /* solhint-disable not-rely-on-time */\n require(\n block.timestamp - governanceDelays[2] > governanceDelay(),\n \"Governance delay has not elapsed\"\n );\n /* solhint-enable not-rely-on-time */\n governanceDelays[0] = governanceDelays[1];\n governanceDelays[1] = 0;\n governanceDelays[2] = 0;\n }\n\n /// @notice Begins the Bridge governance transfer process.\n /// @dev Can be called only by the contract owner. It is the governance\n /// responsibility to validate the correctness of the new Bridge\n /// Governance contract. The other reason for not adding this check is\n /// to go down with the contract size and leaving only the essential code.\n function beginBridgeGovernanceTransfer(address _newBridgeGovernance)\n external\n onlyOwner\n {\n // slither-disable-next-line missing-zero-check\n newBridgeGovernance = _newBridgeGovernance;\n /* solhint-disable not-rely-on-time */\n bridgeGovernanceTransferChangeInitiated = block.timestamp;\n emit BridgeGovernanceTransferStarted(\n _newBridgeGovernance,\n bridgeGovernanceTransferChangeInitiated\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the bridge governance transfer process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses. Bridge governance transferred event can be read\n /// from the Governable bridge contract 'GovernanceTransferred(old, new)'.\n /// Event that informs about the transfer in this function is skipped on\n /// purpose to go down with the contract size.\n function finalizeBridgeGovernanceTransfer() external onlyOwner {\n require(\n bridgeGovernanceTransferChangeInitiated > 0,\n \"Change not initiated\"\n );\n /* solhint-disable not-rely-on-time */\n require(\n block.timestamp - bridgeGovernanceTransferChangeInitiated >=\n governanceDelay(),\n \"Governance delay has not elapsed\"\n );\n /* solhint-enable not-rely-on-time */\n // slither-disable-next-line reentrancy-no-eth\n bridge.transferGovernance(newBridgeGovernance);\n bridgeGovernanceTransferChangeInitiated = 0;\n newBridgeGovernance = address(0);\n }\n\n // --- Deposit\n\n /// @notice Begins the deposit dust threshold amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newDepositDustThreshold New deposit dust threshold amount.\n function beginDepositDustThresholdUpdate(uint64 _newDepositDustThreshold)\n external\n onlyOwner\n {\n depositData.beginDepositDustThresholdUpdate(_newDepositDustThreshold);\n }\n\n /// @notice Finalizes the deposit dust threshold amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeDepositDustThresholdUpdate() external onlyOwner {\n (\n ,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n ) = bridge.depositParameters();\n uint64 newDepositDustThreshold = depositData.newDepositDustThreshold;\n depositData.finalizeDepositDustThresholdUpdate(governanceDelay());\n bridge.updateDepositParameters(\n newDepositDustThreshold,\n depositTreasuryFeeDivisor,\n depositTxMaxFee,\n depositRevealAheadPeriod\n );\n }\n\n /// @notice Begins the deposit treasury fee divisor amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newDepositTreasuryFeeDivisor New deposit treasury fee divisor.\n function beginDepositTreasuryFeeDivisorUpdate(\n uint64 _newDepositTreasuryFeeDivisor\n ) external onlyOwner {\n depositData.beginDepositTreasuryFeeDivisorUpdate(\n _newDepositTreasuryFeeDivisor\n );\n }\n\n /// @notice Finalizes the deposit treasury fee divisor amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeDepositTreasuryFeeDivisorUpdate() external onlyOwner {\n (\n uint64 depositDustThreshold,\n ,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n ) = bridge.depositParameters();\n uint64 newDepositTreasuryFeeDivisor = depositData\n .newDepositTreasuryFeeDivisor;\n depositData.finalizeDepositTreasuryFeeDivisorUpdate(governanceDelay());\n bridge.updateDepositParameters(\n depositDustThreshold,\n newDepositTreasuryFeeDivisor,\n depositTxMaxFee,\n depositRevealAheadPeriod\n );\n }\n\n /// @notice Begins the deposit tx max fee amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newDepositTxMaxFee New deposit tx max fee.\n function beginDepositTxMaxFeeUpdate(uint64 _newDepositTxMaxFee)\n external\n onlyOwner\n {\n depositData.beginDepositTxMaxFeeUpdate(_newDepositTxMaxFee);\n }\n\n /// @notice Finalizes the deposit tx max fee amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeDepositTxMaxFeeUpdate() external onlyOwner {\n (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n ,\n uint32 depositRevealAheadPeriod\n ) = bridge.depositParameters();\n uint64 newDepositTxMaxFee = depositData.newDepositTxMaxFee;\n depositData.finalizeDepositTxMaxFeeUpdate(governanceDelay());\n bridge.updateDepositParameters(\n depositDustThreshold,\n depositTreasuryFeeDivisor,\n newDepositTxMaxFee,\n depositRevealAheadPeriod\n );\n }\n\n /// @notice Begins the deposit reveal ahead period update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newDepositRevealAheadPeriod New deposit reveal ahead period.\n function beginDepositRevealAheadPeriodUpdate(\n uint32 _newDepositRevealAheadPeriod\n ) external onlyOwner {\n depositData.beginDepositRevealAheadPeriodUpdate(\n _newDepositRevealAheadPeriod\n );\n }\n\n /// @notice Finalizes the deposit reveal ahead period update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeDepositRevealAheadPeriodUpdate() external onlyOwner {\n (\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n\n ) = bridge.depositParameters();\n uint32 newDepositRevealAheadPeriod = depositData\n .newDepositRevealAheadPeriod;\n depositData.finalizeDepositRevealAheadPeriodUpdate(governanceDelay());\n bridge.updateDepositParameters(\n depositDustThreshold,\n depositTreasuryFeeDivisor,\n depositTxMaxFee,\n newDepositRevealAheadPeriod\n );\n }\n\n // --- Redemption\n\n /// @notice Begins the redemption dust threshold amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newRedemptionDustThreshold New redemption dust threshold.\n function beginRedemptionDustThresholdUpdate(\n uint64 _newRedemptionDustThreshold\n ) external onlyOwner {\n redemptionData.beginRedemptionDustThresholdUpdate(\n _newRedemptionDustThreshold\n );\n }\n\n /// @notice Finalizes the dust threshold amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeRedemptionDustThresholdUpdate() external onlyOwner {\n (\n ,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n ) = bridge.redemptionParameters();\n uint64 newRedemptionDustThreshold = redemptionData\n .newRedemptionDustThreshold;\n redemptionData.finalizeRedemptionDustThresholdUpdate(governanceDelay());\n bridge.updateRedemptionParameters(\n newRedemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTxMaxTotalFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the redemption treasury fee divisor amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newRedemptionTreasuryFeeDivisor New redemption treasury fee divisor.\n function beginRedemptionTreasuryFeeDivisorUpdate(\n uint64 _newRedemptionTreasuryFeeDivisor\n ) external onlyOwner {\n redemptionData.beginRedemptionTreasuryFeeDivisorUpdate(\n _newRedemptionTreasuryFeeDivisor\n );\n }\n\n /// @notice Finalizes the redemption treasury fee divisor amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeRedemptionTreasuryFeeDivisorUpdate() external onlyOwner {\n (\n uint64 redemptionDustThreshold,\n ,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n ) = bridge.redemptionParameters();\n // slither-disable-next-line reentrancy-no-eth\n uint64 newRedemptionTreasuryFeeDivisor = redemptionData\n .newRedemptionTreasuryFeeDivisor;\n redemptionData.finalizeRedemptionTreasuryFeeDivisorUpdate(\n governanceDelay()\n );\n bridge.updateRedemptionParameters(\n redemptionDustThreshold,\n newRedemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTxMaxTotalFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the redemption tx max fee amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newRedemptionTxMaxFee New redemption tx max fee.\n function beginRedemptionTxMaxFeeUpdate(uint64 _newRedemptionTxMaxFee)\n external\n onlyOwner\n {\n redemptionData.beginRedemptionTxMaxFeeUpdate(_newRedemptionTxMaxFee);\n }\n\n /// @notice Finalizes the redemption tx max fee amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeRedemptionTxMaxFeeUpdate() external onlyOwner {\n (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n ,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n ) = bridge.redemptionParameters();\n uint64 newRedemptionTxMaxFee = redemptionData.newRedemptionTxMaxFee;\n redemptionData.finalizeRedemptionTxMaxFeeUpdate(governanceDelay());\n bridge.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n newRedemptionTxMaxFee,\n redemptionTxMaxTotalFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the redemption tx max total fee amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newRedemptionTxMaxTotalFee New redemption tx max total fee.\n function beginRedemptionTxMaxTotalFeeUpdate(\n uint64 _newRedemptionTxMaxTotalFee\n ) external onlyOwner {\n redemptionData.beginRedemptionTxMaxTotalFeeUpdate(\n _newRedemptionTxMaxTotalFee\n );\n }\n\n /// @notice Finalizes the redemption tx max total fee amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeRedemptionTxMaxTotalFeeUpdate() external onlyOwner {\n (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n ,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n ) = bridge.redemptionParameters();\n uint64 newRedemptionTxMaxTotalFee = redemptionData\n .newRedemptionTxMaxTotalFee;\n redemptionData.finalizeRedemptionTxMaxTotalFeeUpdate(governanceDelay());\n bridge.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n newRedemptionTxMaxTotalFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the redemption timeout amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newRedemptionTimeout New redemption timeout.\n function beginRedemptionTimeoutUpdate(uint32 _newRedemptionTimeout)\n external\n onlyOwner\n {\n redemptionData.beginRedemptionTimeoutUpdate(_newRedemptionTimeout);\n }\n\n /// @notice Finalizes the redemption timeout amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeRedemptionTimeoutUpdate() external onlyOwner {\n (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n ,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n ) = bridge.redemptionParameters();\n uint32 newRedemptionTimeout = redemptionData.newRedemptionTimeout;\n redemptionData.finalizeRedemptionTimeoutUpdate(governanceDelay());\n bridge.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTxMaxTotalFee,\n newRedemptionTimeout,\n redemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the redemption timeout slashing amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newRedemptionTimeoutSlashingAmount New redemption timeout slashing\n /// amount.\n function beginRedemptionTimeoutSlashingAmountUpdate(\n uint96 _newRedemptionTimeoutSlashingAmount\n ) external onlyOwner {\n redemptionData.beginRedemptionTimeoutSlashingAmountUpdate(\n _newRedemptionTimeoutSlashingAmount\n );\n }\n\n /// @notice Finalizes the redemption timeout slashing amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeRedemptionTimeoutSlashingAmountUpdate()\n external\n onlyOwner\n {\n (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n ,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n ) = bridge.redemptionParameters();\n uint96 newRedemptionTimeoutSlashingAmount = redemptionData\n .newRedemptionTimeoutSlashingAmount;\n redemptionData.finalizeRedemptionTimeoutSlashingAmountUpdate(\n governanceDelay()\n );\n bridge.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTxMaxTotalFee,\n redemptionTimeout,\n newRedemptionTimeoutSlashingAmount,\n redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the redemption timeout notifier reward multiplier amount\n /// update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newRedemptionTimeoutNotifierRewardMultiplier New redemption timeout\n /// notifier reward multiplier.\n function beginRedemptionTimeoutNotifierRewardMultiplierUpdate(\n uint32 _newRedemptionTimeoutNotifierRewardMultiplier\n ) external onlyOwner {\n redemptionData.beginRedemptionTimeoutNotifierRewardMultiplierUpdate(\n _newRedemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Finalizes the redemption timeout notifier reward multiplier amount\n /// update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeRedemptionTimeoutNotifierRewardMultiplierUpdate()\n external\n onlyOwner\n {\n (\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n\n ) = bridge.redemptionParameters();\n uint32 newRedemptionTimeoutNotifierRewardMultiplier = redemptionData\n .newRedemptionTimeoutNotifierRewardMultiplier;\n redemptionData.finalizeRedemptionTimeoutNotifierRewardMultiplierUpdate(\n governanceDelay()\n );\n bridge.updateRedemptionParameters(\n redemptionDustThreshold,\n redemptionTreasuryFeeDivisor,\n redemptionTxMaxFee,\n redemptionTxMaxTotalFee,\n redemptionTimeout,\n redemptionTimeoutSlashingAmount,\n newRedemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n // --- Moving funds\n\n /// @notice Begins the moving funds tx max total fee update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovingFundsTxMaxTotalFee New moving funds tx max total fee.\n function beginMovingFundsTxMaxTotalFeeUpdate(\n uint64 _newMovingFundsTxMaxTotalFee\n ) external onlyOwner {\n movingFundsData.beginMovingFundsTxMaxTotalFeeUpdate(\n _newMovingFundsTxMaxTotalFee\n );\n }\n\n /// @notice Finalizes the moving funds tx max total fee update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovingFundsTxMaxTotalFeeUpdate() external onlyOwner {\n (\n ,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) = bridge.movingFundsParameters();\n uint64 newMovingFundsTxMaxTotalFee = movingFundsData\n .newMovingFundsTxMaxTotalFee;\n movingFundsData.finalizeMovingFundsTxMaxTotalFeeUpdate(\n governanceDelay()\n );\n bridge.updateMovingFundsParameters(\n newMovingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the moving funds dust threshold update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovingFundsDustThreshold New moving funds dust threshold.\n function beginMovingFundsDustThresholdUpdate(\n uint64 _newMovingFundsDustThreshold\n ) external onlyOwner {\n movingFundsData.beginMovingFundsDustThresholdUpdate(\n _newMovingFundsDustThreshold\n );\n }\n\n /// @notice Finalizes the moving funds dust threshold update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovingFundsDustThresholdUpdate() external onlyOwner {\n (\n uint64 movingFundsTxMaxTotalFee,\n ,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) = bridge.movingFundsParameters();\n uint64 newMovingFundsDustThreshold = movingFundsData\n .newMovingFundsDustThreshold;\n movingFundsData.finalizeMovingFundsDustThresholdUpdate(\n governanceDelay()\n );\n bridge.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n newMovingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the moving funds timeout reset delay update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovingFundsTimeoutResetDelay New moving funds timeout reset\n /// delay.\n function beginMovingFundsTimeoutResetDelayUpdate(\n uint32 _newMovingFundsTimeoutResetDelay\n ) external onlyOwner {\n movingFundsData.beginMovingFundsTimeoutResetDelayUpdate(\n _newMovingFundsTimeoutResetDelay\n );\n }\n\n /// @notice Finalizes the moving funds timeout reset delay update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovingFundsTimeoutResetDelayUpdate() external onlyOwner {\n (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n ,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) = bridge.movingFundsParameters();\n uint32 newMovingFundsTimeoutResetDelay = movingFundsData\n .newMovingFundsTimeoutResetDelay;\n movingFundsData.finalizeMovingFundsTimeoutResetDelayUpdate(\n governanceDelay()\n );\n bridge.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n newMovingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the moving funds timeout update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovingFundsTimeout New moving funds timeout.\n function beginMovingFundsTimeoutUpdate(uint32 _newMovingFundsTimeout)\n external\n onlyOwner\n {\n movingFundsData.beginMovingFundsTimeoutUpdate(_newMovingFundsTimeout);\n }\n\n /// @notice Finalizes the moving funds timeout update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovingFundsTimeoutUpdate() external onlyOwner {\n (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n ,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) = bridge.movingFundsParameters();\n uint32 newMovingFundsTimeout = movingFundsData.newMovingFundsTimeout;\n movingFundsData.finalizeMovingFundsTimeoutUpdate(governanceDelay());\n bridge.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n newMovingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the moving funds timeout slashing amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovingFundsTimeoutSlashingAmount New moving funds timeout\n /// slashing amount.\n function beginMovingFundsTimeoutSlashingAmountUpdate(\n uint96 _newMovingFundsTimeoutSlashingAmount\n ) external onlyOwner {\n movingFundsData.beginMovingFundsTimeoutSlashingAmountUpdate(\n _newMovingFundsTimeoutSlashingAmount\n );\n }\n\n /// @notice Finalizes the moving funds timeout slashing amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovingFundsTimeoutSlashingAmountUpdate()\n external\n onlyOwner\n {\n (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n ,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) = bridge.movingFundsParameters();\n uint96 newMovingFundsTimeoutSlashingAmount = movingFundsData\n .newMovingFundsTimeoutSlashingAmount;\n movingFundsData.finalizeMovingFundsTimeoutSlashingAmountUpdate(\n governanceDelay()\n );\n bridge.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n newMovingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the moving funds timeout notifier reward multiplier update\n /// process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovingFundsTimeoutNotifierRewardMultiplier New moving funds\n /// timeout notifier reward multiplier.\n function beginMovingFundsTimeoutNotifierRewardMultiplierUpdate(\n uint32 _newMovingFundsTimeoutNotifierRewardMultiplier\n ) external onlyOwner {\n movingFundsData.beginMovingFundsTimeoutNotifierRewardMultiplierUpdate(\n _newMovingFundsTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Finalizes the moving funds timeout notifier reward multiplier\n /// update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovingFundsTimeoutNotifierRewardMultiplierUpdate()\n external\n onlyOwner\n {\n (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n ,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) = bridge.movingFundsParameters();\n uint32 newMovingFundsTimeoutNotifierRewardMultiplier = movingFundsData\n .newMovingFundsTimeoutNotifierRewardMultiplier;\n movingFundsData\n .finalizeMovingFundsTimeoutNotifierRewardMultiplierUpdate(\n governanceDelay()\n );\n bridge.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n newMovingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the moving funds commitment gas offset update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovingFundsCommitmentGasOffset New moving funds commitment\n /// gas offset.\n function beginMovingFundsCommitmentGasOffsetUpdate(\n uint16 _newMovingFundsCommitmentGasOffset\n ) external onlyOwner {\n movingFundsData.beginMovingFundsCommitmentGasOffsetUpdate(\n _newMovingFundsCommitmentGasOffset\n );\n }\n\n /// @notice Finalizes the moving funds commitment gas offset update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovingFundsCommitmentGasOffsetUpdate() external onlyOwner {\n (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n ,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) = bridge.movingFundsParameters();\n uint16 newMovingFundsCommitmentGasOffset = movingFundsData\n .newMovingFundsCommitmentGasOffset;\n movingFundsData.finalizeMovingFundsCommitmentGasOffsetUpdate(\n governanceDelay()\n );\n bridge.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n newMovingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the moved funds sweep tx max total fee update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovedFundsSweepTxMaxTotalFee New moved funds sweep tx max total\n /// fee.\n function beginMovedFundsSweepTxMaxTotalFeeUpdate(\n uint64 _newMovedFundsSweepTxMaxTotalFee\n ) external onlyOwner {\n movingFundsData.beginMovedFundsSweepTxMaxTotalFeeUpdate(\n _newMovedFundsSweepTxMaxTotalFee\n );\n }\n\n /// @notice Finalizes the moved funds sweep tx max total fee update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovedFundsSweepTxMaxTotalFeeUpdate() external onlyOwner {\n (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n ,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) = bridge.movingFundsParameters();\n uint64 newMovedFundsSweepTxMaxTotalFee = movingFundsData\n .newMovedFundsSweepTxMaxTotalFee;\n movingFundsData.finalizeMovedFundsSweepTxMaxTotalFeeUpdate(\n governanceDelay()\n );\n bridge.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n newMovedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the moved funds sweep timeout update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovedFundsSweepTimeout New moved funds sweep timeout.\n function beginMovedFundsSweepTimeoutUpdate(\n uint32 _newMovedFundsSweepTimeout\n ) external onlyOwner {\n movingFundsData.beginMovedFundsSweepTimeoutUpdate(\n _newMovedFundsSweepTimeout\n );\n }\n\n /// @notice Finalizes the moved funds sweep timeout update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovedFundsSweepTimeoutUpdate() external onlyOwner {\n (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n ,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) = bridge.movingFundsParameters();\n uint32 newMovedFundsSweepTimeout = movingFundsData\n .newMovedFundsSweepTimeout;\n movingFundsData.finalizeMovedFundsSweepTimeoutUpdate(governanceDelay());\n bridge.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n newMovedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the moved funds sweep timeout slashing amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovedFundsSweepTimeoutSlashingAmount New moved funds sweep\n /// timeout slashing amount.\n function beginMovedFundsSweepTimeoutSlashingAmountUpdate(\n uint96 _newMovedFundsSweepTimeoutSlashingAmount\n ) external onlyOwner {\n movingFundsData.beginMovedFundsSweepTimeoutSlashingAmountUpdate(\n _newMovedFundsSweepTimeoutSlashingAmount\n );\n }\n\n /// @notice Finalizes the moved funds sweep timeout slashing amount update\n /// process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovedFundsSweepTimeoutSlashingAmountUpdate()\n external\n onlyOwner\n {\n (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n ,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n ) = bridge.movingFundsParameters();\n uint96 newMovedFundsSweepTimeoutSlashingAmount = movingFundsData\n .newMovedFundsSweepTimeoutSlashingAmount;\n movingFundsData.finalizeMovedFundsSweepTimeoutSlashingAmountUpdate(\n governanceDelay()\n );\n bridge.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n newMovedFundsSweepTimeoutSlashingAmount,\n movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the moved funds sweep timeout notifier reward multiplier\n /// update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newMovedFundsSweepTimeoutNotifierRewardMultiplier New moved funds\n /// sweep timeout notifier reward multiplier.\n function beginMovedFundsSweepTimeoutNotifierRewardMultiplierUpdate(\n uint32 _newMovedFundsSweepTimeoutNotifierRewardMultiplier\n ) external onlyOwner {\n movingFundsData\n .beginMovedFundsSweepTimeoutNotifierRewardMultiplierUpdate(\n _newMovedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Finalizes the moved funds sweep timeout notifier reward multiplier\n /// update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeMovedFundsSweepTimeoutNotifierRewardMultiplierUpdate()\n external\n onlyOwner\n {\n (\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n\n ) = bridge.movingFundsParameters();\n uint32 newMovedFundsSweepTimeoutNotifierRewardMultiplier = movingFundsData\n .newMovedFundsSweepTimeoutNotifierRewardMultiplier;\n movingFundsData\n .finalizeMovedFundsSweepTimeoutNotifierRewardMultiplierUpdate(\n governanceDelay()\n );\n bridge.updateMovingFundsParameters(\n movingFundsTxMaxTotalFee,\n movingFundsDustThreshold,\n movingFundsTimeoutResetDelay,\n movingFundsTimeout,\n movingFundsTimeoutSlashingAmount,\n movingFundsTimeoutNotifierRewardMultiplier,\n movingFundsCommitmentGasOffset,\n movedFundsSweepTxMaxTotalFee,\n movedFundsSweepTimeout,\n movedFundsSweepTimeoutSlashingAmount,\n newMovedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n // --- Wallet creation\n\n /// @notice Begins the wallet creation period update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newWalletCreationPeriod New wallet creation period.\n function beginWalletCreationPeriodUpdate(uint32 _newWalletCreationPeriod)\n external\n onlyOwner\n {\n walletData.beginWalletCreationPeriodUpdate(_newWalletCreationPeriod);\n }\n\n /// @notice Finalizes the wallet creation period update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeWalletCreationPeriodUpdate() external onlyOwner {\n (\n ,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) = bridge.walletParameters();\n uint32 newWalletCreationPeriod = walletData.newWalletCreationPeriod;\n walletData.finalizeWalletCreationPeriodUpdate(governanceDelay());\n bridge.updateWalletParameters(\n newWalletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Begins the wallet creation min btc balance update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newWalletCreationMinBtcBalance New wallet creation min btc balance.\n function beginWalletCreationMinBtcBalanceUpdate(\n uint64 _newWalletCreationMinBtcBalance\n ) external onlyOwner {\n walletData.beginWalletCreationMinBtcBalanceUpdate(\n _newWalletCreationMinBtcBalance\n );\n }\n\n /// @notice Finalizes the wallet creation min btc balance update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeWalletCreationMinBtcBalanceUpdate() external onlyOwner {\n (\n uint32 walletCreationPeriod,\n ,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) = bridge.walletParameters();\n uint64 newWalletCreationMinBtcBalance = walletData\n .newWalletCreationMinBtcBalance;\n walletData.finalizeWalletCreationMinBtcBalanceUpdate(governanceDelay());\n bridge.updateWalletParameters(\n walletCreationPeriod,\n newWalletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Begins the wallet creation max btc balance update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newWalletCreationMaxBtcBalance New wallet creation max btc\n /// balance.\n function beginWalletCreationMaxBtcBalanceUpdate(\n uint64 _newWalletCreationMaxBtcBalance\n ) external onlyOwner {\n walletData.beginWalletCreationMaxBtcBalanceUpdate(\n _newWalletCreationMaxBtcBalance\n );\n }\n\n /// @notice Finalizes the wallet creation max btc balance update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeWalletCreationMaxBtcBalanceUpdate() external onlyOwner {\n (\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n ,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) = bridge.walletParameters();\n uint64 newWalletCreationMaxBtcBalance = walletData\n .newWalletCreationMaxBtcBalance;\n walletData.finalizeWalletCreationMaxBtcBalanceUpdate(governanceDelay());\n bridge.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n newWalletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Begins the wallet closure min btc balance update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newWalletClosureMinBtcBalance New wallet closure min btc balance.\n function beginWalletClosureMinBtcBalanceUpdate(\n uint64 _newWalletClosureMinBtcBalance\n ) external onlyOwner {\n walletData.beginWalletClosureMinBtcBalanceUpdate(\n _newWalletClosureMinBtcBalance\n );\n }\n\n /// @notice Finalizes the wallet closure min btc balance update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeWalletClosureMinBtcBalanceUpdate() external onlyOwner {\n (\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n ,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) = bridge.walletParameters();\n uint64 newWalletClosureMinBtcBalance = walletData\n .newWalletClosureMinBtcBalance;\n walletData.finalizeWalletClosureMinBtcBalanceUpdate(governanceDelay());\n bridge.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n newWalletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Begins the wallet max age update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newWalletMaxAge New wallet max age.\n function beginWalletMaxAgeUpdate(uint32 _newWalletMaxAge)\n external\n onlyOwner\n {\n walletData.beginWalletMaxAgeUpdate(_newWalletMaxAge);\n }\n\n /// @notice Finalizes the wallet max age update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeWalletMaxAgeUpdate() external onlyOwner {\n (\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n ,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n ) = bridge.walletParameters();\n uint32 newWalletMaxAge = walletData.newWalletMaxAge;\n walletData.finalizeWalletMaxAgeUpdate(governanceDelay());\n bridge.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n newWalletMaxAge,\n walletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Begins the wallet max btc transfer amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newWalletMaxBtcTransfer New wallet max btc transfer.\n function beginWalletMaxBtcTransferUpdate(uint64 _newWalletMaxBtcTransfer)\n external\n onlyOwner\n {\n walletData.beginWalletMaxBtcTransferUpdate(_newWalletMaxBtcTransfer);\n }\n\n /// @notice Finalizes the wallet max btc transfer amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeWalletMaxBtcTransferUpdate() external onlyOwner {\n (\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n ,\n uint32 walletClosingPeriod\n ) = bridge.walletParameters();\n uint64 newWalletMaxBtcTransfer = walletData.newWalletMaxBtcTransfer;\n walletData.finalizeWalletMaxBtcTransferUpdate(governanceDelay());\n bridge.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n newWalletMaxBtcTransfer,\n walletClosingPeriod\n );\n }\n\n /// @notice Begins the wallet closing period update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newWalletClosingPeriod New wallet closing period.\n function beginWalletClosingPeriodUpdate(uint32 _newWalletClosingPeriod)\n external\n onlyOwner\n {\n walletData.beginWalletClosingPeriodUpdate(_newWalletClosingPeriod);\n }\n\n /// @notice Finalizes the wallet closing period update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeWalletClosingPeriodUpdate() external onlyOwner {\n (\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n\n ) = bridge.walletParameters();\n uint32 newWalletClosingPeriod = walletData.newWalletClosingPeriod;\n walletData.finalizeWalletClosingPeriodUpdate(governanceDelay());\n bridge.updateWalletParameters(\n walletCreationPeriod,\n walletCreationMinBtcBalance,\n walletCreationMaxBtcBalance,\n walletClosureMinBtcBalance,\n walletMaxAge,\n walletMaxBtcTransfer,\n newWalletClosingPeriod\n );\n }\n\n // --- Fraud\n\n /// @notice Begins the fraud challenge deposit amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newFraudChallengeDepositAmount New fraud challenge deposit amount.\n function beginFraudChallengeDepositAmountUpdate(\n uint96 _newFraudChallengeDepositAmount\n ) external onlyOwner {\n fraudData.beginFraudChallengeDepositAmountUpdate(\n _newFraudChallengeDepositAmount\n );\n }\n\n /// @notice Finalizes the fraud challenge deposit amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeFraudChallengeDepositAmountUpdate() external onlyOwner {\n (\n ,\n uint32 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint32 fraudNotifierRewardMultiplier\n ) = bridge.fraudParameters();\n uint96 newFraudChallengeDepositAmount = fraudData\n .newFraudChallengeDepositAmount;\n fraudData.finalizeFraudChallengeDepositAmountUpdate(governanceDelay());\n bridge.updateFraudParameters(\n newFraudChallengeDepositAmount,\n fraudChallengeDefeatTimeout,\n fraudSlashingAmount,\n fraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the fraud challenge defeat timeout update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newFraudChallengeDefeatTimeout New fraud challenge defeat timeout.\n function beginFraudChallengeDefeatTimeoutUpdate(\n uint32 _newFraudChallengeDefeatTimeout\n ) external onlyOwner {\n fraudData.beginFraudChallengeDefeatTimeoutUpdate(\n _newFraudChallengeDefeatTimeout\n );\n }\n\n /// @notice Finalizes the fraud challenge defeat timeout update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeFraudChallengeDefeatTimeoutUpdate() external onlyOwner {\n (\n uint96 fraudChallengeDepositAmount,\n ,\n uint96 fraudSlashingAmount,\n uint32 fraudNotifierRewardMultiplier\n ) = bridge.fraudParameters();\n uint32 newFraudChallengeDefeatTimeout = fraudData\n .newFraudChallengeDefeatTimeout;\n fraudData.finalizeFraudChallengeDefeatTimeoutUpdate(governanceDelay());\n bridge.updateFraudParameters(\n fraudChallengeDepositAmount,\n newFraudChallengeDefeatTimeout,\n fraudSlashingAmount,\n fraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the fraud slashing amount update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newFraudSlashingAmount New fraud slashing amount.\n function beginFraudSlashingAmountUpdate(uint96 _newFraudSlashingAmount)\n external\n onlyOwner\n {\n fraudData.beginFraudSlashingAmountUpdate(_newFraudSlashingAmount);\n }\n\n /// @notice Finalizes the fraud slashing amount update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeFraudSlashingAmountUpdate() external onlyOwner {\n (\n uint96 fraudChallengeDepositAmount,\n uint32 fraudChallengeDefeatTimeout,\n ,\n uint32 fraudNotifierRewardMultiplier\n ) = bridge.fraudParameters();\n uint96 newFraudSlashingAmount = fraudData.newFraudSlashingAmount;\n fraudData.finalizeFraudSlashingAmountUpdate(governanceDelay());\n bridge.updateFraudParameters(\n fraudChallengeDepositAmount,\n fraudChallengeDefeatTimeout,\n newFraudSlashingAmount,\n fraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the fraud notifier reward multiplier update process.\n /// @dev Can be called only by the contract owner.\n /// @param _newFraudNotifierRewardMultiplier New fraud notifier reward\n /// multiplier.\n function beginFraudNotifierRewardMultiplierUpdate(\n uint32 _newFraudNotifierRewardMultiplier\n ) external onlyOwner {\n fraudData.beginFraudNotifierRewardMultiplierUpdate(\n _newFraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Finalizes the fraud notifier reward multiplier update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeFraudNotifierRewardMultiplierUpdate() external onlyOwner {\n (\n uint96 fraudChallengeDepositAmount,\n uint32 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n\n ) = bridge.fraudParameters();\n uint32 newFraudNotifierRewardMultiplier = fraudData\n .newFraudNotifierRewardMultiplier;\n fraudData.finalizeFraudNotifierRewardMultiplierUpdate(\n governanceDelay()\n );\n bridge.updateFraudParameters(\n fraudChallengeDepositAmount,\n fraudChallengeDefeatTimeout,\n fraudSlashingAmount,\n newFraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Begins the treasury address update process.\n /// @dev Can be called only by the contract owner. It does not perform\n /// any parameter validation.\n /// @param _newTreasury New treasury address.\n function beginTreasuryUpdate(address _newTreasury) external onlyOwner {\n treasuryData.beginTreasuryUpdate(_newTreasury);\n }\n\n /// @notice Finalizes the treasury address update process.\n /// @dev Can be called only by the contract owner, after the governance\n /// delay elapses.\n function finalizeTreasuryUpdate() external onlyOwner {\n address newTreasury = treasuryData.newTreasury;\n treasuryData.finalizeTreasuryUpdate(governanceDelay());\n bridge.updateTreasury(newTreasury);\n }\n\n /// @notice Gets the governance delay parameter.\n function governanceDelay() internal view returns (uint256) {\n return governanceDelays[0];\n }\n}\n"
|
|
@@ -134,7 +131,7 @@
|
|
|
134
131
|
"content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity 0.8.17;\n\n/// @title Bridge Governance library for storing updatable parameters.\nlibrary BridgeGovernanceParameters {\n struct TreasuryData {\n address newTreasury;\n uint256 treasuryChangeInitiated;\n }\n\n struct DepositData {\n uint64 newDepositDustThreshold;\n uint256 depositDustThresholdChangeInitiated;\n uint64 newDepositTreasuryFeeDivisor;\n uint256 depositTreasuryFeeDivisorChangeInitiated;\n uint64 newDepositTxMaxFee;\n uint256 depositTxMaxFeeChangeInitiated;\n uint32 newDepositRevealAheadPeriod;\n uint256 depositRevealAheadPeriodChangeInitiated;\n }\n\n struct RedemptionData {\n uint64 newRedemptionDustThreshold;\n uint256 redemptionDustThresholdChangeInitiated;\n uint64 newRedemptionTreasuryFeeDivisor;\n uint256 redemptionTreasuryFeeDivisorChangeInitiated;\n uint64 newRedemptionTxMaxFee;\n uint256 redemptionTxMaxFeeChangeInitiated;\n uint64 newRedemptionTxMaxTotalFee;\n uint256 redemptionTxMaxTotalFeeChangeInitiated;\n uint32 newRedemptionTimeout;\n uint256 redemptionTimeoutChangeInitiated;\n uint96 newRedemptionTimeoutSlashingAmount;\n uint256 redemptionTimeoutSlashingAmountChangeInitiated;\n uint32 newRedemptionTimeoutNotifierRewardMultiplier;\n uint256 redemptionTimeoutNotifierRewardMultiplierChangeInitiated;\n }\n\n struct MovingFundsData {\n uint64 newMovingFundsTxMaxTotalFee;\n uint256 movingFundsTxMaxTotalFeeChangeInitiated;\n uint64 newMovingFundsDustThreshold;\n uint256 movingFundsDustThresholdChangeInitiated;\n uint32 newMovingFundsTimeoutResetDelay;\n uint256 movingFundsTimeoutResetDelayChangeInitiated;\n uint32 newMovingFundsTimeout;\n uint256 movingFundsTimeoutChangeInitiated;\n uint96 newMovingFundsTimeoutSlashingAmount;\n uint256 movingFundsTimeoutSlashingAmountChangeInitiated;\n uint32 newMovingFundsTimeoutNotifierRewardMultiplier;\n uint256 movingFundsTimeoutNotifierRewardMultiplierChangeInitiated;\n uint16 newMovingFundsCommitmentGasOffset;\n uint256 movingFundsCommitmentGasOffsetChangeInitiated;\n uint64 newMovedFundsSweepTxMaxTotalFee;\n uint256 movedFundsSweepTxMaxTotalFeeChangeInitiated;\n uint32 newMovedFundsSweepTimeout;\n uint256 movedFundsSweepTimeoutChangeInitiated;\n uint96 newMovedFundsSweepTimeoutSlashingAmount;\n uint256 movedFundsSweepTimeoutSlashingAmountChangeInitiated;\n uint32 newMovedFundsSweepTimeoutNotifierRewardMultiplier;\n uint256 movedFundsSweepTimeoutNotifierRewardMultiplierChangeInitiated;\n }\n\n struct WalletData {\n uint32 newWalletCreationPeriod;\n uint256 walletCreationPeriodChangeInitiated;\n uint64 newWalletCreationMinBtcBalance;\n uint256 walletCreationMinBtcBalanceChangeInitiated;\n uint64 newWalletCreationMaxBtcBalance;\n uint256 walletCreationMaxBtcBalanceChangeInitiated;\n uint64 newWalletClosureMinBtcBalance;\n uint256 walletClosureMinBtcBalanceChangeInitiated;\n uint32 newWalletMaxAge;\n uint256 walletMaxAgeChangeInitiated;\n uint64 newWalletMaxBtcTransfer;\n uint256 walletMaxBtcTransferChangeInitiated;\n uint32 newWalletClosingPeriod;\n uint256 walletClosingPeriodChangeInitiated;\n }\n\n struct FraudData {\n uint96 newFraudChallengeDepositAmount;\n uint256 fraudChallengeDepositAmountChangeInitiated;\n uint32 newFraudChallengeDefeatTimeout;\n uint256 fraudChallengeDefeatTimeoutChangeInitiated;\n uint96 newFraudSlashingAmount;\n uint256 fraudSlashingAmountChangeInitiated;\n uint32 newFraudNotifierRewardMultiplier;\n uint256 fraudNotifierRewardMultiplierChangeInitiated;\n }\n\n event DepositDustThresholdUpdateStarted(\n uint64 newDepositDustThreshold,\n uint256 timestamp\n );\n event DepositDustThresholdUpdated(uint64 depositDustThreshold);\n\n event DepositTreasuryFeeDivisorUpdateStarted(\n uint64 depositTreasuryFeeDivisor,\n uint256 timestamp\n );\n event DepositTreasuryFeeDivisorUpdated(uint64 depositTreasuryFeeDivisor);\n\n event DepositTxMaxFeeUpdateStarted(\n uint64 newDepositTxMaxFee,\n uint256 timestamp\n );\n event DepositTxMaxFeeUpdated(uint64 depositTxMaxFee);\n\n event DepositRevealAheadPeriodUpdateStarted(\n uint32 newDepositRevealAheadPeriod,\n uint256 timestamp\n );\n event DepositRevealAheadPeriodUpdated(uint32 depositRevealAheadPeriod);\n\n event RedemptionDustThresholdUpdateStarted(\n uint64 newRedemptionDustThreshold,\n uint256 timestamp\n );\n event RedemptionDustThresholdUpdated(uint64 redemptionDustThreshold);\n\n event RedemptionTreasuryFeeDivisorUpdateStarted(\n uint64 newRedemptionTreasuryFeeDivisor,\n uint256 timestamp\n );\n event RedemptionTreasuryFeeDivisorUpdated(\n uint64 redemptionTreasuryFeeDivisor\n );\n\n event RedemptionTxMaxFeeUpdateStarted(\n uint64 newRedemptionTxMaxFee,\n uint256 timestamp\n );\n event RedemptionTxMaxFeeUpdated(uint64 redemptionTxMaxFee);\n\n event RedemptionTxMaxTotalFeeUpdateStarted(\n uint64 newRedemptionTxMaxTotalFee,\n uint256 timestamp\n );\n event RedemptionTxMaxTotalFeeUpdated(uint64 redemptionTxMaxTotalFee);\n\n event RedemptionTimeoutUpdateStarted(\n uint32 newRedemptionTimeout,\n uint256 timestamp\n );\n event RedemptionTimeoutUpdated(uint32 redemptionTimeout);\n\n event RedemptionTimeoutSlashingAmountUpdateStarted(\n uint96 newRedemptionTimeoutSlashingAmount,\n uint256 timestamp\n );\n event RedemptionTimeoutSlashingAmountUpdated(\n uint96 redemptionTimeoutSlashingAmount\n );\n\n event RedemptionTimeoutNotifierRewardMultiplierUpdateStarted(\n uint32 newRedemptionTimeoutNotifierRewardMultiplier,\n uint256 timestamp\n );\n event RedemptionTimeoutNotifierRewardMultiplierUpdated(\n uint32 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsTxMaxTotalFeeUpdateStarted(\n uint64 newMovingFundsTxMaxTotalFee,\n uint256 timestamp\n );\n event MovingFundsTxMaxTotalFeeUpdated(uint64 movingFundsTxMaxTotalFee);\n\n event MovingFundsDustThresholdUpdateStarted(\n uint64 newMovingFundsDustThreshold,\n uint256 timestamp\n );\n event MovingFundsDustThresholdUpdated(uint64 movingFundsDustThreshold);\n\n event MovingFundsTimeoutResetDelayUpdateStarted(\n uint32 newMovingFundsTimeoutResetDelay,\n uint256 timestamp\n );\n event MovingFundsTimeoutResetDelayUpdated(\n uint32 movingFundsTimeoutResetDelay\n );\n\n event MovingFundsTimeoutUpdateStarted(\n uint32 newMovingFundsTimeout,\n uint256 timestamp\n );\n event MovingFundsTimeoutUpdated(uint32 movingFundsTimeout);\n\n event MovingFundsTimeoutSlashingAmountUpdateStarted(\n uint96 newMovingFundsTimeoutSlashingAmount,\n uint256 timestamp\n );\n event MovingFundsTimeoutSlashingAmountUpdated(\n uint96 movingFundsTimeoutSlashingAmount\n );\n\n event MovingFundsTimeoutNotifierRewardMultiplierUpdateStarted(\n uint32 newMovingFundsTimeoutNotifierRewardMultiplier,\n uint256 timestamp\n );\n event MovingFundsTimeoutNotifierRewardMultiplierUpdated(\n uint32 movingFundsTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsCommitmentGasOffsetUpdateStarted(\n uint16 newMovingFundsCommitmentGasOffset,\n uint256 timestamp\n );\n event MovingFundsCommitmentGasOffsetUpdated(\n uint16 movingFundsCommitmentGasOffset\n );\n\n event MovedFundsSweepTxMaxTotalFeeUpdateStarted(\n uint64 newMovedFundsSweepTxMaxTotalFee,\n uint256 timestamp\n );\n event MovedFundsSweepTxMaxTotalFeeUpdated(\n uint64 movedFundsSweepTxMaxTotalFee\n );\n\n event MovedFundsSweepTimeoutUpdateStarted(\n uint32 newMovedFundsSweepTimeout,\n uint256 timestamp\n );\n event MovedFundsSweepTimeoutUpdated(uint32 movedFundsSweepTimeout);\n\n event MovedFundsSweepTimeoutSlashingAmountUpdateStarted(\n uint96 newMovedFundsSweepTimeoutSlashingAmount,\n uint256 timestamp\n );\n event MovedFundsSweepTimeoutSlashingAmountUpdated(\n uint96 movedFundsSweepTimeoutSlashingAmount\n );\n\n event MovedFundsSweepTimeoutNotifierRewardMultiplierUpdateStarted(\n uint32 newMovedFundsSweepTimeoutNotifierRewardMultiplier,\n uint256 timestamp\n );\n event MovedFundsSweepTimeoutNotifierRewardMultiplierUpdated(\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletCreationPeriodUpdateStarted(\n uint32 newWalletCreationPeriod,\n uint256 timestamp\n );\n event WalletCreationPeriodUpdated(uint32 walletCreationPeriod);\n\n event WalletCreationMinBtcBalanceUpdateStarted(\n uint64 newWalletCreationMinBtcBalance,\n uint256 timestamp\n );\n event WalletCreationMinBtcBalanceUpdated(\n uint64 walletCreationMinBtcBalance\n );\n\n event WalletCreationMaxBtcBalanceUpdateStarted(\n uint64 newWalletCreationMaxBtcBalance,\n uint256 timestamp\n );\n event WalletCreationMaxBtcBalanceUpdated(\n uint64 walletCreationMaxBtcBalance\n );\n\n event WalletClosureMinBtcBalanceUpdateStarted(\n uint64 newWalletClosureMinBtcBalance,\n uint256 timestamp\n );\n event WalletClosureMinBtcBalanceUpdated(uint64 walletClosureMinBtcBalance);\n\n event WalletMaxAgeUpdateStarted(uint32 newWalletMaxAge, uint256 timestamp);\n event WalletMaxAgeUpdated(uint32 walletMaxAge);\n\n event WalletMaxBtcTransferUpdateStarted(\n uint64 newWalletMaxBtcTransfer,\n uint256 timestamp\n );\n event WalletMaxBtcTransferUpdated(uint64 walletMaxBtcTransfer);\n\n event WalletClosingPeriodUpdateStarted(\n uint32 newWalletClosingPeriod,\n uint256 timestamp\n );\n event WalletClosingPeriodUpdated(uint32 walletClosingPeriod);\n\n event FraudChallengeDepositAmountUpdateStarted(\n uint96 newFraudChallengeDepositAmount,\n uint256 timestamp\n );\n event FraudChallengeDepositAmountUpdated(\n uint96 fraudChallengeDepositAmount\n );\n\n event FraudChallengeDefeatTimeoutUpdateStarted(\n uint32 newFraudChallengeDefeatTimeout,\n uint256 timestamp\n );\n event FraudChallengeDefeatTimeoutUpdated(\n uint32 fraudChallengeDefeatTimeout\n );\n\n event FraudSlashingAmountUpdateStarted(\n uint96 newFraudSlashingAmount,\n uint256 timestamp\n );\n event FraudSlashingAmountUpdated(uint96 fraudSlashingAmount);\n\n event FraudNotifierRewardMultiplierUpdateStarted(\n uint32 newFraudNotifierRewardMultiplier,\n uint256 timestamp\n );\n event FraudNotifierRewardMultiplierUpdated(\n uint32 fraudNotifierRewardMultiplier\n );\n\n event TreasuryUpdateStarted(address newTreasury, uint256 timestamp);\n event TreasuryUpdated(address treasury);\n\n /// @notice Reverts if called before the governance delay elapses.\n /// @param changeInitiatedTimestamp Timestamp indicating the beginning\n /// of the change.\n modifier onlyAfterGovernanceDelay(\n uint256 changeInitiatedTimestamp,\n uint256 governanceDelay\n ) {\n /* solhint-disable not-rely-on-time */\n require(changeInitiatedTimestamp > 0, \"Change not initiated\");\n require(\n block.timestamp - changeInitiatedTimestamp >= governanceDelay,\n \"Governance delay has not elapsed\"\n );\n _;\n /* solhint-enable not-rely-on-time */\n }\n\n // --- Deposit\n\n /// @notice Begins the deposit dust threshold amount update process.\n /// @param _newDepositDustThreshold New deposit dust threshold amount.\n function beginDepositDustThresholdUpdate(\n DepositData storage self,\n uint64 _newDepositDustThreshold\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newDepositDustThreshold = _newDepositDustThreshold;\n self.depositDustThresholdChangeInitiated = block.timestamp;\n emit DepositDustThresholdUpdateStarted(\n _newDepositDustThreshold,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the deposit dust threshold amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeDepositDustThresholdUpdate(\n DepositData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.depositDustThresholdChangeInitiated,\n governanceDelay\n )\n {\n emit DepositDustThresholdUpdated(self.newDepositDustThreshold);\n\n self.newDepositDustThreshold = 0;\n self.depositDustThresholdChangeInitiated = 0;\n }\n\n /// @notice Begins the deposit treasury fee divisor amount update process.\n /// @param _newDepositTreasuryFeeDivisor New deposit treasury fee divisor amount.\n function beginDepositTreasuryFeeDivisorUpdate(\n DepositData storage self,\n uint64 _newDepositTreasuryFeeDivisor\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newDepositTreasuryFeeDivisor = _newDepositTreasuryFeeDivisor;\n self.depositTreasuryFeeDivisorChangeInitiated = block.timestamp;\n emit DepositTreasuryFeeDivisorUpdateStarted(\n _newDepositTreasuryFeeDivisor,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the deposit treasury fee divisor amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeDepositTreasuryFeeDivisorUpdate(\n DepositData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.depositTreasuryFeeDivisorChangeInitiated,\n governanceDelay\n )\n {\n emit DepositTreasuryFeeDivisorUpdated(\n self.newDepositTreasuryFeeDivisor\n );\n\n self.newDepositTreasuryFeeDivisor = 0;\n self.depositTreasuryFeeDivisorChangeInitiated = 0;\n }\n\n /// @notice Begins the deposit tx max fee amount update process.\n /// @param _newDepositTxMaxFee New deposit tx max fee amount.\n function beginDepositTxMaxFeeUpdate(\n DepositData storage self,\n uint64 _newDepositTxMaxFee\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newDepositTxMaxFee = _newDepositTxMaxFee;\n self.depositTxMaxFeeChangeInitiated = block.timestamp;\n emit DepositTxMaxFeeUpdateStarted(_newDepositTxMaxFee, block.timestamp);\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the deposit tx max fee amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeDepositTxMaxFeeUpdate(\n DepositData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.depositTxMaxFeeChangeInitiated,\n governanceDelay\n )\n {\n emit DepositTxMaxFeeUpdated(self.newDepositTxMaxFee);\n\n self.newDepositTxMaxFee = 0;\n self.depositTxMaxFeeChangeInitiated = 0;\n }\n\n /// @notice Begins the deposit reveal ahead period update process.\n /// @param _newDepositRevealAheadPeriod New deposit reveal ahead period.\n function beginDepositRevealAheadPeriodUpdate(\n DepositData storage self,\n uint32 _newDepositRevealAheadPeriod\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newDepositRevealAheadPeriod = _newDepositRevealAheadPeriod;\n self.depositRevealAheadPeriodChangeInitiated = block.timestamp;\n emit DepositRevealAheadPeriodUpdateStarted(\n _newDepositRevealAheadPeriod,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the deposit reveal ahead period update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeDepositRevealAheadPeriodUpdate(\n DepositData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.depositRevealAheadPeriodChangeInitiated,\n governanceDelay\n )\n {\n emit DepositRevealAheadPeriodUpdated(self.newDepositRevealAheadPeriod);\n\n self.newDepositRevealAheadPeriod = 0;\n self.depositRevealAheadPeriodChangeInitiated = 0;\n }\n\n // --- Redemption\n\n /// @notice Begins the redemption dust threshold amount update process.\n /// @param _newRedemptionDustThreshold New redemption dust threshold amount.\n function beginRedemptionDustThresholdUpdate(\n RedemptionData storage self,\n uint64 _newRedemptionDustThreshold\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newRedemptionDustThreshold = _newRedemptionDustThreshold;\n self.redemptionDustThresholdChangeInitiated = block.timestamp;\n emit RedemptionDustThresholdUpdateStarted(\n _newRedemptionDustThreshold,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the redemption dust threshold amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeRedemptionDustThresholdUpdate(\n RedemptionData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.redemptionDustThresholdChangeInitiated,\n governanceDelay\n )\n {\n emit RedemptionDustThresholdUpdated(self.newRedemptionDustThreshold);\n\n self.newRedemptionDustThreshold = 0;\n self.redemptionDustThresholdChangeInitiated = 0;\n }\n\n /// @notice Begins the redemption treasury fee divisor amount update process.\n /// @param _newRedemptionTreasuryFeeDivisor New redemption treasury fee divisor\n /// amount.\n function beginRedemptionTreasuryFeeDivisorUpdate(\n RedemptionData storage self,\n uint64 _newRedemptionTreasuryFeeDivisor\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newRedemptionTreasuryFeeDivisor = _newRedemptionTreasuryFeeDivisor;\n self.redemptionTreasuryFeeDivisorChangeInitiated = block.timestamp;\n emit RedemptionTreasuryFeeDivisorUpdateStarted(\n _newRedemptionTreasuryFeeDivisor,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the redemption treasury fee divisor amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeRedemptionTreasuryFeeDivisorUpdate(\n RedemptionData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.redemptionTreasuryFeeDivisorChangeInitiated,\n governanceDelay\n )\n {\n emit RedemptionTreasuryFeeDivisorUpdated(\n self.newRedemptionTreasuryFeeDivisor\n );\n\n self.newRedemptionTreasuryFeeDivisor = 0;\n self.redemptionTreasuryFeeDivisorChangeInitiated = 0;\n }\n\n /// @notice Begins the redemption tx max fee amount update process.\n /// @param _newRedemptionTxMaxFee New redemption tx max fee amount.\n function beginRedemptionTxMaxFeeUpdate(\n RedemptionData storage self,\n uint64 _newRedemptionTxMaxFee\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newRedemptionTxMaxFee = _newRedemptionTxMaxFee;\n self.redemptionTxMaxFeeChangeInitiated = block.timestamp;\n emit RedemptionTxMaxFeeUpdateStarted(\n _newRedemptionTxMaxFee,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the redemption tx max fee amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeRedemptionTxMaxFeeUpdate(\n RedemptionData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.redemptionTxMaxFeeChangeInitiated,\n governanceDelay\n )\n {\n emit RedemptionTxMaxFeeUpdated(self.newRedemptionTxMaxFee);\n\n self.newRedemptionTxMaxFee = 0;\n self.redemptionTxMaxFeeChangeInitiated = 0;\n }\n\n /// @notice Begins the redemption tx max total fee amount update process.\n /// @param _newRedemptionTxMaxTotalFee New redemption tx max total fee amount.\n function beginRedemptionTxMaxTotalFeeUpdate(\n RedemptionData storage self,\n uint64 _newRedemptionTxMaxTotalFee\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newRedemptionTxMaxTotalFee = _newRedemptionTxMaxTotalFee;\n self.redemptionTxMaxTotalFeeChangeInitiated = block.timestamp;\n emit RedemptionTxMaxTotalFeeUpdateStarted(\n _newRedemptionTxMaxTotalFee,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the redemption tx max total fee amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeRedemptionTxMaxTotalFeeUpdate(\n RedemptionData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.redemptionTxMaxTotalFeeChangeInitiated,\n governanceDelay\n )\n {\n emit RedemptionTxMaxTotalFeeUpdated(self.newRedemptionTxMaxTotalFee);\n\n self.newRedemptionTxMaxTotalFee = 0;\n self.redemptionTxMaxTotalFeeChangeInitiated = 0;\n }\n\n /// @notice Begins the redemption timeout amount update process.\n /// @param _newRedemptionTimeout New redemption timeout amount.\n function beginRedemptionTimeoutUpdate(\n RedemptionData storage self,\n uint32 _newRedemptionTimeout\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newRedemptionTimeout = _newRedemptionTimeout;\n self.redemptionTimeoutChangeInitiated = block.timestamp;\n emit RedemptionTimeoutUpdateStarted(\n _newRedemptionTimeout,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the redemption timeout amount update\n /// process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeRedemptionTimeoutUpdate(\n RedemptionData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.redemptionTimeoutChangeInitiated,\n governanceDelay\n )\n {\n emit RedemptionTimeoutUpdated(self.newRedemptionTimeout);\n\n self.newRedemptionTimeout = 0;\n self.redemptionTimeoutChangeInitiated = 0;\n }\n\n /// @notice Begins the redemption timeout slashing amount update process.\n /// @param _newRedemptionTimeoutSlashingAmount New redemption timeout slashing\n /// amount.\n function beginRedemptionTimeoutSlashingAmountUpdate(\n RedemptionData storage self,\n uint96 _newRedemptionTimeoutSlashingAmount\n ) external {\n /* solhint-disable not-rely-on-time */\n self\n .newRedemptionTimeoutSlashingAmount = _newRedemptionTimeoutSlashingAmount;\n self.redemptionTimeoutSlashingAmountChangeInitiated = block.timestamp;\n emit RedemptionTimeoutSlashingAmountUpdateStarted(\n _newRedemptionTimeoutSlashingAmount,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the redemption timeout slashing amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeRedemptionTimeoutSlashingAmountUpdate(\n RedemptionData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.redemptionTimeoutSlashingAmountChangeInitiated,\n governanceDelay\n )\n {\n emit RedemptionTimeoutSlashingAmountUpdated(\n self.newRedemptionTimeoutSlashingAmount\n );\n\n self.newRedemptionTimeoutSlashingAmount = 0;\n self.redemptionTimeoutSlashingAmountChangeInitiated = 0;\n }\n\n /// @notice Begins the redemption timeout notifier reward multiplier amount\n /// update process.\n /// @param _newRedemptionTimeoutNotifierRewardMultiplier New redemption\n /// timeout notifier reward multiplier amount.\n function beginRedemptionTimeoutNotifierRewardMultiplierUpdate(\n RedemptionData storage self,\n uint32 _newRedemptionTimeoutNotifierRewardMultiplier\n ) external {\n /* solhint-disable not-rely-on-time */\n self\n .newRedemptionTimeoutNotifierRewardMultiplier = _newRedemptionTimeoutNotifierRewardMultiplier;\n self.redemptionTimeoutNotifierRewardMultiplierChangeInitiated = block\n .timestamp;\n emit RedemptionTimeoutNotifierRewardMultiplierUpdateStarted(\n _newRedemptionTimeoutNotifierRewardMultiplier,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the redemption timeout notifier reward multiplier amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeRedemptionTimeoutNotifierRewardMultiplierUpdate(\n RedemptionData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.redemptionTimeoutNotifierRewardMultiplierChangeInitiated,\n governanceDelay\n )\n {\n emit RedemptionTimeoutNotifierRewardMultiplierUpdated(\n self.newRedemptionTimeoutNotifierRewardMultiplier\n );\n\n self.newRedemptionTimeoutNotifierRewardMultiplier = 0;\n self.redemptionTimeoutNotifierRewardMultiplierChangeInitiated = 0;\n }\n\n // --- Moving funds\n\n /// @notice Begins the moving funds tx max total fee amount update process.\n /// @param _newMovingFundsTxMaxTotalFee New moving funds tx max total fee amount.\n function beginMovingFundsTxMaxTotalFeeUpdate(\n MovingFundsData storage self,\n uint64 _newMovingFundsTxMaxTotalFee\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newMovingFundsTxMaxTotalFee = _newMovingFundsTxMaxTotalFee;\n self.movingFundsTxMaxTotalFeeChangeInitiated = block.timestamp;\n emit MovingFundsTxMaxTotalFeeUpdateStarted(\n _newMovingFundsTxMaxTotalFee,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moving funds tx max total fee amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovingFundsTxMaxTotalFeeUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movingFundsTxMaxTotalFeeChangeInitiated,\n governanceDelay\n )\n {\n emit MovingFundsTxMaxTotalFeeUpdated(self.newMovingFundsTxMaxTotalFee);\n\n self.newMovingFundsTxMaxTotalFee = 0;\n self.movingFundsTxMaxTotalFeeChangeInitiated = 0;\n }\n\n /// @notice Begins the moving funds dust threshold amount update process.\n /// @param _newMovingFundsDustThreshold New moving funds dust threshold amount.\n function beginMovingFundsDustThresholdUpdate(\n MovingFundsData storage self,\n uint64 _newMovingFundsDustThreshold\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newMovingFundsDustThreshold = _newMovingFundsDustThreshold;\n self.movingFundsDustThresholdChangeInitiated = block.timestamp;\n emit MovingFundsDustThresholdUpdateStarted(\n _newMovingFundsDustThreshold,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moving funds dust threshold amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovingFundsDustThresholdUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movingFundsDustThresholdChangeInitiated,\n governanceDelay\n )\n {\n emit MovingFundsDustThresholdUpdated(self.newMovingFundsDustThreshold);\n\n self.newMovingFundsDustThreshold = 0;\n self.movingFundsDustThresholdChangeInitiated = 0;\n }\n\n /// @notice Begins the moving funds timeout reset delay amount update process.\n /// @param _newMovingFundsTimeoutResetDelay New moving funds timeout reset\n /// delay amount.\n function beginMovingFundsTimeoutResetDelayUpdate(\n MovingFundsData storage self,\n uint32 _newMovingFundsTimeoutResetDelay\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newMovingFundsTimeoutResetDelay = _newMovingFundsTimeoutResetDelay;\n self.movingFundsTimeoutResetDelayChangeInitiated = block.timestamp;\n emit MovingFundsTimeoutResetDelayUpdateStarted(\n _newMovingFundsTimeoutResetDelay,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moving funds timeout reset delay amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovingFundsTimeoutResetDelayUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movingFundsTimeoutResetDelayChangeInitiated,\n governanceDelay\n )\n {\n emit MovingFundsTimeoutResetDelayUpdated(\n self.newMovingFundsTimeoutResetDelay\n );\n\n self.newMovingFundsTimeoutResetDelay = 0;\n self.movingFundsTimeoutResetDelayChangeInitiated = 0;\n }\n\n /// @notice Begins the moving funds timeout amount update process.\n /// @param _newMovingFundsTimeout New moving funds timeout amount.\n function beginMovingFundsTimeoutUpdate(\n MovingFundsData storage self,\n uint32 _newMovingFundsTimeout\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newMovingFundsTimeout = _newMovingFundsTimeout;\n self.movingFundsTimeoutChangeInitiated = block.timestamp;\n emit MovingFundsTimeoutUpdateStarted(\n _newMovingFundsTimeout,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moving funds timeout amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovingFundsTimeoutUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movingFundsTimeoutChangeInitiated,\n governanceDelay\n )\n {\n emit MovingFundsTimeoutUpdated(self.newMovingFundsTimeout);\n\n self.newMovingFundsTimeout = 0;\n self.movingFundsTimeoutChangeInitiated = 0;\n }\n\n /// @notice Begins the moving funds timeout slashing amount update process.\n /// @param _newMovingFundsTimeoutSlashingAmount New moving funds timeout slashing amount.\n function beginMovingFundsTimeoutSlashingAmountUpdate(\n MovingFundsData storage self,\n uint96 _newMovingFundsTimeoutSlashingAmount\n ) external {\n /* solhint-disable not-rely-on-time */\n self\n .newMovingFundsTimeoutSlashingAmount = _newMovingFundsTimeoutSlashingAmount;\n self.movingFundsTimeoutSlashingAmountChangeInitiated = block.timestamp;\n emit MovingFundsTimeoutSlashingAmountUpdateStarted(\n _newMovingFundsTimeoutSlashingAmount,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moving funds timeout slashing amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovingFundsTimeoutSlashingAmountUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movingFundsTimeoutSlashingAmountChangeInitiated,\n governanceDelay\n )\n {\n emit MovingFundsTimeoutSlashingAmountUpdated(\n self.newMovingFundsTimeoutSlashingAmount\n );\n\n self.newMovingFundsTimeoutSlashingAmount = 0;\n self.movingFundsTimeoutSlashingAmountChangeInitiated = 0;\n }\n\n /// @notice Begins the moving funds timeout notifier reward multiplier amount\n /// update process.\n /// @param _newMovingFundsTimeoutNotifierRewardMultiplier New moving funds\n /// timeout notifier reward multiplier amount.\n function beginMovingFundsTimeoutNotifierRewardMultiplierUpdate(\n MovingFundsData storage self,\n uint32 _newMovingFundsTimeoutNotifierRewardMultiplier\n ) external {\n /* solhint-disable not-rely-on-time */\n self\n .newMovingFundsTimeoutNotifierRewardMultiplier = _newMovingFundsTimeoutNotifierRewardMultiplier;\n self.movingFundsTimeoutNotifierRewardMultiplierChangeInitiated = block\n .timestamp;\n emit MovingFundsTimeoutNotifierRewardMultiplierUpdateStarted(\n _newMovingFundsTimeoutNotifierRewardMultiplier,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moving funds timeout notifier reward multiplier\n /// amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovingFundsTimeoutNotifierRewardMultiplierUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movingFundsTimeoutNotifierRewardMultiplierChangeInitiated,\n governanceDelay\n )\n {\n emit MovingFundsTimeoutNotifierRewardMultiplierUpdated(\n self.newMovingFundsTimeoutNotifierRewardMultiplier\n );\n\n self.newMovingFundsTimeoutNotifierRewardMultiplier = 0;\n self.movingFundsTimeoutNotifierRewardMultiplierChangeInitiated = 0;\n }\n\n /// @notice Begins the moving funds commitment gas offset update process.\n /// @param _newMovingFundsCommitmentGasOffset New moving funds commitment\n /// gas offset.\n function beginMovingFundsCommitmentGasOffsetUpdate(\n MovingFundsData storage self,\n uint16 _newMovingFundsCommitmentGasOffset\n ) external {\n /* solhint-disable not-rely-on-time */\n self\n .newMovingFundsCommitmentGasOffset = _newMovingFundsCommitmentGasOffset;\n self.movingFundsCommitmentGasOffsetChangeInitiated = block.timestamp;\n emit MovingFundsCommitmentGasOffsetUpdateStarted(\n _newMovingFundsCommitmentGasOffset,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moving funds commitment gas offset update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovingFundsCommitmentGasOffsetUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movingFundsCommitmentGasOffsetChangeInitiated,\n governanceDelay\n )\n {\n emit MovingFundsCommitmentGasOffsetUpdated(\n self.newMovingFundsCommitmentGasOffset\n );\n\n self.newMovingFundsCommitmentGasOffset = 0;\n self.movingFundsCommitmentGasOffsetChangeInitiated = 0;\n }\n\n /// @notice Begins the moved funds sweep tx max total fee amount update process.\n /// @param _newMovedFundsSweepTxMaxTotalFee New moved funds sweep tx max total\n /// fee amount.\n function beginMovedFundsSweepTxMaxTotalFeeUpdate(\n MovingFundsData storage self,\n uint64 _newMovedFundsSweepTxMaxTotalFee\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newMovedFundsSweepTxMaxTotalFee = _newMovedFundsSweepTxMaxTotalFee;\n self.movedFundsSweepTxMaxTotalFeeChangeInitiated = block.timestamp;\n emit MovedFundsSweepTxMaxTotalFeeUpdateStarted(\n _newMovedFundsSweepTxMaxTotalFee,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moved funds sweep tx max total fee amount update\n /// process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovedFundsSweepTxMaxTotalFeeUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movedFundsSweepTxMaxTotalFeeChangeInitiated,\n governanceDelay\n )\n {\n emit MovedFundsSweepTxMaxTotalFeeUpdated(\n self.newMovedFundsSweepTxMaxTotalFee\n );\n\n self.newMovedFundsSweepTxMaxTotalFee = 0;\n self.movedFundsSweepTxMaxTotalFeeChangeInitiated = 0;\n }\n\n /// @notice Begins the moved funds sweep timeout amount update process.\n /// @param _newMovedFundsSweepTimeout New moved funds sweep timeout amount.\n function beginMovedFundsSweepTimeoutUpdate(\n MovingFundsData storage self,\n uint32 _newMovedFundsSweepTimeout\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newMovedFundsSweepTimeout = _newMovedFundsSweepTimeout;\n self.movedFundsSweepTimeoutChangeInitiated = block.timestamp;\n emit MovedFundsSweepTimeoutUpdateStarted(\n _newMovedFundsSweepTimeout,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moved funds sweep timeout amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovedFundsSweepTimeoutUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movedFundsSweepTimeoutChangeInitiated,\n governanceDelay\n )\n {\n emit MovedFundsSweepTimeoutUpdated(self.newMovedFundsSweepTimeout);\n\n self.newMovedFundsSweepTimeout = 0;\n self.movedFundsSweepTimeoutChangeInitiated = 0;\n }\n\n /// @notice Begins the moved funds sweep timeout slashing amount update\n /// process.\n /// @param _newMovedFundsSweepTimeoutSlashingAmount New moved funds sweep\n /// timeout slashing amount.\n function beginMovedFundsSweepTimeoutSlashingAmountUpdate(\n MovingFundsData storage self,\n uint96 _newMovedFundsSweepTimeoutSlashingAmount\n ) external {\n /* solhint-disable not-rely-on-time */\n self\n .newMovedFundsSweepTimeoutSlashingAmount = _newMovedFundsSweepTimeoutSlashingAmount;\n self.movedFundsSweepTimeoutSlashingAmountChangeInitiated = block\n .timestamp;\n emit MovedFundsSweepTimeoutSlashingAmountUpdateStarted(\n _newMovedFundsSweepTimeoutSlashingAmount,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moved funds sweep timeout slashing amount\n /// update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovedFundsSweepTimeoutSlashingAmountUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movedFundsSweepTimeoutSlashingAmountChangeInitiated,\n governanceDelay\n )\n {\n emit MovedFundsSweepTimeoutSlashingAmountUpdated(\n self.newMovedFundsSweepTimeoutSlashingAmount\n );\n\n self.newMovedFundsSweepTimeoutSlashingAmount = 0;\n self.movedFundsSweepTimeoutSlashingAmountChangeInitiated = 0;\n }\n\n /// @notice Begins the moved funds sweep timeout notifier reward multiplier\n /// amount update process.\n /// @param _newMovedFundsSweepTimeoutNotifierRewardMultiplier New moved funds\n /// sweep timeout notifier reward multiplier amount.\n function beginMovedFundsSweepTimeoutNotifierRewardMultiplierUpdate(\n MovingFundsData storage self,\n uint32 _newMovedFundsSweepTimeoutNotifierRewardMultiplier\n ) external {\n /* solhint-disable not-rely-on-time */\n self\n .newMovedFundsSweepTimeoutNotifierRewardMultiplier = _newMovedFundsSweepTimeoutNotifierRewardMultiplier;\n self\n .movedFundsSweepTimeoutNotifierRewardMultiplierChangeInitiated = block\n .timestamp;\n emit MovedFundsSweepTimeoutNotifierRewardMultiplierUpdateStarted(\n _newMovedFundsSweepTimeoutNotifierRewardMultiplier,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the moved funds sweep timeout notifier reward multiplier\n /// amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeMovedFundsSweepTimeoutNotifierRewardMultiplierUpdate(\n MovingFundsData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.movedFundsSweepTimeoutNotifierRewardMultiplierChangeInitiated,\n governanceDelay\n )\n {\n emit MovedFundsSweepTimeoutNotifierRewardMultiplierUpdated(\n self.newMovedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n self.newMovedFundsSweepTimeoutNotifierRewardMultiplier = 0;\n self.movedFundsSweepTimeoutNotifierRewardMultiplierChangeInitiated = 0;\n }\n\n // --- Wallet params\n\n /// @notice Begins the wallet creation period amount update process.\n /// @param _newWalletCreationPeriod New wallet creation period amount.\n function beginWalletCreationPeriodUpdate(\n WalletData storage self,\n uint32 _newWalletCreationPeriod\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newWalletCreationPeriod = _newWalletCreationPeriod;\n self.walletCreationPeriodChangeInitiated = block.timestamp;\n emit WalletCreationPeriodUpdateStarted(\n _newWalletCreationPeriod,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the wallet creation period amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeWalletCreationPeriodUpdate(\n WalletData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.walletCreationPeriodChangeInitiated,\n governanceDelay\n )\n {\n emit WalletCreationPeriodUpdated(self.newWalletCreationPeriod);\n\n self.newWalletCreationPeriod = 0;\n self.walletCreationPeriodChangeInitiated = 0;\n }\n\n /// @notice Begins the wallet creation min btc balance amount update process.\n /// @param _newWalletCreationMinBtcBalance New wallet creation min btc balance\n /// amount.\n function beginWalletCreationMinBtcBalanceUpdate(\n WalletData storage self,\n uint64 _newWalletCreationMinBtcBalance\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newWalletCreationMinBtcBalance = _newWalletCreationMinBtcBalance;\n self.walletCreationMinBtcBalanceChangeInitiated = block.timestamp;\n emit WalletCreationMinBtcBalanceUpdateStarted(\n _newWalletCreationMinBtcBalance,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the wallet creation min btc balance amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeWalletCreationMinBtcBalanceUpdate(\n WalletData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.walletCreationMinBtcBalanceChangeInitiated,\n governanceDelay\n )\n {\n emit WalletCreationMinBtcBalanceUpdated(\n self.newWalletCreationMinBtcBalance\n );\n\n self.newWalletCreationMinBtcBalance = 0;\n self.walletCreationMinBtcBalanceChangeInitiated = 0;\n }\n\n /// @notice Begins the wallet creation max btc balance amount update process.\n /// @param _newWalletCreationMaxBtcBalance New wallet creation max btc balance\n /// amount.\n function beginWalletCreationMaxBtcBalanceUpdate(\n WalletData storage self,\n uint64 _newWalletCreationMaxBtcBalance\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newWalletCreationMaxBtcBalance = _newWalletCreationMaxBtcBalance;\n self.walletCreationMaxBtcBalanceChangeInitiated = block.timestamp;\n emit WalletCreationMaxBtcBalanceUpdateStarted(\n _newWalletCreationMaxBtcBalance,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the wallet creation max btc balance amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeWalletCreationMaxBtcBalanceUpdate(\n WalletData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.walletCreationMaxBtcBalanceChangeInitiated,\n governanceDelay\n )\n {\n emit WalletCreationMaxBtcBalanceUpdated(\n self.newWalletCreationMaxBtcBalance\n );\n\n self.newWalletCreationMaxBtcBalance = 0;\n self.walletCreationMaxBtcBalanceChangeInitiated = 0;\n }\n\n /// @notice Begins the wallet closure min btc balance amount update process.\n /// @param _newWalletClosureMinBtcBalance New wallet closure min btc balance amount.\n function beginWalletClosureMinBtcBalanceUpdate(\n WalletData storage self,\n uint64 _newWalletClosureMinBtcBalance\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newWalletClosureMinBtcBalance = _newWalletClosureMinBtcBalance;\n self.walletClosureMinBtcBalanceChangeInitiated = block.timestamp;\n emit WalletClosureMinBtcBalanceUpdateStarted(\n _newWalletClosureMinBtcBalance,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the wallet closure min btc balance amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeWalletClosureMinBtcBalanceUpdate(\n WalletData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.walletClosureMinBtcBalanceChangeInitiated,\n governanceDelay\n )\n {\n emit WalletClosureMinBtcBalanceUpdated(\n self.newWalletClosureMinBtcBalance\n );\n\n self.newWalletClosureMinBtcBalance = 0;\n self.walletClosureMinBtcBalanceChangeInitiated = 0;\n }\n\n /// @notice Begins the wallet max age amount update process.\n /// @param _newWalletMaxAge New wallet max age amount.\n function beginWalletMaxAgeUpdate(\n WalletData storage self,\n uint32 _newWalletMaxAge\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newWalletMaxAge = _newWalletMaxAge;\n self.walletMaxAgeChangeInitiated = block.timestamp;\n emit WalletMaxAgeUpdateStarted(_newWalletMaxAge, block.timestamp);\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the wallet max age amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeWalletMaxAgeUpdate(\n WalletData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.walletMaxAgeChangeInitiated,\n governanceDelay\n )\n {\n emit WalletMaxAgeUpdated(self.newWalletMaxAge);\n\n self.newWalletMaxAge = 0;\n self.walletMaxAgeChangeInitiated = 0;\n }\n\n /// @notice Begins the wallet max btc transfer amount update process.\n /// @param _newWalletMaxBtcTransfer New wallet max btc transfer amount.\n function beginWalletMaxBtcTransferUpdate(\n WalletData storage self,\n uint64 _newWalletMaxBtcTransfer\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newWalletMaxBtcTransfer = _newWalletMaxBtcTransfer;\n self.walletMaxBtcTransferChangeInitiated = block.timestamp;\n emit WalletMaxBtcTransferUpdateStarted(\n _newWalletMaxBtcTransfer,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the wallet max btc transfer amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeWalletMaxBtcTransferUpdate(\n WalletData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.walletMaxBtcTransferChangeInitiated,\n governanceDelay\n )\n {\n emit WalletMaxBtcTransferUpdated(self.newWalletMaxBtcTransfer);\n\n self.newWalletMaxBtcTransfer = 0;\n self.walletMaxBtcTransferChangeInitiated = 0;\n }\n\n /// @notice Begins the wallet closing period amount update process.\n /// @param _newWalletClosingPeriod New wallet closing period amount.\n function beginWalletClosingPeriodUpdate(\n WalletData storage self,\n uint32 _newWalletClosingPeriod\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newWalletClosingPeriod = _newWalletClosingPeriod;\n self.walletClosingPeriodChangeInitiated = block.timestamp;\n emit WalletClosingPeriodUpdateStarted(\n _newWalletClosingPeriod,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the wallet closing period amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeWalletClosingPeriodUpdate(\n WalletData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.walletClosingPeriodChangeInitiated,\n governanceDelay\n )\n {\n emit WalletClosingPeriodUpdated(self.newWalletClosingPeriod);\n\n self.newWalletClosingPeriod = 0;\n self.walletClosingPeriodChangeInitiated = 0;\n }\n\n // --- Fraud\n\n /// @notice Begins the fraud challenge deposit amount update process.\n /// @param _newFraudChallengeDepositAmount New fraud challenge deposit amount.\n function beginFraudChallengeDepositAmountUpdate(\n FraudData storage self,\n uint96 _newFraudChallengeDepositAmount\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newFraudChallengeDepositAmount = _newFraudChallengeDepositAmount;\n self.fraudChallengeDepositAmountChangeInitiated = block.timestamp;\n emit FraudChallengeDepositAmountUpdateStarted(\n _newFraudChallengeDepositAmount,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the fraud challenge deposit amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeFraudChallengeDepositAmountUpdate(\n FraudData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.fraudChallengeDepositAmountChangeInitiated,\n governanceDelay\n )\n {\n emit FraudChallengeDepositAmountUpdated(\n self.newFraudChallengeDepositAmount\n );\n\n self.newFraudChallengeDepositAmount = 0;\n self.fraudChallengeDepositAmountChangeInitiated = 0;\n }\n\n /// @notice Begins the fraud challenge defeat timeout amount update process.\n /// @param _newFraudChallengeDefeatTimeout New fraud challenge defeat timeout\n /// amount.\n function beginFraudChallengeDefeatTimeoutUpdate(\n FraudData storage self,\n uint32 _newFraudChallengeDefeatTimeout\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newFraudChallengeDefeatTimeout = _newFraudChallengeDefeatTimeout;\n self.fraudChallengeDefeatTimeoutChangeInitiated = block.timestamp;\n emit FraudChallengeDefeatTimeoutUpdateStarted(\n _newFraudChallengeDefeatTimeout,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the fraud challenge defeat timeout amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeFraudChallengeDefeatTimeoutUpdate(\n FraudData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.fraudChallengeDefeatTimeoutChangeInitiated,\n governanceDelay\n )\n {\n emit FraudChallengeDefeatTimeoutUpdated(\n self.newFraudChallengeDefeatTimeout\n );\n\n self.newFraudChallengeDefeatTimeout = 0;\n self.fraudChallengeDefeatTimeoutChangeInitiated = 0;\n }\n\n /// @notice Begins the fraud slashing amount update process.\n /// @param _newFraudSlashingAmount New fraud slashing amount.\n function beginFraudSlashingAmountUpdate(\n FraudData storage self,\n uint96 _newFraudSlashingAmount\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newFraudSlashingAmount = _newFraudSlashingAmount;\n self.fraudSlashingAmountChangeInitiated = block.timestamp;\n emit FraudSlashingAmountUpdateStarted(\n _newFraudSlashingAmount,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the fraud slashing amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeFraudSlashingAmountUpdate(\n FraudData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.fraudSlashingAmountChangeInitiated,\n governanceDelay\n )\n {\n emit FraudSlashingAmountUpdated(self.newFraudSlashingAmount);\n\n self.newFraudSlashingAmount = 0;\n self.fraudSlashingAmountChangeInitiated = 0;\n }\n\n /// @notice Begins the fraud notifier reward multiplier amount update process.\n /// @param _newFraudNotifierRewardMultiplier New fraud notifier reward multiplier\n /// amount.\n function beginFraudNotifierRewardMultiplierUpdate(\n FraudData storage self,\n uint32 _newFraudNotifierRewardMultiplier\n ) external {\n /* solhint-disable not-rely-on-time */\n self\n .newFraudNotifierRewardMultiplier = _newFraudNotifierRewardMultiplier;\n self.fraudNotifierRewardMultiplierChangeInitiated = block.timestamp;\n emit FraudNotifierRewardMultiplierUpdateStarted(\n _newFraudNotifierRewardMultiplier,\n block.timestamp\n );\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the fraud notifier reward multiplier amount update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeFraudNotifierRewardMultiplierUpdate(\n FraudData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(\n self.fraudNotifierRewardMultiplierChangeInitiated,\n governanceDelay\n )\n {\n emit FraudNotifierRewardMultiplierUpdated(\n self.newFraudNotifierRewardMultiplier\n );\n\n self.newFraudNotifierRewardMultiplier = 0;\n self.fraudNotifierRewardMultiplierChangeInitiated = 0;\n }\n\n /// @notice Begins the treasury address update process.\n /// @dev It does not perform any parameter validation.\n /// @param _newTreasury New treasury address.\n function beginTreasuryUpdate(\n TreasuryData storage self,\n address _newTreasury\n ) external {\n /* solhint-disable not-rely-on-time */\n self.newTreasury = _newTreasury;\n self.treasuryChangeInitiated = block.timestamp;\n emit TreasuryUpdateStarted(_newTreasury, block.timestamp);\n /* solhint-enable not-rely-on-time */\n }\n\n /// @notice Finalizes the treasury address update process.\n /// @dev Can be called after the governance delay elapses.\n function finalizeTreasuryUpdate(\n TreasuryData storage self,\n uint256 governanceDelay\n )\n external\n onlyAfterGovernanceDelay(self.treasuryChangeInitiated, governanceDelay)\n {\n emit TreasuryUpdated(self.newTreasury);\n\n self.newTreasury = address(0);\n self.treasuryChangeInitiated = 0;\n }\n}\n"
|
|
135
132
|
},
|
|
136
133
|
"contracts/bridge/BridgeState.sol": {
|
|
137
|
-
"content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity 0.8.17;\n\nimport {IWalletRegistry as EcdsaWalletRegistry} from \"@keep-network/ecdsa/contracts/api/IWalletRegistry.sol\";\nimport \"@keep-network/random-beacon/contracts/ReimbursementPool.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./Deposit.sol\";\nimport \"./Redemption.sol\";\nimport \"./Fraud.sol\";\nimport \"./Wallets.sol\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/Bank.sol\";\n\nlibrary BridgeState {\n struct Storage {\n // Address of the Bank the Bridge belongs to.\n Bank bank;\n // Bitcoin relay providing the current Bitcoin network difficulty.\n IRelay relay;\n // The number of confirmations on the Bitcoin chain required to\n // successfully evaluate an SPV proof.\n uint96 txProofDifficultyFactor;\n // ECDSA Wallet Registry contract handle.\n EcdsaWalletRegistry ecdsaWalletRegistry;\n // Reimbursement Pool contract handle.\n ReimbursementPool reimbursementPool;\n // Address where the deposit and redemption treasury fees will be sent\n // to. Treasury takes part in the operators rewarding process.\n address treasury;\n // Move depositDustThreshold to the next storage slot for a more\n // efficient variable layout in the storage.\n // slither-disable-next-line unused-state\n bytes32 __treasuryAlignmentGap;\n // The minimal amount that can be requested to deposit.\n // Value of this parameter must take into account the value of\n // `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters in order\n // to make requests that can incur the treasury and transaction fee and\n // still satisfy the depositor.\n uint64 depositDustThreshold;\n // Divisor used to compute the treasury fee taken from each deposit and\n // transferred to the treasury upon sweep proof submission. That fee is\n // computed as follows:\n // `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each deposit,\n // the `depositTreasuryFeeDivisor` should be set to `50` because\n // `1/50 = 0.02 = 2%`.\n uint64 depositTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by each\n // swept deposit being part of the given sweep transaction. If the\n // maximum BTC transaction fee is exceeded, such transaction is\n // considered a fraud.\n //\n // This is a per-deposit input max fee for the sweep transaction.\n uint64 depositTxMaxFee;\n // Defines the length of the period that must be preserved between\n // the deposit reveal time and the deposit refund locktime. For example,\n // if the deposit become refundable on August 1st, and the ahead period\n // is 7 days, the latest moment for deposit reveal is July 25th.\n // Value in seconds. The value equal to zero disables the validation\n // of this parameter.\n uint32 depositRevealAheadPeriod;\n // Move movingFundsTxMaxTotalFee to the next storage slot for a more\n // efficient variable layout in the storage.\n // slither-disable-next-line unused-state\n bytes32 __depositAlignmentGap;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moving funds transaction.\n //\n // This is a TOTAL max fee for the moving funds transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // is per single redemption. `movingFundsTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movingFundsTxMaxTotalFee;\n // The minimal satoshi amount that makes sense to be transferred during\n // the moving funds process. Moving funds wallets having their BTC\n // balance below that value can begin closing immediately as\n // transferring such a low value may not be possible due to\n // BTC network fees. The value of this parameter must always be lower\n // than `redemptionDustThreshold` in order to prevent redemption requests\n // with values lower or equal to `movingFundsDustThreshold`.\n uint64 movingFundsDustThreshold;\n // Time after which the moving funds timeout can be reset in case the\n // target wallet commitment cannot be submitted due to a lack of live\n // wallets in the system. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state or from the moment the timeout was reset the last time.\n // Value in seconds. This value should be lower than the value\n // of the `movingFundsTimeout`.\n uint32 movingFundsTimeoutResetDelay;\n // Time after which the moving funds process can be reported as\n // timed out. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state. Value in seconds.\n uint32 movingFundsTimeout;\n // The amount of stake slashed from each member of a wallet for a moving\n // funds timeout.\n uint96 movingFundsTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moving funds timeout receives. The value is in the\n // range [0, 100].\n uint32 movingFundsTimeoutNotifierRewardMultiplier;\n // The gas offset used for the target wallet commitment transaction cost\n // reimbursement.\n uint16 movingFundsCommitmentGasOffset;\n // Move movedFundsSweepTxMaxTotalFee to the next storage slot for a more\n // efficient variable layout in the storage.\n // slither-disable-next-line unused-state\n bytes32 __movingFundsAlignmentGap;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moved funds sweep transaction.\n //\n // This is a TOTAL max fee for the moved funds sweep transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // is per single redemption. `movedFundsSweepTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movedFundsSweepTxMaxTotalFee;\n // Time after which the moved funds sweep process can be reported as\n // timed out. It is counted from the moment when the recipient wallet\n // was requested to sweep the received funds. Value in seconds.\n uint32 movedFundsSweepTimeout;\n // The amount of stake slashed from each member of a wallet for a moved\n // funds sweep timeout.\n uint96 movedFundsSweepTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moved funds sweep timeout receives. The value is\n // in the range [0, 100].\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier;\n // The minimal amount that can be requested for redemption.\n // Value of this parameter must take into account the value of\n // `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n // parameters in order to make requests that can incur the\n // treasury and transaction fee and still satisfy the redeemer.\n // Additionally, the value of this parameter must always be greater\n // than `movingFundsDustThreshold` in order to prevent redemption\n // requests with values lower or equal to `movingFundsDustThreshold`.\n uint64 redemptionDustThreshold;\n // Divisor used to compute the treasury fee taken from each\n // redemption request and transferred to the treasury upon\n // successful request finalization. That fee is computed as follows:\n // `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each\n // redemption request, the `redemptionTreasuryFeeDivisor` should\n // be set to `50` because `1/50 = 0.02 = 2%`.\n uint64 redemptionTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by\n // each redemption request being part of the given redemption\n // transaction. If the maximum BTC transaction fee is exceeded, such\n // transaction is considered a fraud.\n //\n // This is a per-redemption output max fee for the redemption\n // transaction.\n uint64 redemptionTxMaxFee;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single redemption transaction.\n //\n // This is a TOTAL max fee for the redemption transaction. Note\n // that the `redemptionTxMaxFee` is per single redemption.\n // `redemptionTxMaxTotalFee` is a total fee for the entire transaction.\n uint64 redemptionTxMaxTotalFee;\n // Move redemptionTimeout to the next storage slot for a more efficient\n // variable layout in the storage.\n // slither-disable-next-line unused-state\n bytes32 __redemptionAlignmentGap;\n // Time after which the redemption request can be reported as\n // timed out. It is counted from the moment when the redemption\n // request was created via `requestRedemption` call. Reported\n // timed out requests are cancelled and locked TBTC is returned\n // to the redeemer in full amount.\n uint32 redemptionTimeout;\n // The amount of stake slashed from each member of a wallet for a\n // redemption timeout.\n uint96 redemptionTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a redemption timeout receives. The value is in the\n // range [0, 100].\n uint32 redemptionTimeoutNotifierRewardMultiplier;\n // The amount of ETH in wei the party challenging the wallet for fraud\n // needs to deposit.\n uint96 fraudChallengeDepositAmount;\n // The amount of time the wallet has to defeat a fraud challenge.\n uint32 fraudChallengeDefeatTimeout;\n // The amount of stake slashed from each member of a wallet for a fraud.\n uint96 fraudSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a fraud receives. The value is in the range [0, 100].\n uint32 fraudNotifierRewardMultiplier;\n // Determines how frequently a new wallet creation can be requested.\n // Value in seconds.\n uint32 walletCreationPeriod;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet creation. Specifically, we allow for the creation of a new\n // wallet if the active wallet is old enough and their amount of BTC\n // is greater than or equal this threshold.\n uint64 walletCreationMinBtcBalance;\n // The maximum BTC threshold in satoshi that is used to decide about\n // wallet creation. Specifically, we allow for the creation of a new\n // wallet if the active wallet's amount of BTC is greater than or equal\n // this threshold, regardless of the active wallet's age.\n uint64 walletCreationMaxBtcBalance;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet closing. Specifically, we allow for the closure of the given\n // wallet if their amount of BTC is lesser than this threshold,\n // regardless of the wallet's age.\n uint64 walletClosureMinBtcBalance;\n // The maximum age of a wallet in seconds, after which the wallet\n // moving funds process can be requested.\n uint32 walletMaxAge;\n // 20-byte wallet public key hash being reference to the currently\n // active wallet. Can be unset to the zero value under certain\n // circumstances.\n bytes20 activeWalletPubKeyHash;\n // The current number of wallets in the Live state.\n uint32 liveWalletsCount;\n // The maximum BTC amount in satoshi than can be transferred to a single\n // target wallet during the moving funds process.\n uint64 walletMaxBtcTransfer;\n // Determines the length of the wallet closing period, i.e. the period\n // when the wallet remains in the Closing state and can be subject\n // of deposit fraud challenges. This value is in seconds and should be\n // greater than the deposit refund time plus some time margin.\n uint32 walletClosingPeriod;\n // Collection of all revealed deposits indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`.\n // The `fundingTxHash` is `bytes32` (ordered as in Bitcoin internally)\n // and `fundingOutputIndex` an `uint32`. This mapping may contain valid\n // and invalid deposits and the wallet is responsible for validating\n // them before attempting to execute a sweep.\n mapping(uint256 => Deposit.DepositRequest) deposits;\n // Indicates if the vault with the given address is trusted.\n // Depositors can route their revealed deposits only to trusted vaults\n // and have trusted vaults notified about new deposits as soon as these\n // deposits get swept. Vaults not trusted by the Bridge can still be\n // used by Bank balance owners on their own responsibility - anyone can\n // approve their Bank balance to any address.\n mapping(address => bool) isVaultTrusted;\n // Indicates if the address is a trusted SPV maintainer.\n // The SPV proof does not check whether the transaction is a part of the\n // Bitcoin mainnet, it only checks whether the transaction has been\n // mined performing the required amount of work as on Bitcoin mainnet.\n // The possibility of submitting SPV proofs is limited to trusted SPV\n // maintainers. The system expects transaction confirmations with the\n // required work accumulated, so trusted SPV maintainers can not prove\n // the transaction without providing the required Bitcoin proof of work.\n // Trusted maintainers address the issue of an economic game between\n // tBTC and Bitcoin mainnet where large Bitcoin mining pools can decide\n // to use their hash power to mine fake Bitcoin blocks to prove them in\n // tBTC instead of receiving Bitcoin miner rewards.\n mapping(address => bool) isSpvMaintainer;\n // Collection of all moved funds sweep requests indexed by\n // `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n // The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n // internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n // is actually an UTXO representing the moved funds and is supposed\n // to be swept with the current main UTXO of the recipient wallet.\n mapping(uint256 => MovingFunds.MovedFundsSweepRequest) movedFundsSweepRequests;\n // Collection of all pending redemption requests indexed by\n // redemption key built as\n // `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.\n // The `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is a Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n // redeemed BTC as requested by the redeemer. Requests are added\n // to this mapping by the `requestRedemption` method (duplicates\n // not allowed) and are removed by one of the following methods:\n // - `submitRedemptionProof` in case the request was handled\n // successfully,\n // - `notifyRedemptionTimeout` in case the request was reported\n // to be timed out.\n mapping(uint256 => Redemption.RedemptionRequest) pendingRedemptions;\n // Collection of all timed out redemptions requests indexed by\n // redemption key built as\n // `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.\n // The `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is the Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n // out request.\n // Only one method can add to this mapping:\n // - `notifyRedemptionTimeout` which puts the redemption key to this\n // mapping based on a timed out request stored previously in\n // `pendingRedemptions` mapping.\n // Only one method can remove entries from this mapping:\n // - `submitRedemptionProof` in case the timed out redemption request\n // was a part of the proven transaction.\n mapping(uint256 => Redemption.RedemptionRequest) timedOutRedemptions;\n // Collection of all submitted fraud challenges indexed by challenge\n // key built as `keccak256(walletPublicKey|sighash)`.\n mapping(uint256 => Fraud.FraudChallenge) fraudChallenges;\n // Collection of main UTXOs that are honestly spent indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`. The `fundingTxHash`\n // is `bytes32` (ordered as in Bitcoin internally) and\n // `fundingOutputIndex` an `uint32`. A main UTXO is considered honestly\n // spent if it was used as an input of a transaction that have been\n // proven in the Bridge.\n mapping(uint256 => bool) spentMainUTXOs;\n // Maps the 20-byte wallet public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) to the basic wallet\n // information like state and pending redemptions value.\n mapping(bytes20 => Wallets.Wallet) registeredWallets;\n // Reserved storage space in case we need to add more variables.\n // The convention from OpenZeppelin suggests the storage space should\n // add up to 50 slots. Here we want to have more slots as there are\n // planned upgrades of the Bridge contract. If more entires are added to\n // the struct in the upcoming versions we need to reduce the array size.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[50] __gap;\n }\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint96 fraudChallengeDepositAmount,\n uint32 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint32 fraudNotifierRewardMultiplier\n );\n\n event TreasuryUpdated(address treasury);\n\n /// @notice Updates parameters of deposits.\n /// @param _depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor.\n /// @param _depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @param _depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @param _depositRevealAheadPeriod New value of the deposit reveal ahead\n /// period parameter in seconds. It defines the length of the period\n /// that must be preserved between the deposit reveal time and the\n /// deposit refund locktime.\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero,\n /// - Deposit dust threshold must be greater than deposit TX max fee,\n /// - Deposit transaction max fee must be greater than zero.\n function updateDepositParameters(\n Storage storage self,\n uint64 _depositDustThreshold,\n uint64 _depositTreasuryFeeDivisor,\n uint64 _depositTxMaxFee,\n uint32 _depositRevealAheadPeriod\n ) internal {\n require(\n _depositDustThreshold > 0,\n \"Deposit dust threshold must be greater than zero\"\n );\n\n require(\n _depositDustThreshold > _depositTxMaxFee,\n \"Deposit dust threshold must be greater than deposit TX max fee\"\n );\n\n require(\n _depositTxMaxFee > 0,\n \"Deposit transaction max fee must be greater than zero\"\n );\n\n self.depositDustThreshold = _depositDustThreshold;\n self.depositTreasuryFeeDivisor = _depositTreasuryFeeDivisor;\n self.depositTxMaxFee = _depositTxMaxFee;\n self.depositRevealAheadPeriod = _depositRevealAheadPeriod;\n\n emit DepositParametersUpdated(\n _depositDustThreshold,\n _depositTreasuryFeeDivisor,\n _depositTxMaxFee,\n _depositRevealAheadPeriod\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param _redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param _redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param _redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param _redemptionTxMaxTotalFee New value of the redemption transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single redemption\n /// transaction. This is a _total_ max fee for the entire redemption\n /// transaction.\n /// @param _redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked TBTC is returned to the\n /// redeemer in full amount.\n /// @param _redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param _redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\n /// - Redemption dust threshold must be greater than the redemption TX\n /// max fee,\n /// - Redemption transaction max fee must be greater than zero,\n /// - Redemption transaction max total fee must be greater than or\n /// equal to the redemption transaction per-request max fee,\n /// - Redemption timeout must be greater than zero,\n /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n Storage storage self,\n uint64 _redemptionDustThreshold,\n uint64 _redemptionTreasuryFeeDivisor,\n uint64 _redemptionTxMaxFee,\n uint64 _redemptionTxMaxTotalFee,\n uint32 _redemptionTimeout,\n uint96 _redemptionTimeoutSlashingAmount,\n uint32 _redemptionTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _redemptionDustThreshold > self.movingFundsDustThreshold,\n \"Redemption dust threshold must be greater than moving funds dust threshold\"\n );\n\n require(\n _redemptionDustThreshold > _redemptionTxMaxFee,\n \"Redemption dust threshold must be greater than redemption TX max fee\"\n );\n\n require(\n _redemptionTxMaxFee > 0,\n \"Redemption transaction max fee must be greater than zero\"\n );\n\n require(\n _redemptionTxMaxTotalFee >= _redemptionTxMaxFee,\n \"Redemption transaction max total fee must be greater than or equal to the redemption transaction per-request max fee\"\n );\n\n require(\n _redemptionTimeout > 0,\n \"Redemption timeout must be greater than zero\"\n );\n\n require(\n _redemptionTimeoutNotifierRewardMultiplier <= 100,\n \"Redemption timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.redemptionDustThreshold = _redemptionDustThreshold;\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n self.redemptionTxMaxFee = _redemptionTxMaxFee;\n self.redemptionTxMaxTotalFee = _redemptionTxMaxTotalFee;\n self.redemptionTimeout = _redemptionTimeout;\n self.redemptionTimeoutSlashingAmount = _redemptionTimeoutSlashingAmount;\n self\n .redemptionTimeoutNotifierRewardMultiplier = _redemptionTimeoutNotifierRewardMultiplier;\n\n emit RedemptionParametersUpdated(\n _redemptionDustThreshold,\n _redemptionTreasuryFeeDivisor,\n _redemptionTxMaxFee,\n _redemptionTxMaxTotalFee,\n _redemptionTimeout,\n _redemptionTimeoutSlashingAmount,\n _redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param _movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param _movingFundsDustThreshold New value of the moving funds dust\n /// threshold. It is the minimal satoshi amount that makes sense to\n /// be transferred during the moving funds process. Moving funds\n /// wallets having their BTC balance below that value can begin\n /// closing immediately as transferring such a low value may not be\n /// possible due to BTC network fees.\n /// @param _movingFundsTimeoutResetDelay New value of the moving funds\n /// timeout reset delay in seconds. It is the time after which the\n /// moving funds timeout can be reset in case the target wallet\n /// commitment cannot be submitted due to a lack of live wallets\n /// in the system. It is counted from the moment when the wallet\n /// was requested to move their funds and switched to the MovingFunds\n /// state or from the moment the timeout was reset the last time.\n /// @param _movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @param _movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param _movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param _movingFundsCommitmentGasOffset New value of the gas offset for\n /// moving funds target wallet commitment transaction gas costs\n /// reimbursement.\n /// @param _movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param _movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param _movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param _movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout reset delay must be greater than zero,\n /// - Moving funds timeout must be greater than the moving funds\n /// timeout reset delay,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n Storage storage self,\n uint64 _movingFundsTxMaxTotalFee,\n uint64 _movingFundsDustThreshold,\n uint32 _movingFundsTimeoutResetDelay,\n uint32 _movingFundsTimeout,\n uint96 _movingFundsTimeoutSlashingAmount,\n uint32 _movingFundsTimeoutNotifierRewardMultiplier,\n uint16 _movingFundsCommitmentGasOffset,\n uint64 _movedFundsSweepTxMaxTotalFee,\n uint32 _movedFundsSweepTimeout,\n uint96 _movedFundsSweepTimeoutSlashingAmount,\n uint32 _movedFundsSweepTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _movingFundsTxMaxTotalFee > 0,\n \"Moving funds transaction max total fee must be greater than zero\"\n );\n\n require(\n _movingFundsDustThreshold > 0 &&\n _movingFundsDustThreshold < self.redemptionDustThreshold,\n \"Moving funds dust threshold must be greater than zero and lower than redemption dust threshold\"\n );\n\n require(\n _movingFundsTimeoutResetDelay > 0,\n \"Moving funds timeout reset delay must be greater than zero\"\n );\n\n require(\n _movingFundsTimeout > _movingFundsTimeoutResetDelay,\n \"Moving funds timeout must be greater than its reset delay\"\n );\n\n require(\n _movingFundsTimeoutNotifierRewardMultiplier <= 100,\n \"Moving funds timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n require(\n _movedFundsSweepTxMaxTotalFee > 0,\n \"Moved funds sweep transaction max total fee must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeout > 0,\n \"Moved funds sweep timeout must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeoutNotifierRewardMultiplier <= 100,\n \"Moved funds sweep timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n self.movingFundsDustThreshold = _movingFundsDustThreshold;\n self.movingFundsTimeoutResetDelay = _movingFundsTimeoutResetDelay;\n self.movingFundsTimeout = _movingFundsTimeout;\n self\n .movingFundsTimeoutSlashingAmount = _movingFundsTimeoutSlashingAmount;\n self\n .movingFundsTimeoutNotifierRewardMultiplier = _movingFundsTimeoutNotifierRewardMultiplier;\n self.movingFundsCommitmentGasOffset = _movingFundsCommitmentGasOffset;\n self.movedFundsSweepTxMaxTotalFee = _movedFundsSweepTxMaxTotalFee;\n self.movedFundsSweepTimeout = _movedFundsSweepTimeout;\n self\n .movedFundsSweepTimeoutSlashingAmount = _movedFundsSweepTimeoutSlashingAmount;\n self\n .movedFundsSweepTimeoutNotifierRewardMultiplier = _movedFundsSweepTimeoutNotifierRewardMultiplier;\n\n emit MovingFundsParametersUpdated(\n _movingFundsTxMaxTotalFee,\n _movingFundsDustThreshold,\n _movingFundsTimeoutResetDelay,\n _movingFundsTimeout,\n _movingFundsTimeoutSlashingAmount,\n _movingFundsTimeoutNotifierRewardMultiplier,\n _movingFundsCommitmentGasOffset,\n _movedFundsSweepTxMaxTotalFee,\n _movedFundsSweepTimeout,\n _movedFundsSweepTimeoutSlashingAmount,\n _movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param _walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested.\n /// @param _walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\n /// @param _walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @param _walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n /// to a single target wallet during the moving funds process.\n /// @param _walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges.\n /// @dev Requirements:\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance,\n /// - Wallet maximum BTC transfer must be greater than zero,\n /// - Wallet closing period must be greater than zero.\n function updateWalletParameters(\n Storage storage self,\n uint32 _walletCreationPeriod,\n uint64 _walletCreationMinBtcBalance,\n uint64 _walletCreationMaxBtcBalance,\n uint64 _walletClosureMinBtcBalance,\n uint32 _walletMaxAge,\n uint64 _walletMaxBtcTransfer,\n uint32 _walletClosingPeriod\n ) internal {\n require(\n _walletCreationMaxBtcBalance > _walletCreationMinBtcBalance,\n \"Wallet creation maximum BTC balance must be greater than the creation minimum BTC balance\"\n );\n require(\n _walletMaxBtcTransfer > 0,\n \"Wallet maximum BTC transfer must be greater than zero\"\n );\n require(\n _walletClosingPeriod > 0,\n \"Wallet closing period must be greater than zero\"\n );\n\n self.walletCreationPeriod = _walletCreationPeriod;\n self.walletCreationMinBtcBalance = _walletCreationMinBtcBalance;\n self.walletCreationMaxBtcBalance = _walletCreationMaxBtcBalance;\n self.walletClosureMinBtcBalance = _walletClosureMinBtcBalance;\n self.walletMaxAge = _walletMaxAge;\n self.walletMaxBtcTransfer = _walletMaxBtcTransfer;\n self.walletClosingPeriod = _walletClosingPeriod;\n\n emit WalletParametersUpdated(\n _walletCreationPeriod,\n _walletCreationMinBtcBalance,\n _walletCreationMaxBtcBalance,\n _walletClosureMinBtcBalance,\n _walletMaxAge,\n _walletMaxBtcTransfer,\n _walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param _fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit.\n /// @param _fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero.\n /// @param _fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud.\n /// @param _fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n Storage storage self,\n uint96 _fraudChallengeDepositAmount,\n uint32 _fraudChallengeDefeatTimeout,\n uint96 _fraudSlashingAmount,\n uint32 _fraudNotifierRewardMultiplier\n ) internal {\n require(\n _fraudChallengeDefeatTimeout > 0,\n \"Fraud challenge defeat timeout must be greater than zero\"\n );\n\n require(\n _fraudNotifierRewardMultiplier <= 100,\n \"Fraud notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.fraudChallengeDepositAmount = _fraudChallengeDepositAmount;\n self.fraudChallengeDefeatTimeout = _fraudChallengeDefeatTimeout;\n self.fraudSlashingAmount = _fraudSlashingAmount;\n self.fraudNotifierRewardMultiplier = _fraudNotifierRewardMultiplier;\n\n emit FraudParametersUpdated(\n _fraudChallengeDepositAmount,\n _fraudChallengeDefeatTimeout,\n _fraudSlashingAmount,\n _fraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates treasury address. The treasury receives the system fees.\n /// @param _treasury New value of the treasury address.\n /// @dev The treasury address must not be 0x0.\n function updateTreasury(Storage storage self, address _treasury) internal {\n require(_treasury != address(0), \"Treasury address must not be 0x0\");\n\n self.treasury = _treasury;\n emit TreasuryUpdated(_treasury);\n }\n}\n"
|
|
134
|
+
"content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity 0.8.17;\n\nimport {IWalletRegistry as EcdsaWalletRegistry} from \"@keep-network/ecdsa/contracts/api/IWalletRegistry.sol\";\nimport \"@keep-network/random-beacon/contracts/ReimbursementPool.sol\";\n\nimport \"./IRelay.sol\";\nimport \"./Deposit.sol\";\nimport \"./Redemption.sol\";\nimport \"./Fraud.sol\";\nimport \"./Wallets.sol\";\nimport \"./MovingFunds.sol\";\n\nimport \"../bank/Bank.sol\";\n\nlibrary BridgeState {\n struct Storage {\n // Address of the Bank the Bridge belongs to.\n Bank bank;\n // Bitcoin relay providing the current Bitcoin network difficulty.\n IRelay relay;\n // The number of confirmations on the Bitcoin chain required to\n // successfully evaluate an SPV proof.\n uint96 txProofDifficultyFactor;\n // ECDSA Wallet Registry contract handle.\n EcdsaWalletRegistry ecdsaWalletRegistry;\n // Reimbursement Pool contract handle.\n ReimbursementPool reimbursementPool;\n // Address where the deposit and redemption treasury fees will be sent\n // to. Treasury takes part in the operators rewarding process.\n address treasury;\n // Move depositDustThreshold to the next storage slot for a more\n // efficient variable layout in the storage.\n // slither-disable-next-line unused-state\n bytes32 __treasuryAlignmentGap;\n // The minimal amount that can be requested to deposit.\n // Value of this parameter must take into account the value of\n // `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters in order\n // to make requests that can incur the treasury and transaction fee and\n // still satisfy the depositor.\n uint64 depositDustThreshold;\n // Divisor used to compute the treasury fee taken from each deposit and\n // transferred to the treasury upon sweep proof submission. That fee is\n // computed as follows:\n // `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each deposit,\n // the `depositTreasuryFeeDivisor` should be set to `50` because\n // `1/50 = 0.02 = 2%`.\n uint64 depositTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by each\n // swept deposit being part of the given sweep transaction. If the\n // maximum BTC transaction fee is exceeded, such transaction is\n // considered a fraud.\n //\n // This is a per-deposit input max fee for the sweep transaction.\n uint64 depositTxMaxFee;\n // Defines the length of the period that must be preserved between\n // the deposit reveal time and the deposit refund locktime. For example,\n // if the deposit become refundable on August 1st, and the ahead period\n // is 7 days, the latest moment for deposit reveal is July 25th.\n // Value in seconds. The value equal to zero disables the validation\n // of this parameter.\n uint32 depositRevealAheadPeriod;\n // Move movingFundsTxMaxTotalFee to the next storage slot for a more\n // efficient variable layout in the storage.\n // slither-disable-next-line unused-state\n bytes32 __depositAlignmentGap;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moving funds transaction.\n //\n // This is a TOTAL max fee for the moving funds transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // is per single redemption. `movingFundsTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movingFundsTxMaxTotalFee;\n // The minimal satoshi amount that makes sense to be transferred during\n // the moving funds process. Moving funds wallets having their BTC\n // balance below that value can begin closing immediately as\n // transferring such a low value may not be possible due to\n // BTC network fees. The value of this parameter must always be lower\n // than `redemptionDustThreshold` in order to prevent redemption requests\n // with values lower or equal to `movingFundsDustThreshold`.\n uint64 movingFundsDustThreshold;\n // Time after which the moving funds timeout can be reset in case the\n // target wallet commitment cannot be submitted due to a lack of live\n // wallets in the system. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state or from the moment the timeout was reset the last time.\n // Value in seconds. This value should be lower than the value\n // of the `movingFundsTimeout`.\n uint32 movingFundsTimeoutResetDelay;\n // Time after which the moving funds process can be reported as\n // timed out. It is counted from the moment when the wallet\n // was requested to move their funds and switched to the MovingFunds\n // state. Value in seconds.\n uint32 movingFundsTimeout;\n // The amount of stake slashed from each member of a wallet for a moving\n // funds timeout.\n uint96 movingFundsTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moving funds timeout receives. The value is in the\n // range [0, 100].\n uint32 movingFundsTimeoutNotifierRewardMultiplier;\n // The gas offset used for the target wallet commitment transaction cost\n // reimbursement.\n uint16 movingFundsCommitmentGasOffset;\n // Move movedFundsSweepTxMaxTotalFee to the next storage slot for a more\n // efficient variable layout in the storage.\n // slither-disable-next-line unused-state\n bytes32 __movingFundsAlignmentGap;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single moved funds sweep transaction.\n //\n // This is a TOTAL max fee for the moved funds sweep transaction. Note\n // that `depositTxMaxFee` is per single deposit and `redemptionTxMaxFee`\n // is per single redemption. `movedFundsSweepTxMaxTotalFee` is a total\n // fee for the entire transaction.\n uint64 movedFundsSweepTxMaxTotalFee;\n // Time after which the moved funds sweep process can be reported as\n // timed out. It is counted from the moment when the recipient wallet\n // was requested to sweep the received funds. Value in seconds.\n uint32 movedFundsSweepTimeout;\n // The amount of stake slashed from each member of a wallet for a moved\n // funds sweep timeout.\n uint96 movedFundsSweepTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a moved funds sweep timeout receives. The value is\n // in the range [0, 100].\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier;\n // The minimal amount that can be requested for redemption.\n // Value of this parameter must take into account the value of\n // `redemptionTreasuryFeeDivisor` and `redemptionTxMaxFee`\n // parameters in order to make requests that can incur the\n // treasury and transaction fee and still satisfy the redeemer.\n // Additionally, the value of this parameter must always be greater\n // than `movingFundsDustThreshold` in order to prevent redemption\n // requests with values lower or equal to `movingFundsDustThreshold`.\n uint64 redemptionDustThreshold;\n // Divisor used to compute the treasury fee taken from each\n // redemption request and transferred to the treasury upon\n // successful request finalization. That fee is computed as follows:\n // `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n // For example, if the treasury fee needs to be 2% of each\n // redemption request, the `redemptionTreasuryFeeDivisor` should\n // be set to `50` because `1/50 = 0.02 = 2%`.\n uint64 redemptionTreasuryFeeDivisor;\n // Maximum amount of BTC transaction fee that can be incurred by\n // each redemption request being part of the given redemption\n // transaction. If the maximum BTC transaction fee is exceeded, such\n // transaction is considered a fraud.\n //\n // This is a per-redemption output max fee for the redemption\n // transaction.\n uint64 redemptionTxMaxFee;\n // Maximum amount of the total BTC transaction fee that is acceptable in\n // a single redemption transaction.\n //\n // This is a TOTAL max fee for the redemption transaction. Note\n // that the `redemptionTxMaxFee` is per single redemption.\n // `redemptionTxMaxTotalFee` is a total fee for the entire transaction.\n uint64 redemptionTxMaxTotalFee;\n // Move redemptionTimeout to the next storage slot for a more efficient\n // variable layout in the storage.\n // slither-disable-next-line unused-state\n bytes32 __redemptionAlignmentGap;\n // Time after which the redemption request can be reported as\n // timed out. It is counted from the moment when the redemption\n // request was created via `requestRedemption` call. Reported\n // timed out requests are cancelled and locked TBTC is returned\n // to the redeemer in full amount.\n uint32 redemptionTimeout;\n // The amount of stake slashed from each member of a wallet for a\n // redemption timeout.\n uint96 redemptionTimeoutSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a redemption timeout receives. The value is in the\n // range [0, 100].\n uint32 redemptionTimeoutNotifierRewardMultiplier;\n // The amount of ETH in wei the party challenging the wallet for fraud\n // needs to deposit.\n uint96 fraudChallengeDepositAmount;\n // The amount of time the wallet has to defeat a fraud challenge.\n uint32 fraudChallengeDefeatTimeout;\n // The amount of stake slashed from each member of a wallet for a fraud.\n uint96 fraudSlashingAmount;\n // The percentage of the notifier reward from the staking contract\n // the notifier of a fraud receives. The value is in the range [0, 100].\n uint32 fraudNotifierRewardMultiplier;\n // Determines how frequently a new wallet creation can be requested.\n // Value in seconds.\n uint32 walletCreationPeriod;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet creation. Specifically, we allow for the creation of a new\n // wallet if the active wallet is old enough and their amount of BTC\n // is greater than or equal this threshold.\n uint64 walletCreationMinBtcBalance;\n // The maximum BTC threshold in satoshi that is used to decide about\n // wallet creation. Specifically, we allow for the creation of a new\n // wallet if the active wallet's amount of BTC is greater than or equal\n // this threshold, regardless of the active wallet's age.\n uint64 walletCreationMaxBtcBalance;\n // The minimum BTC threshold in satoshi that is used to decide about\n // wallet closing. Specifically, we allow for the closure of the given\n // wallet if their amount of BTC is lesser than this threshold,\n // regardless of the wallet's age.\n uint64 walletClosureMinBtcBalance;\n // The maximum age of a wallet in seconds, after which the wallet\n // moving funds process can be requested.\n uint32 walletMaxAge;\n // 20-byte wallet public key hash being reference to the currently\n // active wallet. Can be unset to the zero value under certain\n // circumstances.\n bytes20 activeWalletPubKeyHash;\n // The current number of wallets in the Live state.\n uint32 liveWalletsCount;\n // The maximum BTC amount in satoshi than can be transferred to a single\n // target wallet during the moving funds process.\n uint64 walletMaxBtcTransfer;\n // Determines the length of the wallet closing period, i.e. the period\n // when the wallet remains in the Closing state and can be subject\n // of deposit fraud challenges. This value is in seconds and should be\n // greater than the deposit refund time plus some time margin.\n uint32 walletClosingPeriod;\n // Collection of all revealed deposits indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`.\n // The `fundingTxHash` is `bytes32` (ordered as in Bitcoin internally)\n // and `fundingOutputIndex` an `uint32`. This mapping may contain valid\n // and invalid deposits and the wallet is responsible for validating\n // them before attempting to execute a sweep.\n mapping(uint256 => Deposit.DepositRequest) deposits;\n // Indicates if the vault with the given address is trusted.\n // Depositors can route their revealed deposits only to trusted vaults\n // and have trusted vaults notified about new deposits as soon as these\n // deposits get swept. Vaults not trusted by the Bridge can still be\n // used by Bank balance owners on their own responsibility - anyone can\n // approve their Bank balance to any address.\n mapping(address => bool) isVaultTrusted;\n // Indicates if the address is a trusted SPV maintainer.\n // The SPV proof does not check whether the transaction is a part of the\n // Bitcoin mainnet, it only checks whether the transaction has been\n // mined performing the required amount of work as on Bitcoin mainnet.\n // The possibility of submitting SPV proofs is limited to trusted SPV\n // maintainers. The system expects transaction confirmations with the\n // required work accumulated, so trusted SPV maintainers can not prove\n // the transaction without providing the required Bitcoin proof of work.\n // Trusted maintainers address the issue of an economic game between\n // tBTC and Bitcoin mainnet where large Bitcoin mining pools can decide\n // to use their hash power to mine fake Bitcoin blocks to prove them in\n // tBTC instead of receiving Bitcoin miner rewards.\n mapping(address => bool) isSpvMaintainer;\n // Collection of all moved funds sweep requests indexed by\n // `keccak256(movingFundsTxHash | movingFundsOutputIndex)`.\n // The `movingFundsTxHash` is `bytes32` (ordered as in Bitcoin\n // internally) and `movingFundsOutputIndex` an `uint32`. Each entry\n // is actually an UTXO representing the moved funds and is supposed\n // to be swept with the current main UTXO of the recipient wallet.\n mapping(uint256 => MovingFunds.MovedFundsSweepRequest) movedFundsSweepRequests;\n // Collection of all pending redemption requests indexed by\n // redemption key built as\n // `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.\n // The `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is a Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that will be used to lock\n // redeemed BTC as requested by the redeemer. Requests are added\n // to this mapping by the `requestRedemption` method (duplicates\n // not allowed) and are removed by one of the following methods:\n // - `submitRedemptionProof` in case the request was handled\n // successfully,\n // - `notifyRedemptionTimeout` in case the request was reported\n // to be timed out.\n mapping(uint256 => Redemption.RedemptionRequest) pendingRedemptions;\n // Collection of all timed out redemptions requests indexed by\n // redemption key built as\n // `keccak256(keccak256(redeemerOutputScript) | walletPubKeyHash)`.\n // The `walletPubKeyHash` is the 20-byte wallet's public key hash\n // (computed using Bitcoin HASH160 over the compressed ECDSA\n // public key) and `redeemerOutputScript` is the Bitcoin script\n // (P2PKH, P2WPKH, P2SH or P2WSH) that is involved in the timed\n // out request.\n // Only one method can add to this mapping:\n // - `notifyRedemptionTimeout` which puts the redemption key to this\n // mapping based on a timed out request stored previously in\n // `pendingRedemptions` mapping.\n // Only one method can remove entries from this mapping:\n // - `submitRedemptionProof` in case the timed out redemption request\n // was a part of the proven transaction.\n mapping(uint256 => Redemption.RedemptionRequest) timedOutRedemptions;\n // Collection of all submitted fraud challenges indexed by challenge\n // key built as `keccak256(walletPublicKey|sighash)`.\n mapping(uint256 => Fraud.FraudChallenge) fraudChallenges;\n // Collection of main UTXOs that are honestly spent indexed by\n // `keccak256(fundingTxHash | fundingOutputIndex)`. The `fundingTxHash`\n // is `bytes32` (ordered as in Bitcoin internally) and\n // `fundingOutputIndex` an `uint32`. A main UTXO is considered honestly\n // spent if it was used as an input of a transaction that have been\n // proven in the Bridge.\n mapping(uint256 => bool) spentMainUTXOs;\n // Maps the 20-byte wallet public key hash (computed using Bitcoin\n // HASH160 over the compressed ECDSA public key) to the basic wallet\n // information like state and pending redemptions value.\n mapping(bytes20 => Wallets.Wallet) registeredWallets;\n // Reserved storage space in case we need to add more variables.\n // The convention from OpenZeppelin suggests the storage space should\n // add up to 50 slots. Here we want to have more slots as there are\n // planned upgrades of the Bridge contract. If more entires are added to\n // the struct in the upcoming versions we need to reduce the array size.\n // See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n // slither-disable-next-line unused-state\n uint256[50] __gap;\n }\n\n event DepositParametersUpdated(\n uint64 depositDustThreshold,\n uint64 depositTreasuryFeeDivisor,\n uint64 depositTxMaxFee,\n uint32 depositRevealAheadPeriod\n );\n\n event RedemptionParametersUpdated(\n uint64 redemptionDustThreshold,\n uint64 redemptionTreasuryFeeDivisor,\n uint64 redemptionTxMaxFee,\n uint64 redemptionTxMaxTotalFee,\n uint32 redemptionTimeout,\n uint96 redemptionTimeoutSlashingAmount,\n uint32 redemptionTimeoutNotifierRewardMultiplier\n );\n\n event MovingFundsParametersUpdated(\n uint64 movingFundsTxMaxTotalFee,\n uint64 movingFundsDustThreshold,\n uint32 movingFundsTimeoutResetDelay,\n uint32 movingFundsTimeout,\n uint96 movingFundsTimeoutSlashingAmount,\n uint32 movingFundsTimeoutNotifierRewardMultiplier,\n uint16 movingFundsCommitmentGasOffset,\n uint64 movedFundsSweepTxMaxTotalFee,\n uint32 movedFundsSweepTimeout,\n uint96 movedFundsSweepTimeoutSlashingAmount,\n uint32 movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n\n event WalletParametersUpdated(\n uint32 walletCreationPeriod,\n uint64 walletCreationMinBtcBalance,\n uint64 walletCreationMaxBtcBalance,\n uint64 walletClosureMinBtcBalance,\n uint32 walletMaxAge,\n uint64 walletMaxBtcTransfer,\n uint32 walletClosingPeriod\n );\n\n event FraudParametersUpdated(\n uint96 fraudChallengeDepositAmount,\n uint32 fraudChallengeDefeatTimeout,\n uint96 fraudSlashingAmount,\n uint32 fraudNotifierRewardMultiplier\n );\n\n event TreasuryUpdated(address treasury);\n\n /// @notice Updates parameters of deposits.\n /// @param _depositDustThreshold New value of the deposit dust threshold in\n /// satoshis. It is the minimal amount that can be requested to\n //// deposit. Value of this parameter must take into account the value\n /// of `depositTreasuryFeeDivisor` and `depositTxMaxFee` parameters\n /// in order to make requests that can incur the treasury and\n /// transaction fee and still satisfy the depositor.\n /// @param _depositTreasuryFeeDivisor New value of the treasury fee divisor.\n /// It is the divisor used to compute the treasury fee taken from\n /// each deposit and transferred to the treasury upon sweep proof\n /// submission. That fee is computed as follows:\n /// `treasuryFee = depositedAmount / depositTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each deposit,\n /// the `depositTreasuryFeeDivisor` should be set to `50`\n /// because `1/50 = 0.02 = 2%`.\n /// @param _depositTxMaxFee New value of the deposit tx max fee in satoshis.\n /// It is the maximum amount of BTC transaction fee that can\n /// be incurred by each swept deposit being part of the given sweep\n /// transaction. If the maximum BTC transaction fee is exceeded,\n /// such transaction is considered a fraud.\n /// @param _depositRevealAheadPeriod New value of the deposit reveal ahead\n /// period parameter in seconds. It defines the length of the period\n /// that must be preserved between the deposit reveal time and the\n /// deposit refund locktime.\n /// @dev Requirements:\n /// - Deposit dust threshold must be greater than zero,\n /// - Deposit dust threshold must be greater than deposit TX max fee,\n /// - Deposit transaction max fee must be greater than zero.\n function updateDepositParameters(\n Storage storage self,\n uint64 _depositDustThreshold,\n uint64 _depositTreasuryFeeDivisor,\n uint64 _depositTxMaxFee,\n uint32 _depositRevealAheadPeriod\n ) internal {\n require(\n _depositDustThreshold > 0,\n \"Deposit dust threshold must be greater than zero\"\n );\n\n require(\n _depositDustThreshold > _depositTxMaxFee,\n \"Deposit dust threshold must be greater than deposit TX max fee\"\n );\n\n require(\n _depositTxMaxFee > 0,\n \"Deposit transaction max fee must be greater than zero\"\n );\n\n self.depositDustThreshold = _depositDustThreshold;\n self.depositTreasuryFeeDivisor = _depositTreasuryFeeDivisor;\n self.depositTxMaxFee = _depositTxMaxFee;\n self.depositRevealAheadPeriod = _depositRevealAheadPeriod;\n\n emit DepositParametersUpdated(\n _depositDustThreshold,\n _depositTreasuryFeeDivisor,\n _depositTxMaxFee,\n _depositRevealAheadPeriod\n );\n }\n\n /// @notice Updates parameters of redemptions.\n /// @param _redemptionDustThreshold New value of the redemption dust\n /// threshold in satoshis. It is the minimal amount that can be\n /// requested for redemption. Value of this parameter must take into\n /// account the value of `redemptionTreasuryFeeDivisor` and\n /// `redemptionTxMaxFee` parameters in order to make requests that\n /// can incur the treasury and transaction fee and still satisfy the\n /// redeemer.\n /// @param _redemptionTreasuryFeeDivisor New value of the redemption\n /// treasury fee divisor. It is the divisor used to compute the\n /// treasury fee taken from each redemption request and transferred\n /// to the treasury upon successful request finalization. That fee is\n /// computed as follows:\n /// `treasuryFee = requestedAmount / redemptionTreasuryFeeDivisor`\n /// For example, if the treasury fee needs to be 2% of each\n /// redemption request, the `redemptionTreasuryFeeDivisor` should\n /// be set to `50` because `1/50 = 0.02 = 2%`.\n /// @param _redemptionTxMaxFee New value of the redemption transaction max\n /// fee in satoshis. It is the maximum amount of BTC transaction fee\n /// that can be incurred by each redemption request being part of the\n /// given redemption transaction. If the maximum BTC transaction fee\n /// is exceeded, such transaction is considered a fraud.\n /// This is a per-redemption output max fee for the redemption\n /// transaction.\n /// @param _redemptionTxMaxTotalFee New value of the redemption transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single redemption\n /// transaction. This is a _total_ max fee for the entire redemption\n /// transaction.\n /// @param _redemptionTimeout New value of the redemption timeout in seconds.\n /// It is the time after which the redemption request can be reported\n /// as timed out. It is counted from the moment when the redemption\n /// request was created via `requestRedemption` call. Reported timed\n /// out requests are cancelled and locked TBTC is returned to the\n /// redeemer in full amount.\n /// @param _redemptionTimeoutSlashingAmount New value of the redemption\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for redemption timeout.\n /// @param _redemptionTimeoutNotifierRewardMultiplier New value of the\n /// redemption timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a redemption timeout receives.\n /// The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Redemption dust threshold must be greater than moving funds dust\n /// threshold,\n /// - Redemption dust threshold must be greater than the redemption TX\n /// max fee,\n /// - Redemption transaction max fee must be greater than zero,\n /// - Redemption transaction max total fee must be greater than or\n /// equal to the redemption transaction per-request max fee,\n /// - Redemption timeout must be greater than zero,\n /// - Redemption timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateRedemptionParameters(\n Storage storage self,\n uint64 _redemptionDustThreshold,\n uint64 _redemptionTreasuryFeeDivisor,\n uint64 _redemptionTxMaxFee,\n uint64 _redemptionTxMaxTotalFee,\n uint32 _redemptionTimeout,\n uint96 _redemptionTimeoutSlashingAmount,\n uint32 _redemptionTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _redemptionDustThreshold > self.movingFundsDustThreshold,\n \"Redemption dust threshold must be greater than moving funds dust threshold\"\n );\n\n require(\n _redemptionDustThreshold > _redemptionTxMaxFee,\n \"Redemption dust threshold must be greater than redemption TX max fee\"\n );\n\n require(\n _redemptionTxMaxFee > 0,\n \"Redemption transaction max fee must be greater than zero\"\n );\n\n require(\n _redemptionTxMaxTotalFee >= _redemptionTxMaxFee,\n \"Redemption transaction max total fee must be greater than or equal to the redemption transaction per-request max fee\"\n );\n\n require(\n _redemptionTimeout > 0,\n \"Redemption timeout must be greater than zero\"\n );\n\n require(\n _redemptionTimeoutNotifierRewardMultiplier <= 100,\n \"Redemption timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.redemptionDustThreshold = _redemptionDustThreshold;\n self.redemptionTreasuryFeeDivisor = _redemptionTreasuryFeeDivisor;\n self.redemptionTxMaxFee = _redemptionTxMaxFee;\n self.redemptionTxMaxTotalFee = _redemptionTxMaxTotalFee;\n self.redemptionTimeout = _redemptionTimeout;\n self.redemptionTimeoutSlashingAmount = _redemptionTimeoutSlashingAmount;\n self\n .redemptionTimeoutNotifierRewardMultiplier = _redemptionTimeoutNotifierRewardMultiplier;\n\n emit RedemptionParametersUpdated(\n _redemptionDustThreshold,\n _redemptionTreasuryFeeDivisor,\n _redemptionTxMaxFee,\n _redemptionTxMaxTotalFee,\n _redemptionTimeout,\n _redemptionTimeoutSlashingAmount,\n _redemptionTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of moving funds.\n /// @param _movingFundsTxMaxTotalFee New value of the moving funds transaction\n /// max total fee in satoshis. It is the maximum amount of the total\n /// BTC transaction fee that is acceptable in a single moving funds\n /// transaction. This is a _total_ max fee for the entire moving\n /// funds transaction.\n /// @param _movingFundsDustThreshold New value of the moving funds dust\n /// threshold. It is the minimal satoshi amount that makes sense to\n /// be transferred during the moving funds process. Moving funds\n /// wallets having their BTC balance below that value can begin\n /// closing immediately as transferring such a low value may not be\n /// possible due to BTC network fees.\n /// @param _movingFundsTimeoutResetDelay New value of the moving funds\n /// timeout reset delay in seconds. It is the time after which the\n /// moving funds timeout can be reset in case the target wallet\n /// commitment cannot be submitted due to a lack of live wallets\n /// in the system. It is counted from the moment when the wallet\n /// was requested to move their funds and switched to the MovingFunds\n /// state or from the moment the timeout was reset the last time.\n /// @param _movingFundsTimeout New value of the moving funds timeout in\n /// seconds. It is the time after which the moving funds process can\n /// be reported as timed out. It is counted from the moment when the\n /// wallet was requested to move their funds and switched to the\n /// MovingFunds state.\n /// @param _movingFundsTimeoutSlashingAmount New value of the moving funds\n /// timeout slashing amount in T, it is the amount slashed from each\n /// wallet member for moving funds timeout.\n /// @param _movingFundsTimeoutNotifierRewardMultiplier New value of the\n /// moving funds timeout notifier reward multiplier as percentage,\n /// it determines the percentage of the notifier reward from the\n /// staking contact the notifier of a moving funds timeout receives.\n /// The value must be in the range [0, 100].\n /// @param _movingFundsCommitmentGasOffset New value of the gas offset for\n /// moving funds target wallet commitment transaction gas costs\n /// reimbursement.\n /// @param _movedFundsSweepTxMaxTotalFee New value of the moved funds sweep\n /// transaction max total fee in satoshis. It is the maximum amount\n /// of the total BTC transaction fee that is acceptable in a single\n /// moved funds sweep transaction. This is a _total_ max fee for the\n /// entire moved funds sweep transaction.\n /// @param _movedFundsSweepTimeout New value of the moved funds sweep\n /// timeout in seconds. It is the time after which the moved funds\n /// sweep process can be reported as timed out. It is counted from\n /// the moment when the wallet was requested to sweep the received\n /// funds.\n /// @param _movedFundsSweepTimeoutSlashingAmount New value of the moved\n /// funds sweep timeout slashing amount in T, it is the amount\n /// slashed from each wallet member for moved funds sweep timeout.\n /// @param _movedFundsSweepTimeoutNotifierRewardMultiplier New value of\n /// the moved funds sweep timeout notifier reward multiplier as\n /// percentage, it determines the percentage of the notifier reward\n /// from the staking contact the notifier of a moved funds sweep\n /// timeout receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Moving funds transaction max total fee must be greater than zero,\n /// - Moving funds dust threshold must be greater than zero and lower\n /// than the redemption dust threshold,\n /// - Moving funds timeout reset delay must be greater than zero,\n /// - Moving funds timeout must be greater than the moving funds\n /// timeout reset delay,\n /// - Moving funds timeout notifier reward multiplier must be in the\n /// range [0, 100],\n /// - Moved funds sweep transaction max total fee must be greater than zero,\n /// - Moved funds sweep timeout must be greater than zero,\n /// - Moved funds sweep timeout notifier reward multiplier must be in the\n /// range [0, 100].\n function updateMovingFundsParameters(\n Storage storage self,\n uint64 _movingFundsTxMaxTotalFee,\n uint64 _movingFundsDustThreshold,\n uint32 _movingFundsTimeoutResetDelay,\n uint32 _movingFundsTimeout,\n uint96 _movingFundsTimeoutSlashingAmount,\n uint32 _movingFundsTimeoutNotifierRewardMultiplier,\n uint16 _movingFundsCommitmentGasOffset,\n uint64 _movedFundsSweepTxMaxTotalFee,\n uint32 _movedFundsSweepTimeout,\n uint96 _movedFundsSweepTimeoutSlashingAmount,\n uint32 _movedFundsSweepTimeoutNotifierRewardMultiplier\n ) internal {\n require(\n _movingFundsTxMaxTotalFee > 0,\n \"Moving funds transaction max total fee must be greater than zero\"\n );\n\n require(\n _movingFundsDustThreshold > 0 &&\n _movingFundsDustThreshold < self.redemptionDustThreshold,\n \"Moving funds dust threshold must be greater than zero and lower than redemption dust threshold\"\n );\n\n require(\n _movingFundsTimeoutResetDelay > 0,\n \"Moving funds timeout reset delay must be greater than zero\"\n );\n\n require(\n _movingFundsTimeout > _movingFundsTimeoutResetDelay,\n \"Moving funds timeout must be greater than its reset delay\"\n );\n\n require(\n _movingFundsTimeoutNotifierRewardMultiplier <= 100,\n \"Moving funds timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n require(\n _movedFundsSweepTxMaxTotalFee > 0,\n \"Moved funds sweep transaction max total fee must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeout > 0,\n \"Moved funds sweep timeout must be greater than zero\"\n );\n\n require(\n _movedFundsSweepTimeoutNotifierRewardMultiplier <= 100,\n \"Moved funds sweep timeout notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.movingFundsTxMaxTotalFee = _movingFundsTxMaxTotalFee;\n self.movingFundsDustThreshold = _movingFundsDustThreshold;\n self.movingFundsTimeoutResetDelay = _movingFundsTimeoutResetDelay;\n self.movingFundsTimeout = _movingFundsTimeout;\n self\n .movingFundsTimeoutSlashingAmount = _movingFundsTimeoutSlashingAmount;\n self\n .movingFundsTimeoutNotifierRewardMultiplier = _movingFundsTimeoutNotifierRewardMultiplier;\n self.movingFundsCommitmentGasOffset = _movingFundsCommitmentGasOffset;\n self.movedFundsSweepTxMaxTotalFee = _movedFundsSweepTxMaxTotalFee;\n self.movedFundsSweepTimeout = _movedFundsSweepTimeout;\n self\n .movedFundsSweepTimeoutSlashingAmount = _movedFundsSweepTimeoutSlashingAmount;\n self\n .movedFundsSweepTimeoutNotifierRewardMultiplier = _movedFundsSweepTimeoutNotifierRewardMultiplier;\n\n emit MovingFundsParametersUpdated(\n _movingFundsTxMaxTotalFee,\n _movingFundsDustThreshold,\n _movingFundsTimeoutResetDelay,\n _movingFundsTimeout,\n _movingFundsTimeoutSlashingAmount,\n _movingFundsTimeoutNotifierRewardMultiplier,\n _movingFundsCommitmentGasOffset,\n _movedFundsSweepTxMaxTotalFee,\n _movedFundsSweepTimeout,\n _movedFundsSweepTimeoutSlashingAmount,\n _movedFundsSweepTimeoutNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates parameters of wallets.\n /// @param _walletCreationPeriod New value of the wallet creation period in\n /// seconds, determines how frequently a new wallet creation can be\n /// requested.\n /// @param _walletCreationMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletCreationMaxBtcBalance New value of the wallet maximum BTC\n /// balance in satoshi, used to decide about wallet creation.\n /// @param _walletClosureMinBtcBalance New value of the wallet minimum BTC\n /// balance in satoshi, used to decide about wallet closure.\n /// @param _walletMaxAge New value of the wallet maximum age in seconds,\n /// indicates the maximum age of a wallet in seconds, after which\n /// the wallet moving funds process can be requested.\n /// @param _walletMaxBtcTransfer New value of the wallet maximum BTC transfer\n /// in satoshi, determines the maximum amount that can be transferred\n /// to a single target wallet during the moving funds process.\n /// @param _walletClosingPeriod New value of the wallet closing period in\n /// seconds, determines the length of the wallet closing period,\n // i.e. the period when the wallet remains in the Closing state\n // and can be subject of deposit fraud challenges.\n /// @dev Requirements:\n /// - Wallet maximum BTC balance must be greater than the wallet\n /// minimum BTC balance,\n /// - Wallet closure BTC balance must be greater than zero,\n /// - Wallet maximum BTC transfer must be greater than zero,\n /// - Wallet closing period must be greater than zero.\n function updateWalletParameters(\n Storage storage self,\n uint32 _walletCreationPeriod,\n uint64 _walletCreationMinBtcBalance,\n uint64 _walletCreationMaxBtcBalance,\n uint64 _walletClosureMinBtcBalance,\n uint32 _walletMaxAge,\n uint64 _walletMaxBtcTransfer,\n uint32 _walletClosingPeriod\n ) internal {\n require(\n _walletCreationMaxBtcBalance > _walletCreationMinBtcBalance,\n \"Wallet creation maximum BTC balance must be greater than the creation minimum BTC balance\"\n );\n require(\n _walletClosureMinBtcBalance > 0,\n \"Wallet closure minimum BTC balance must be greater than zero\"\n );\n require(\n _walletMaxBtcTransfer > 0,\n \"Wallet maximum BTC transfer must be greater than zero\"\n );\n require(\n _walletClosingPeriod > 0,\n \"Wallet closing period must be greater than zero\"\n );\n\n self.walletCreationPeriod = _walletCreationPeriod;\n self.walletCreationMinBtcBalance = _walletCreationMinBtcBalance;\n self.walletCreationMaxBtcBalance = _walletCreationMaxBtcBalance;\n self.walletClosureMinBtcBalance = _walletClosureMinBtcBalance;\n self.walletMaxAge = _walletMaxAge;\n self.walletMaxBtcTransfer = _walletMaxBtcTransfer;\n self.walletClosingPeriod = _walletClosingPeriod;\n\n emit WalletParametersUpdated(\n _walletCreationPeriod,\n _walletCreationMinBtcBalance,\n _walletCreationMaxBtcBalance,\n _walletClosureMinBtcBalance,\n _walletMaxAge,\n _walletMaxBtcTransfer,\n _walletClosingPeriod\n );\n }\n\n /// @notice Updates parameters related to frauds.\n /// @param _fraudChallengeDepositAmount New value of the fraud challenge\n /// deposit amount in wei, it is the amount of ETH the party\n /// challenging the wallet for fraud needs to deposit.\n /// @param _fraudChallengeDefeatTimeout New value of the challenge defeat\n /// timeout in seconds, it is the amount of time the wallet has to\n /// defeat a fraud challenge. The value must be greater than zero.\n /// @param _fraudSlashingAmount New value of the fraud slashing amount in T,\n /// it is the amount slashed from each wallet member for committing\n /// a fraud.\n /// @param _fraudNotifierRewardMultiplier New value of the fraud notifier\n /// reward multiplier as percentage, it determines the percentage of\n /// the notifier reward from the staking contact the notifier of\n /// a fraud receives. The value must be in the range [0, 100].\n /// @dev Requirements:\n /// - Fraud challenge defeat timeout must be greater than 0,\n /// - Fraud notifier reward multiplier must be in the range [0, 100].\n function updateFraudParameters(\n Storage storage self,\n uint96 _fraudChallengeDepositAmount,\n uint32 _fraudChallengeDefeatTimeout,\n uint96 _fraudSlashingAmount,\n uint32 _fraudNotifierRewardMultiplier\n ) internal {\n require(\n _fraudChallengeDefeatTimeout > 0,\n \"Fraud challenge defeat timeout must be greater than zero\"\n );\n\n require(\n _fraudNotifierRewardMultiplier <= 100,\n \"Fraud notifier reward multiplier must be in the range [0, 100]\"\n );\n\n self.fraudChallengeDepositAmount = _fraudChallengeDepositAmount;\n self.fraudChallengeDefeatTimeout = _fraudChallengeDefeatTimeout;\n self.fraudSlashingAmount = _fraudSlashingAmount;\n self.fraudNotifierRewardMultiplier = _fraudNotifierRewardMultiplier;\n\n emit FraudParametersUpdated(\n _fraudChallengeDepositAmount,\n _fraudChallengeDefeatTimeout,\n _fraudSlashingAmount,\n _fraudNotifierRewardMultiplier\n );\n }\n\n /// @notice Updates treasury address. The treasury receives the system fees.\n /// @param _treasury New value of the treasury address.\n /// @dev The treasury address must not be 0x0.\n function updateTreasury(Storage storage self, address _treasury) internal {\n require(_treasury != address(0), \"Treasury address must not be 0x0\");\n\n self.treasury = _treasury;\n emit TreasuryUpdated(_treasury);\n }\n}\n"
|
|
138
135
|
},
|
|
139
136
|
"contracts/bridge/Deposit.sol": {
|
|
140
137
|
"content": "// SPDX-License-Identifier: GPL-3.0-only\n\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ██████████████ ▐████▌ ██████████████\n// ██████████████ ▐████▌ ██████████████\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n// ▐████▌ ▐████▌\n\npragma solidity 0.8.17;\n\nimport {BTCUtils} from \"@keep-network/bitcoin-spv-sol/contracts/BTCUtils.sol\";\nimport {BytesLib} from \"@keep-network/bitcoin-spv-sol/contracts/BytesLib.sol\";\n\nimport \"./BitcoinTx.sol\";\nimport \"./BridgeState.sol\";\nimport \"./Wallets.sol\";\n\n/// @title Bridge deposit\n/// @notice The library handles the logic for revealing Bitcoin deposits to\n/// the Bridge.\n/// @dev The depositor puts together a P2SH or P2WSH address to deposit the\n/// funds. This script is unique to each depositor and looks like this:\n///\n/// ```\n/// <depositorAddress> DROP\n/// <blindingFactor> DROP\n/// DUP HASH160 <walletPubKeyHash> EQUAL\n/// IF\n/// CHECKSIG\n/// ELSE\n/// DUP HASH160 <refundPubkeyHash> EQUALVERIFY\n/// <refundLocktime> CHECKLOCKTIMEVERIFY DROP\n/// CHECKSIG\n/// ENDIF\n/// ```\n///\n/// Since each depositor has their own Ethereum address and their own\n/// blinding factor, each depositor’s script is unique, and the hash\n/// of each depositor’s script is unique.\nlibrary Deposit {\n using BTCUtils for bytes;\n using BytesLib for bytes;\n\n /// @notice Represents data which must be revealed by the depositor during\n /// deposit reveal.\n struct DepositRevealInfo {\n // Index of the funding output belonging to the funding transaction.\n uint32 fundingOutputIndex;\n // The blinding factor as 8 bytes. Byte endianness doesn't matter\n // as this factor is not interpreted as uint. The blinding factor allows\n // to distinguish deposits from the same depositor.\n bytes8 blindingFactor;\n // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)\n // of the deposit's wallet hashed in the HASH160 Bitcoin opcode style.\n bytes20 walletPubKeyHash;\n // The compressed Bitcoin public key (33 bytes and 02 or 03 prefix)\n // that can be used to make the deposit refund after the refund\n // locktime passes. Hashed in the HASH160 Bitcoin opcode style.\n bytes20 refundPubKeyHash;\n // The refund locktime (4-byte LE). Interpreted according to locktime\n // parsing rules described in:\n // https://developer.bitcoin.org/devguide/transactions.html#locktime-and-sequence-number\n // and used with OP_CHECKLOCKTIMEVERIFY opcode as described in:\n // https://github.com/bitcoin/bips/blob/master/bip-0065.mediawiki\n bytes4 refundLocktime;\n // Address of the Bank vault to which the deposit is routed to.\n // Optional, can be 0x0. The vault must be trusted by the Bridge.\n address vault;\n // This struct doesn't contain `__gap` property as the structure is not\n // stored, it is used as a function's calldata argument.\n }\n\n /// @notice Represents tBTC deposit request data.\n struct DepositRequest {\n // Ethereum depositor address.\n address depositor;\n // Deposit amount in satoshi.\n uint64 amount;\n // UNIX timestamp the deposit was revealed at.\n // XXX: Unsigned 32-bit int unix seconds, will break February 7th 2106.\n uint32 revealedAt;\n // Address of the Bank vault the deposit is routed to.\n // Optional, can be 0x0.\n address vault;\n // Treasury TBTC fee in satoshi at the moment of deposit reveal.\n uint64 treasuryFee;\n // UNIX timestamp the deposit was swept at. Note this is not the\n // time when the deposit was swept on the Bitcoin chain but actually\n // the time when the sweep proof was delivered to the Ethereum chain.\n // XXX: Unsigned 32-bit int unix seconds, will break February 7th 2106.\n uint32 sweptAt;\n // This struct doesn't contain `__gap` property as the structure is stored\n // in a mapping, mappings store values in different slots and they are\n // not contiguous with other values.\n }\n\n event DepositRevealed(\n bytes32 fundingTxHash,\n uint32 fundingOutputIndex,\n address indexed depositor,\n uint64 amount,\n bytes8 blindingFactor,\n bytes20 indexed walletPubKeyHash,\n bytes20 refundPubKeyHash,\n bytes4 refundLocktime,\n address vault\n );\n\n /// @notice Used by the depositor to reveal information about their P2(W)SH\n /// Bitcoin deposit to the Bridge on Ethereum chain. The off-chain\n /// wallet listens for revealed deposit events and may decide to\n /// include the revealed deposit in the next executed sweep.\n /// Information about the Bitcoin deposit can be revealed before or\n /// after the Bitcoin transaction with P2(W)SH deposit is mined on\n /// the Bitcoin chain. Worth noting, the gas cost of this function\n /// scales with the number of P2(W)SH transaction inputs and\n /// outputs. The deposit may be routed to one of the trusted vaults.\n /// When a deposit is routed to a vault, vault gets notified when\n /// the deposit gets swept and it may execute the appropriate action.\n /// @param fundingTx Bitcoin funding transaction data, see `BitcoinTx.Info`.\n /// @param reveal Deposit reveal data, see `RevealInfo struct.\n /// @dev Requirements:\n /// - This function must be called by the same Ethereum address as the\n /// one used in the P2(W)SH BTC deposit transaction as a depositor,\n /// - `reveal.walletPubKeyHash` must identify a `Live` wallet,\n /// - `reveal.vault` must be 0x0 or point to a trusted vault,\n /// - `reveal.fundingOutputIndex` must point to the actual P2(W)SH\n /// output of the BTC deposit transaction,\n /// - `reveal.blindingFactor` must be the blinding factor used in the\n /// P2(W)SH BTC deposit transaction,\n /// - `reveal.walletPubKeyHash` must be the wallet pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundPubKeyHash` must be the refund pub key hash used in\n /// the P2(W)SH BTC deposit transaction,\n /// - `reveal.refundLocktime` must be the refund locktime used in the\n /// P2(W)SH BTC deposit transaction,\n /// - BTC deposit for the given `fundingTxHash`, `fundingOutputIndex`\n /// can be revealed only one time.\n ///\n /// If any of these requirements is not met, the wallet _must_ refuse\n /// to sweep the deposit and the depositor has to wait until the\n /// deposit script unlocks to receive their BTC back.\n function revealDeposit(\n BridgeState.Storage storage self,\n BitcoinTx.Info calldata fundingTx,\n DepositRevealInfo calldata reveal\n ) external {\n require(\n self.registeredWallets[reveal.walletPubKeyHash].state ==\n Wallets.WalletState.Live,\n \"Wallet must be in Live state\"\n );\n\n require(\n reveal.vault == address(0) || self.isVaultTrusted[reveal.vault],\n \"Vault is not trusted\"\n );\n\n if (self.depositRevealAheadPeriod > 0) {\n validateDepositRefundLocktime(self, reveal.refundLocktime);\n }\n\n bytes memory expectedScript = abi.encodePacked(\n hex\"14\", // Byte length of depositor Ethereum address.\n msg.sender,\n hex\"75\", // OP_DROP\n hex\"08\", // Byte length of blinding factor value.\n reveal.blindingFactor,\n hex\"75\", // OP_DROP\n hex\"76\", // OP_DUP\n hex\"a9\", // OP_HASH160\n hex\"14\", // Byte length of a compressed Bitcoin public key hash.\n reveal.walletPubKeyHash,\n hex\"87\", // OP_EQUAL\n hex\"63\", // OP_IF\n hex\"ac\", // OP_CHECKSIG\n hex\"67\", // OP_ELSE\n hex\"76\", // OP_DUP\n hex\"a9\", // OP_HASH160\n hex\"14\", // Byte length of a compressed Bitcoin public key hash.\n reveal.refundPubKeyHash,\n hex\"88\", // OP_EQUALVERIFY\n hex\"04\", // Byte length of refund locktime value.\n reveal.refundLocktime,\n hex\"b1\", // OP_CHECKLOCKTIMEVERIFY\n hex\"75\", // OP_DROP\n hex\"ac\", // OP_CHECKSIG\n hex\"68\" // OP_ENDIF\n );\n\n bytes memory fundingOutput = fundingTx\n .outputVector\n .extractOutputAtIndex(reveal.fundingOutputIndex);\n bytes memory fundingOutputHash = fundingOutput.extractHash();\n\n if (fundingOutputHash.length == 20) {\n // A 20-byte output hash is used by P2SH. That hash is constructed\n // by applying OP_HASH160 on the locking script. A 20-byte output\n // hash is used as well by P2PKH and P2WPKH (OP_HASH160 on the\n // public key). However, since we compare the actual output hash\n // with an expected locking script hash, this check will succeed only\n // for P2SH transaction type with expected script hash value. For\n // P2PKH and P2WPKH, it will fail on the output hash comparison with\n // the expected locking script hash.\n require(\n fundingOutputHash.slice20(0) == expectedScript.hash160View(),\n \"Wrong 20-byte script hash\"\n );\n } else if (fundingOutputHash.length == 32) {\n // A 32-byte output hash is used by P2WSH. That hash is constructed\n // by applying OP_SHA256 on the locking script.\n require(\n fundingOutputHash.toBytes32() == sha256(expectedScript),\n \"Wrong 32-byte script hash\"\n );\n } else {\n revert(\"Wrong script hash length\");\n }\n\n // Resulting TX hash is in native Bitcoin little-endian format.\n bytes32 fundingTxHash = abi\n .encodePacked(\n fundingTx.version,\n fundingTx.inputVector,\n fundingTx.outputVector,\n fundingTx.locktime\n )\n .hash256View();\n\n DepositRequest storage deposit = self.deposits[\n uint256(\n keccak256(\n abi.encodePacked(fundingTxHash, reveal.fundingOutputIndex)\n )\n )\n ];\n require(deposit.revealedAt == 0, \"Deposit already revealed\");\n\n uint64 fundingOutputAmount = fundingOutput.extractValue();\n\n require(\n fundingOutputAmount >= self.depositDustThreshold,\n \"Deposit amount too small\"\n );\n\n deposit.amount = fundingOutputAmount;\n deposit.depositor = msg.sender;\n /* solhint-disable-next-line not-rely-on-time */\n deposit.revealedAt = uint32(block.timestamp);\n deposit.vault = reveal.vault;\n deposit.treasuryFee = self.depositTreasuryFeeDivisor > 0\n ? fundingOutputAmount / self.depositTreasuryFeeDivisor\n : 0;\n // slither-disable-next-line reentrancy-events\n emit DepositRevealed(\n fundingTxHash,\n reveal.fundingOutputIndex,\n msg.sender,\n fundingOutputAmount,\n reveal.blindingFactor,\n reveal.walletPubKeyHash,\n reveal.refundPubKeyHash,\n reveal.refundLocktime,\n reveal.vault\n );\n }\n\n /// @notice Validates the deposit refund locktime. The validation passes\n /// successfully only if the deposit reveal is done respectively\n /// earlier than the moment when the deposit refund locktime is\n /// reached, i.e. the deposit become refundable. Reverts otherwise.\n /// @param refundLocktime The deposit refund locktime as 4-byte LE.\n /// @dev Requirements:\n /// - `refundLocktime` as integer must be >= 500M\n /// - `refundLocktime` must denote a timestamp that is at least\n /// `depositRevealAheadPeriod` seconds later than the moment\n /// of `block.timestamp`\n function validateDepositRefundLocktime(\n BridgeState.Storage storage self,\n bytes4 refundLocktime\n ) internal view {\n // Convert the refund locktime byte array to a LE integer. This is\n // the moment in time when the deposit become refundable.\n uint32 depositRefundableTimestamp = BTCUtils.reverseUint32(\n uint32(refundLocktime)\n );\n // According to https://developer.bitcoin.org/devguide/transactions.html#locktime-and-sequence-number\n // the locktime is parsed as a block number if less than 500M. We always\n // want to parse the locktime as an Unix timestamp so we allow only for\n // values bigger than or equal to 500M.\n require(\n depositRefundableTimestamp >= 500 * 1e6,\n \"Refund locktime must be a value >= 500M\"\n );\n // The deposit must be revealed before it becomes refundable.\n // This is because the sweeping wallet needs to have some time to\n // sweep the deposit and avoid a potential competition with the\n // depositor making the deposit refund.\n require(\n /* solhint-disable-next-line not-rely-on-time */\n block.timestamp + self.depositRevealAheadPeriod <=\n depositRefundableTimestamp,\n \"Deposit refund locktime is too close\"\n );\n }\n}\n"
|