@ocap/tx-pipeline 1.31.1 → 1.31.3

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.
Files changed (105) hide show
  1. package/esm/bridge-release-keys.d.mts +33 -0
  2. package/esm/bridge-release-keys.mjs +81 -0
  3. package/esm/bridge-reserves.d.mts +107 -0
  4. package/esm/bridge-reserves.mjs +242 -0
  5. package/esm/helpers/bridge-withdraw.d.mts +86 -0
  6. package/esm/helpers/bridge-withdraw.mjs +123 -0
  7. package/esm/helpers/replay-guard.d.mts +19 -1
  8. package/esm/helpers/replay-guard.mjs +39 -1
  9. package/esm/index.d.mts +3 -1
  10. package/esm/index.mjs +8 -6
  11. package/esm/legacy-protocol-sunset.d.mts +2 -2
  12. package/esm/legacy-protocol-sunset.mjs +5 -5
  13. package/esm/legacy-rollup-archive.d.mts +67 -0
  14. package/esm/legacy-rollup-archive.mjs +199 -0
  15. package/esm/library.d.mts +4 -4
  16. package/esm/library.mjs +3 -3
  17. package/esm/native-abt-exchange.d.mts +3 -0
  18. package/esm/native-abt-exchange.mjs +93 -46
  19. package/esm/pipes/bridge-release-gate.d.mts +30 -0
  20. package/esm/pipes/bridge-release-gate.mjs +143 -0
  21. package/esm/pipes/bridge-reserve-v2-gate.d.mts +53 -0
  22. package/esm/pipes/bridge-reserve-v2-gate.mjs +264 -0
  23. package/esm/pipes/decode-tx.mjs +29 -4
  24. package/esm/pipes/extract-signer.mjs +1 -1
  25. package/esm/pipes/extract-state.mjs +2 -2
  26. package/esm/pipes/post-execution-invariant-gate.d.mts +19 -2
  27. package/esm/pipes/post-execution-invariant-gate.mjs +121 -6
  28. package/esm/pipes/pre-flight-waf.d.mts +18 -1
  29. package/esm/pipes/pre-flight-waf.mjs +48 -13
  30. package/esm/pipes/update-owner.mjs +1 -1
  31. package/esm/pipes/verify-account-migration.mjs +1 -1
  32. package/esm/pipes/verify-delegation.mjs +49 -25
  33. package/esm/pipes/verify-multisig-v2.mjs +5 -4
  34. package/esm/pipes/verify-multisig.mjs +5 -4
  35. package/esm/pipes/verify-signature.d.mts +7 -1
  36. package/esm/pipes/verify-signature.mjs +119 -16
  37. package/esm/pipes/verify-signer.mjs +2 -2
  38. package/esm/pipes/verify-token-access.mjs +1 -1
  39. package/esm/pipes/verify-token-balance.mjs +1 -1
  40. package/esm/pipes/verify-tx-input.mjs +1 -1
  41. package/esm/pipes/verify-tx-size.mjs +1 -1
  42. package/esm/pipes/verify-tx.mjs +12 -5
  43. package/esm/super-suites-foundation.mjs +6 -6
  44. package/esm/transaction-block.d.mts +6 -2
  45. package/esm/transaction-block.mjs +282 -40
  46. package/esm/uniswap-router.d.mts +247 -1
  47. package/esm/uniswap-router.mjs +573 -2
  48. package/lib/bridge-release-keys.cjs +88 -0
  49. package/lib/bridge-release-keys.d.cts +33 -0
  50. package/lib/bridge-reserves.cjs +257 -0
  51. package/lib/bridge-reserves.d.cts +107 -0
  52. package/lib/helpers/bridge-withdraw.cjs +136 -0
  53. package/lib/helpers/bridge-withdraw.d.cts +86 -0
  54. package/lib/helpers/replay-guard.cjs +39 -0
  55. package/lib/helpers/replay-guard.d.cts +20 -2
  56. package/lib/index.cjs +25 -5
  57. package/lib/index.d.cts +3 -1
  58. package/lib/legacy-protocol-sunset.cjs +7 -7
  59. package/lib/legacy-protocol-sunset.d.cts +2 -2
  60. package/lib/legacy-rollup-archive.cjs +208 -0
  61. package/lib/legacy-rollup-archive.d.cts +67 -0
  62. package/lib/library.cjs +14 -68
  63. package/lib/library.d.cts +4 -4
  64. package/lib/native-abt-exchange.cjs +93 -46
  65. package/lib/native-abt-exchange.d.cts +3 -0
  66. package/lib/pipes/bridge-release-gate.cjs +145 -0
  67. package/lib/pipes/bridge-release-gate.d.cts +30 -0
  68. package/lib/pipes/bridge-reserve-v2-gate.cjs +273 -0
  69. package/lib/pipes/bridge-reserve-v2-gate.d.cts +53 -0
  70. package/lib/pipes/decode-itx.d.cts +1 -1
  71. package/lib/pipes/decode-tx.cjs +28 -3
  72. package/lib/pipes/decode-tx.d.cts +1 -1
  73. package/lib/pipes/extract-signer.cjs +1 -1
  74. package/lib/pipes/extract-state.cjs +3 -3
  75. package/lib/pipes/post-execution-invariant-gate.cjs +121 -4
  76. package/lib/pipes/post-execution-invariant-gate.d.cts +19 -2
  77. package/lib/pipes/pre-flight-waf.cjs +51 -13
  78. package/lib/pipes/pre-flight-waf.d.cts +19 -2
  79. package/lib/pipes/update-owner.cjs +1 -1
  80. package/lib/pipes/update-owner.d.cts +1 -1
  81. package/lib/pipes/verify-account-migration.cjs +1 -1
  82. package/lib/pipes/verify-delegation.cjs +50 -26
  83. package/lib/pipes/verify-multisig-v2.cjs +5 -4
  84. package/lib/pipes/verify-multisig.cjs +5 -4
  85. package/lib/pipes/verify-service-fee.d.cts +1 -1
  86. package/lib/pipes/verify-signature.cjs +118 -14
  87. package/lib/pipes/verify-signature.d.cts +8 -2
  88. package/lib/pipes/verify-signer.cjs +2 -2
  89. package/lib/pipes/verify-token-access.cjs +1 -1
  90. package/lib/pipes/verify-token-balance.cjs +1 -1
  91. package/lib/pipes/verify-tx-input.cjs +1 -1
  92. package/lib/pipes/verify-tx-size.cjs +1 -1
  93. package/lib/pipes/verify-tx-size.d.cts +1 -1
  94. package/lib/pipes/verify-tx.cjs +11 -5
  95. package/lib/pipes/verify-tx.d.cts +1 -1
  96. package/lib/super-suites-foundation.cjs +6 -6
  97. package/lib/transaction-block.cjs +282 -40
  98. package/lib/transaction-block.d.cts +6 -2
  99. package/lib/uniswap-router.cjs +576 -1
  100. package/lib/uniswap-router.d.cts +247 -1
  101. package/package.json +10 -10
  102. package/esm/evm-simplified-bridge.d.mts +0 -1370
  103. package/esm/evm-simplified-bridge.mjs +0 -3875
  104. package/lib/evm-simplified-bridge.cjs +0 -3943
  105. package/lib/evm-simplified-bridge.d.cts +0 -1370
@@ -1,3875 +0,0 @@
1
- import { Hasher } from "@ocap/mcrypto";
2
- import { CustomError } from "@ocap/util/lib/error";
3
- import { createHmac, timingSafeEqual } from "node:crypto";
4
- import elliptic from "elliptic";
5
-
6
- //#region src/evm-simplified-bridge.ts
7
- const keccak256 = Hasher.Keccak.hash256;
8
- const secp256k1Curve = new elliptic.ec("secp256k1");
9
- const ErrorCode = {
10
- InvalidBridge: "INVALID_EVM_SIMPLIFIED_BRIDGE",
11
- ForbiddenBridge: "FORBIDDEN_EVM_SIMPLIFIED_BRIDGE"
12
- };
13
- const DEFAULT_MIN_EVM_CONFIRMATIONS = 12;
14
- const DEFAULT_MAX_ROLLUP_BLOCK_SIZE = 256;
15
- const MAX_EDGE_WEBHOOK_SKEW_SECONDS = 300;
16
- const MAX_EDGE_WEBHOOK_BODY_BYTES = 65536;
17
- const MAX_TRACKED_WEBHOOK_NONCES = 4096;
18
- const MIN_DIRECT_VOUCHER_TTL_SECONDS = 300;
19
- const MAX_DIRECT_VOUCHER_TTL_SECONDS = 604800;
20
- const DEFAULT_WITHDRAW_TIMELOCK_DELAY_SECONDS = 86400;
21
- const DEFAULT_ROLLUP_SUNSET_ACTIVATION_HEIGHT = 1;
22
- const DEPRECATED_ROLLUP_PROTOCOL_TYPE_URLS = Object.freeze([
23
- "fg:t:create_rollup",
24
- "fg:t:update_rollup",
25
- "fg:t:join_rollup",
26
- "fg:t:leave_rollup",
27
- "fg:t:create_rollup_block",
28
- "fg:t:claim_block_reward",
29
- "fg:t:pause_rollup",
30
- "fg:t:resume_rollup"
31
- ]);
32
- const EIP712_BRIDGE_DOMAIN_NAME = "ArcEvmBridgeGateway";
33
- const EIP712_BRIDGE_DOMAIN_VERSION = "1";
34
- const DEFAULT_VERIFYING_CONTRACT_ADDRESS = "0x0000000000000000000000000000000000001241";
35
- const EMPTY_ROLLUP_MERKLE_ROOT = "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
36
- const ZERO_BYTES32_HASH = "0x0000000000000000000000000000000000000000000000000000000000000000";
37
- const ZERO_EVM_ADDRESS = "0x0000000000000000000000000000000000000000";
38
- const BYTES32_HEX_REGEX = /^0x[0-9a-fA-F]{64}$/;
39
- const EVM_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/;
40
- const CANONICAL_UINT256_DECIMAL_REGEX = /^(0|[1-9]\d{0,77})$/;
41
- /**
42
- * Issue #1241 & #1243:
43
- * Redesigned Simplified EVM Bridge Contract Specification (`ArcEvmBridgeGateway.sol`).
44
- * Implements the Dual-Track KISS architecture + 3-Layer Anti-Vault-Drain Security + EIP-712 Typed Data Signing:
45
- * 1. `payForOcapService`: Pay-Where-You-Are direct cashier (ERC-20 ABT / USDC stays on EVM, service delivered on OCAP).
46
- * 2. `depositForNativeAbt` & `claimWithdrawWithDirectVoucher` (Zero-Rollup-Block EIP-712 Pull Mode) / `claimWithdrawWithMerkleProof`.
47
- */
48
- const ARC_EVM_BRIDGE_GATEWAY_SOLIDITY_SPEC = `// SPDX-License-Identifier: MIT
49
- pragma solidity ^0.8.24;
50
-
51
- interface IERC20Minimal {
52
- function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
53
- function transfer(address recipient, uint256 amount) external returns (bool);
54
- }
55
-
56
- contract ArcEvmBridgeGateway {
57
- bytes32 public constant EIP712_DOMAIN_TYPEHASH =
58
- keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
59
- bytes32 public constant DIRECT_WITHDRAW_TYPEHASH =
60
- keccak256("DirectWithdrawVoucher(bytes32 bridgeIdHash,bytes32 ocapTxHash,address recipient,uint256 amount,uint256 expiresAt)");
61
-
62
- address public immutable canonicalAbtToken;
63
- address public immutable guardian;
64
- bytes32 public immutable bridgeIdHash;
65
- bytes32 public immutable DOMAIN_SEPARATOR;
66
- uint256 public immutable minValidatorSignatures;
67
- uint256 public immutable maxDailyWithdrawCap;
68
- uint256 public immutable largeWithdrawThreshold;
69
- uint256 public constant TIMELOCK_DELAY = 24 hours;
70
-
71
- bool public paused;
72
- uint256 public latestBlockHeight;
73
- bytes32 public latestBlockHash;
74
- uint256 public cumulativeDepositedAbt;
75
- uint256 public cumulativeWithdrawnAbt;
76
-
77
- mapping(address => bool) public isBridgeValidator;
78
- mapping(uint256 => bytes32) public blockMerkleRoots;
79
- mapping(bytes32 => bool) public processedServiceOrders;
80
- mapping(bytes32 => bool) public claimedWithdrawTxs;
81
- mapping(bytes32 => bool) public cancelledWithdrawTxs;
82
- mapping(bytes32 => uint256) public timelockUnlockAt;
83
- mapping(uint256 => uint256) public dailyWithdrawnAbt;
84
- mapping(address => bool) public supportedServiceTokens;
85
-
86
- event OcapServicePaid(
87
- bytes32 indexed orderId,
88
- address indexed payer,
89
- string recipientDid,
90
- string serviceDid,
91
- address paymentToken,
92
- uint256 amount
93
- );
94
-
95
- event NativeAbtDepositLocked(
96
- address indexed depositor,
97
- string recipientDid,
98
- uint256 amount,
99
- uint256 cumulativeDepositedAbt
100
- );
101
-
102
- event RollupBlockSubmitted(
103
- uint256 indexed height,
104
- bytes32 previousHash,
105
- bytes32 merkleRoot,
106
- bytes32 txsHash,
107
- bytes32 blockHash
108
- );
109
-
110
- event LargeWithdrawTimelocked(
111
- bytes32 indexed ocapTxHash,
112
- address indexed recipient,
113
- uint256 amount,
114
- uint256 unlockAt
115
- );
116
-
117
- event NativeAbtWithdrawClaimed(
118
- bytes32 indexed ocapTxHash,
119
- address indexed recipient,
120
- uint256 amount,
121
- uint256 blockHeight
122
- );
123
-
124
- constructor(
125
- address _canonicalAbtToken,
126
- address _guardian,
127
- bytes32 _bridgeIdHash,
128
- bytes32 _genesisBlockHash,
129
- address[] memory _validators,
130
- uint256 _minValidatorSignatures,
131
- uint256 _maxDailyWithdrawCap,
132
- uint256 _largeWithdrawThreshold
133
- ) {
134
- require(_canonicalAbtToken != address(0) && _guardian != address(0), "ZERO_ADDRESS");
135
- require(_validators.length >= 2 && _minValidatorSignatures >= 2 && _minValidatorSignatures <= _validators.length, "MULTI_SIGNER_QUORUM_REQUIRED");
136
- require(_maxDailyWithdrawCap > 0 && _largeWithdrawThreshold > 0, "INVALID_CAPS");
137
- canonicalAbtToken = _canonicalAbtToken;
138
- guardian = _guardian;
139
- bridgeIdHash = _bridgeIdHash;
140
- minValidatorSignatures = _minValidatorSignatures;
141
- maxDailyWithdrawCap = _maxDailyWithdrawCap;
142
- largeWithdrawThreshold = _largeWithdrawThreshold;
143
- DOMAIN_SEPARATOR = keccak256(
144
- abi.encode(
145
- EIP712_DOMAIN_TYPEHASH,
146
- keccak256(bytes("ArcEvmBridgeGateway")),
147
- keccak256(bytes("1")),
148
- block.chainid,
149
- address(this)
150
- )
151
- );
152
- supportedServiceTokens[_canonicalAbtToken] = true;
153
- latestBlockHash = _genesisBlockHash;
154
- for (uint256 i = 0; i < _validators.length; i++) {
155
- require(_validators[i] != address(0) && !isBridgeValidator[_validators[i]], "INVALID_VALIDATOR");
156
- isBridgeValidator[_validators[i]] = true;
157
- }
158
- }
159
-
160
- function setPaused(bool _paused) external {
161
- require(msg.sender == guardian, "ONLY_GUARDIAN");
162
- paused = _paused;
163
- }
164
-
165
- function cancelFraudulentWithdraw(bytes32 ocapTxHash) external {
166
- require(msg.sender == guardian, "ONLY_GUARDIAN");
167
- require(!claimedWithdrawTxs[ocapTxHash], "ALREADY_CLAIMED");
168
- cancelledWithdrawTxs[ocapTxHash] = true;
169
- }
170
-
171
- // Track 1: Pay-Where-You-Are Direct Service Cashier (Zero Foreign Asset Bridge)
172
- function payForOcapService(
173
- bytes32 orderId,
174
- string calldata recipientDid,
175
- string calldata serviceDid,
176
- address paymentToken,
177
- uint256 amount
178
- ) external {
179
- require(!paused, "BRIDGE_PAUSED");
180
- require(orderId != bytes32(0) && !processedServiceOrders[orderId], "INVALID_OR_DUPLICATE_ORDER");
181
- require(supportedServiceTokens[paymentToken], "UNSUPPORTED_PAYMENT_TOKEN");
182
- require(amount > 0 && bytes(recipientDid).length > 0 && bytes(serviceDid).length > 0, "INVALID_ARGS");
183
-
184
- processedServiceOrders[orderId] = true;
185
- require(IERC20Minimal(paymentToken).transferFrom(msg.sender, address(this), amount), "TRANSFER_FAILED");
186
- emit OcapServicePaid(orderId, msg.sender, recipientDid, serviceDid, paymentToken, amount);
187
- }
188
-
189
- // Track 2A: Canonical ERC-20 ABT -> OCAP Native ABT 1:1 Deposit
190
- function depositForNativeAbt(string calldata recipientDid, uint256 amount) external {
191
- require(!paused, "BRIDGE_PAUSED");
192
- require(amount > 0 && bytes(recipientDid).length > 0, "INVALID_DEPOSIT");
193
- cumulativeDepositedAbt += amount;
194
- require(IERC20Minimal(canonicalAbtToken).transferFrom(msg.sender, address(this), amount), "TRANSFER_FAILED");
195
- emit NativeAbtDepositLocked(msg.sender, recipientDid, amount, cumulativeDepositedAbt);
196
- }
197
-
198
- // Track 2B (Primary — Zero-Rollup-Block EIP-712 Pull Mode):
199
- // Direct Threshold-Signed Withdraw Voucher (User-Pays-Claim-Gas, 0 RollupBlock / 0 Operator ETH Gas)
200
- function claimWithdrawWithDirectVoucher(
201
- bytes32 ocapTxHash,
202
- address to,
203
- uint256 amount,
204
- uint256 expiresAt,
205
- bytes32 voucherDigest,
206
- uint8[] calldata v,
207
- bytes32[] calldata r,
208
- bytes32[] calldata s
209
- ) external {
210
- require(!paused, "BRIDGE_PAUSED");
211
- require(!claimedWithdrawTxs[ocapTxHash] && !cancelledWithdrawTxs[ocapTxHash], "ALREADY_CLAIMED_OR_CANCELLED");
212
- require(to != address(0) && amount > 0, "INVALID_RECIPIENT_OR_AMOUNT");
213
- require(block.timestamp <= expiresAt, "VOUCHER_EXPIRED");
214
- require(cumulativeWithdrawnAbt + amount <= cumulativeDepositedAbt, "CANARY_RESERVE_WATERMARK_EXCEEDED");
215
-
216
- bytes32 structHash = keccak256(
217
- abi.encode(DIRECT_WITHDRAW_TYPEHASH, bridgeIdHash, ocapTxHash, to, amount, expiresAt)
218
- );
219
- bytes32 expectedDigest = keccak256(abi.encodePacked("\\x19\\x01", DOMAIN_SEPARATOR, structHash));
220
- require(voucherDigest == expectedDigest, "INVALID_EIP712_VOUCHER_DIGEST");
221
- _verifyValidatorQuorum(voucherDigest, v, r, s);
222
-
223
- if (amount >= largeWithdrawThreshold) {
224
- uint256 unlockAt = timelockUnlockAt[ocapTxHash];
225
- if (unlockAt == 0) {
226
- timelockUnlockAt[ocapTxHash] = block.timestamp + TIMELOCK_DELAY;
227
- emit LargeWithdrawTimelocked(ocapTxHash, to, amount, timelockUnlockAt[ocapTxHash]);
228
- return;
229
- }
230
- require(block.timestamp >= unlockAt, "TIMELOCK_ACTIVE");
231
- }
232
-
233
- uint256 currentDay = block.timestamp / 1 days;
234
- require(dailyWithdrawnAbt[currentDay] + amount <= maxDailyWithdrawCap, "DAILY_WITHDRAW_CAP_EXCEEDED");
235
- dailyWithdrawnAbt[currentDay] += amount;
236
-
237
- claimedWithdrawTxs[ocapTxHash] = true;
238
- cumulativeWithdrawnAbt += amount;
239
- require(IERC20Minimal(canonicalAbtToken).transfer(to, amount), "TRANSFER_FAILED");
240
- emit NativeAbtWithdrawClaimed(ocapTxHash, to, amount, 0);
241
- }
242
-
243
- // Track 2B (Legacy Compatibility): Submit Rollup Merkle Block & Claim with Merkle Proof
244
- function submitRollupBlock(
245
- uint256 height,
246
- bytes32 previousHash,
247
- bytes32 merkleRoot,
248
- bytes32 txsHash,
249
- uint8[] calldata v,
250
- bytes32[] calldata r,
251
- bytes32[] calldata s
252
- ) external {
253
- require(!paused, "BRIDGE_PAUSED");
254
- require(height == latestBlockHeight + 1, "INVALID_HEIGHT");
255
- require(previousHash == latestBlockHash, "INVALID_PREVIOUS_HASH");
256
- bytes32 blockHash = keccak256(abi.encodePacked(height, previousHash, merkleRoot, txsHash));
257
- _verifyValidatorQuorum(blockHash, v, r, s);
258
-
259
- latestBlockHeight = height;
260
- latestBlockHash = blockHash;
261
- blockMerkleRoots[height] = merkleRoot;
262
- emit RollupBlockSubmitted(height, previousHash, merkleRoot, txsHash, blockHash);
263
- }
264
-
265
- function claimWithdrawWithMerkleProof(
266
- bytes32 ocapTxHash,
267
- address to,
268
- uint256 amount,
269
- uint256 blockHeight,
270
- bytes32[] calldata proof
271
- ) external {
272
- require(!paused, "BRIDGE_PAUSED");
273
- require(!claimedWithdrawTxs[ocapTxHash] && !cancelledWithdrawTxs[ocapTxHash], "ALREADY_CLAIMED_OR_CANCELLED");
274
- require(to != address(0) && amount > 0, "INVALID_RECIPIENT_OR_AMOUNT");
275
- require(cumulativeWithdrawnAbt + amount <= cumulativeDepositedAbt, "CANARY_RESERVE_WATERMARK_EXCEEDED");
276
-
277
- bytes32 root = blockMerkleRoots[blockHeight];
278
- require(root != bytes32(0) && root != bytes32(type(uint256).max), "INVALID_BLOCK_ROOT");
279
- bytes32 leaf = keccak256(abi.encodePacked(ocapTxHash, to, amount));
280
- require(_verifyMerkleProof(proof, root, leaf), "INVALID_MERKLE_PROOF");
281
-
282
- if (amount >= largeWithdrawThreshold) {
283
- uint256 unlockAt = timelockUnlockAt[ocapTxHash];
284
- if (unlockAt == 0) {
285
- timelockUnlockAt[ocapTxHash] = block.timestamp + TIMELOCK_DELAY;
286
- emit LargeWithdrawTimelocked(ocapTxHash, to, amount, timelockUnlockAt[ocapTxHash]);
287
- return;
288
- }
289
- require(block.timestamp >= unlockAt, "TIMELOCK_ACTIVE");
290
- }
291
-
292
- uint256 currentDay = block.timestamp / 1 days;
293
- require(dailyWithdrawnAbt[currentDay] + amount <= maxDailyWithdrawCap, "DAILY_WITHDRAW_CAP_EXCEEDED");
294
- dailyWithdrawnAbt[currentDay] += amount;
295
-
296
- claimedWithdrawTxs[ocapTxHash] = true;
297
- cumulativeWithdrawnAbt += amount;
298
- require(IERC20Minimal(canonicalAbtToken).transfer(to, amount), "TRANSFER_FAILED");
299
- emit NativeAbtWithdrawClaimed(ocapTxHash, to, amount, blockHeight);
300
- }
301
-
302
- function _verifyValidatorQuorum(
303
- bytes32 digest,
304
- uint8[] calldata v,
305
- bytes32[] calldata r,
306
- bytes32[] calldata s
307
- ) internal view {
308
- require(v.length >= minValidatorSignatures && v.length == r.length && v.length == s.length, "QUORUM_NOT_MET");
309
- address lastSigner = address(0);
310
- for (uint256 i = 0; i < v.length; i++) {
311
- address signer = ecrecover(digest, v[i], r[i], s[i]);
312
- require(signer > lastSigner && isBridgeValidator[signer], "INVALID_OR_UNSORTED_SIGNER");
313
- lastSigner = signer;
314
- }
315
- }
316
-
317
- function _verifyMerkleProof(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
318
- bytes32 computedHash = leaf;
319
- for (uint256 i = 0; i < proof.length; i++) {
320
- bytes32 proofElement = proof[i];
321
- if (computedHash <= proofElement) {
322
- computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
323
- } else {
324
- computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
325
- }
326
- }
327
- return computedHash == root;
328
- }
329
- }
330
- `;
331
- function assertCleanString(value, label) {
332
- if (typeof value !== "string" || value.trim().length === 0) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} must be a non-empty string`);
333
- const trimmed = value.trim();
334
- if (trimmed !== value || /[\s/\\?#%]|::|->/.test(trimmed)) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} contains invalid characters`);
335
- return trimmed;
336
- }
337
- function assertBytes32Hex(value, label) {
338
- if (typeof value !== "string" || !BYTES32_HEX_REGEX.test(value)) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} must be a 32-byte 0x-prefixed hex string`);
339
- return value.toLowerCase();
340
- }
341
- function assertEvmAddress(value, label) {
342
- if (typeof value !== "string" || !EVM_ADDRESS_REGEX.test(value)) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} must be a 20-byte 0x-prefixed EVM address`);
343
- const normalized = value.toLowerCase();
344
- if (normalized === ZERO_EVM_ADDRESS) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: ${label} cannot be the zero address`);
345
- return normalized;
346
- }
347
- function uint256ToHex64(value) {
348
- const big = typeof value === "number" ? BigInt(value) : value;
349
- if (big < 0n || big >= 1n << 256n) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: uint256 out of range");
350
- return big.toString(16).padStart(64, "0");
351
- }
352
- function parseStrictUint256JsonValue(value, label) {
353
- if (typeof value === "bigint") {
354
- if (value < 0n || value >= 1n << 256n) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} out of uint256 range`);
355
- return value;
356
- }
357
- if (typeof value === "string" && CANONICAL_UINT256_DECIMAL_REGEX.test(value)) {
358
- const big = BigInt(value);
359
- if (big < 0n || big >= 1n << 256n) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} out of uint256 range`);
360
- return big;
361
- }
362
- throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} must be a canonical base-10 uint256 string`);
363
- }
364
- /**
365
- * Computes the `@ocap/merkle-tree` compatible packed withdraw leaf preimage:
366
- * `encodePacked(bytes32 txHash, address to, uint256 amount)`
367
- */
368
- function encodeEvmBridgeWithdrawPackedPreimage(txHash, toEvmAddress, amount) {
369
- return `0x${assertBytes32Hex(txHash, "txHash").slice(2)}${assertEvmAddress(toEvmAddress, "toEvmAddress").slice(2)}${uint256ToHex64(amount)}`;
370
- }
371
- /**
372
- * Computes the `@ocap/merkle-tree` leaf hash (`keccak256(encodePacked(bytes32, address, uint256))`).
373
- */
374
- function computeEvmBridgeWithdrawLeafHash(txHash, toEvmAddress, amount) {
375
- return keccak256(encodeEvmBridgeWithdrawPackedPreimage(txHash, toEvmAddress, amount)).toLowerCase();
376
- }
377
- /**
378
- * Computes the `@ocap/merkle-tree` compatible `getListHash(txHashes)`.
379
- */
380
- function computeEvmBridgeTxsHash(txHashes) {
381
- if (txHashes.length === 0) return ZERO_BYTES32_HASH;
382
- return keccak256(`0x${txHashes.map((h) => assertBytes32Hex(h, "txHash").slice(2)).join("")}`).toLowerCase();
383
- }
384
- /**
385
- * Computes the `@ocap/merkle-tree` compatible `getBlockHash`:
386
- * `keccak256(encodePacked(uint256 height, bytes32 previousHash, bytes32 merkleRoot, bytes32 txsHash))`
387
- */
388
- function computeEvmBridgeBlockHash(block) {
389
- if (!Number.isSafeInteger(block.height) || block.height <= 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: block height must be a positive safe integer");
390
- return keccak256(`0x${uint256ToHex64(block.height)}${assertBytes32Hex(block.previousHash, "previousHash").slice(2)}${assertBytes32Hex(block.merkleRoot, "merkleRoot").slice(2)}${assertBytes32Hex(block.txsHash, "txsHash").slice(2)}`).toLowerCase();
391
- }
392
- /**
393
- * Deterministic sorted-pair Keccak-256 Merkle tree compatible with `@ocap/merkle-tree` and OpenZeppelin `MerkleProof`.
394
- */
395
- function buildEvmBridgeMerkleTree(withdrawTxs) {
396
- if (withdrawTxs.length === 0) return {
397
- merkleRoot: EMPTY_ROLLUP_MERKLE_ROOT,
398
- leaves: [],
399
- getProofForLeaf: () => []
400
- };
401
- const rawLeafBuffers = withdrawTxs.map((tx) => Buffer.from(computeEvmBridgeWithdrawLeafHash(tx.ocapTxHash, tx.recipientEvmAddress, tx.amount).slice(2), "hex"));
402
- rawLeafBuffers.sort(Buffer.compare);
403
- const uniqueLeaves = rawLeafBuffers.filter((el, idx) => idx === 0 || !rawLeafBuffers[idx - 1].equals(el));
404
- const layers = [uniqueLeaves];
405
- while (layers[layers.length - 1].length > 1) {
406
- const current = layers[layers.length - 1];
407
- const nextLayer = [];
408
- for (let i = 0; i < current.length; i += 2) {
409
- const left = current[i];
410
- const right = current[i + 1];
411
- if (!right) nextLayer.push(left);
412
- else {
413
- const parentHex = keccak256(`0x${Buffer.concat([left, right].sort(Buffer.compare)).toString("hex")}`).slice(2);
414
- nextLayer.push(Buffer.from(parentHex, "hex"));
415
- }
416
- }
417
- layers.push(nextLayer);
418
- }
419
- const merkleRoot = `0x${layers[layers.length - 1][0].toString("hex").toLowerCase()}`;
420
- const leaves = uniqueLeaves.map((b) => `0x${b.toString("hex").toLowerCase()}`);
421
- const getProofForLeaf = (leafHash) => {
422
- const targetBuf = Buffer.from(assertBytes32Hex(leafHash, "leafHash").slice(2), "hex");
423
- let idx = uniqueLeaves.findIndex((b) => b.equals(targetBuf));
424
- if (idx === -1) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: leaf ${leafHash} not found in Merkle tree`);
425
- const proof = [];
426
- for (const layer of layers) {
427
- const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1;
428
- if (pairIdx < layer.length) proof.push(`0x${layer[pairIdx].toString("hex").toLowerCase()}`);
429
- idx = Math.floor(idx / 2);
430
- }
431
- return proof;
432
- };
433
- return {
434
- merkleRoot,
435
- leaves,
436
- getProofForLeaf
437
- };
438
- }
439
- /**
440
- * Verifies a sorted-pair Keccak-256 Merkle proof against `merkleRoot`.
441
- */
442
- function verifyEvmBridgeMerkleProof(proof, merkleRoot, leafHash) {
443
- if (!Array.isArray(proof) || !BYTES32_HEX_REGEX.test(merkleRoot) || !BYTES32_HEX_REGEX.test(leafHash)) return false;
444
- if (merkleRoot.toLowerCase() === EMPTY_ROLLUP_MERKLE_ROOT) return false;
445
- let computed = Buffer.from(leafHash.slice(2).toLowerCase(), "hex");
446
- for (const p of proof) {
447
- if (typeof p !== "string" || !BYTES32_HEX_REGEX.test(p)) return false;
448
- const sibling = Buffer.from(p.slice(2).toLowerCase(), "hex");
449
- const parentHex = keccak256(`0x${Buffer.concat([computed, sibling].sort(Buffer.compare)).toString("hex")}`).slice(2);
450
- computed = Buffer.from(parentHex, "hex");
451
- }
452
- return `0x${computed.toString("hex").toLowerCase()}` === merkleRoot.toLowerCase();
453
- }
454
- /**
455
- * Computes the expected validator signature digest for a Rollup block.
456
- */
457
- function computeValidatorBlockSignatureDigest(bridgeId, rollupAddress, blockHash, validatorDid) {
458
- const payload = `ocap:evm-simplified-bridge:v1:${bridgeId}:${rollupAddress}:${blockHash.toLowerCase()}:${validatorDid}`;
459
- return keccak256(`0x${Buffer.from(payload, "utf8").toString("hex")}`).toLowerCase();
460
- }
461
- function utf8Keccak256Hex(text) {
462
- return keccak256(`0x${Buffer.from(text, "utf8").toString("hex")}`).toLowerCase();
463
- }
464
- const EIP712_DOMAIN_TYPEHASH = utf8Keccak256Hex("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
465
- const DIRECT_WITHDRAW_TYPEHASH = utf8Keccak256Hex("DirectWithdrawVoucher(bytes32 bridgeIdHash,bytes32 ocapTxHash,address recipient,uint256 amount,uint256 expiresAt)");
466
- /**
467
- * Computes the standard EIP-712 `DOMAIN_SEPARATOR` matching `ArcEvmBridgeGateway.sol`:
468
- * `keccak256(abi.encode(EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(version)), chainId, verifyingContract))`
469
- */
470
- function computeEip712BridgeDomainSeparator(params) {
471
- const name = params.name ?? EIP712_BRIDGE_DOMAIN_NAME;
472
- const version = params.version ?? EIP712_BRIDGE_DOMAIN_VERSION;
473
- const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
474
- const verifyingContractAddress = assertEvmAddress(params.verifyingContractAddress ?? DEFAULT_VERIFYING_CONTRACT_ADDRESS, "verifyingContractAddress");
475
- const nameHashHex = utf8Keccak256Hex(name).slice(2);
476
- const versionHashHex = utf8Keccak256Hex(version).slice(2);
477
- const chainIdHex64 = CANONICAL_UINT256_DECIMAL_REGEX.test(evmChainId) ? uint256ToHex64(BigInt(evmChainId)) : utf8Keccak256Hex(evmChainId).slice(2);
478
- const contractWordHex64 = verifyingContractAddress.slice(2).padStart(64, "0");
479
- return keccak256(`0x${EIP712_DOMAIN_TYPEHASH.slice(2)}${nameHashHex}${versionHashHex}${chainIdHex64}${contractWordHex64}`).toLowerCase();
480
- }
481
- /**
482
- * Computes the standard EIP-712 `structHash` for `DirectWithdrawVoucher` matching `ArcEvmBridgeGateway.sol`:
483
- * `keccak256(abi.encode(DIRECT_WITHDRAW_TYPEHASH, keccak256(bytes(bridgeId)), ocapTxHash, recipient, amount, expiresAt))`
484
- */
485
- function computeEip712WithdrawStructHash(params) {
486
- const bridgeId = assertCleanString(params.bridgeId, "bridgeId");
487
- const ocapTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
488
- if (ocapTxHash === ZERO_BYTES32_HASH) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: ocapTxHash cannot be zero bytes32");
489
- const recipientEvmAddress = assertEvmAddress(params.recipientEvmAddress, "recipientEvmAddress");
490
- if (typeof params.amount !== "bigint" || params.amount <= 0n) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: voucher amount must be > 0n");
491
- if (!Number.isSafeInteger(params.expiresAtUnixSeconds) || params.expiresAtUnixSeconds <= 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: expiresAtUnixSeconds must be a positive integer");
492
- const bridgeIdHashHex = utf8Keccak256Hex(bridgeId).slice(2);
493
- const recipientWordHex64 = recipientEvmAddress.slice(2).padStart(64, "0");
494
- const amountHex64 = uint256ToHex64(params.amount);
495
- const expiresHex64 = uint256ToHex64(params.expiresAtUnixSeconds);
496
- return keccak256(`0x${DIRECT_WITHDRAW_TYPEHASH.slice(2)}${bridgeIdHashHex}${ocapTxHash.slice(2)}${recipientWordHex64}${amountHex64}${expiresHex64}`).toLowerCase();
497
- }
498
- /**
499
- * Computes the deterministic EIP-712 Zero-Rollup-Block Direct Withdraw Voucher Digest (`\x19\x01 || DOMAIN_SEPARATOR || structHash`):
500
- * binds `(bridgeId, evmChainId, verifyingContractAddress, ocapTxHash, recipientEvmAddress, amount, expiresAtUnixSeconds)`
501
- * so the withdrawing user can claim ERC-20 ABT directly on Ethereum/Base (`claimWithdrawWithDirectVoucher`)
502
- * without waiting for any RollupBlock batch or operator-paid Ethereum transactions.
503
- */
504
- function computeDirectWithdrawVoucherDigest(params) {
505
- const domainSeparator = computeEip712BridgeDomainSeparator({
506
- evmChainId: params.evmChainId,
507
- verifyingContractAddress: params.verifyingContractAddress
508
- });
509
- const structHash = computeEip712WithdrawStructHash({
510
- bridgeId: params.bridgeId,
511
- ocapTxHash: params.ocapTxHash,
512
- recipientEvmAddress: params.recipientEvmAddress,
513
- amount: params.amount,
514
- expiresAtUnixSeconds: params.expiresAtUnixSeconds
515
- });
516
- return keccak256(`0x1901${domainSeparator.slice(2)}${structHash.slice(2)}`).toLowerCase();
517
- }
518
- /**
519
- * Computes the expected validator signature digest for a Zero-Rollup-Block Direct Withdraw Voucher.
520
- */
521
- function computeValidatorVoucherSignatureDigest(bridgeId, voucherDigest, validatorDid) {
522
- const payload = `ocap:evm-direct-withdraw-sig:v1:${assertCleanString(bridgeId, "bridgeId")}:${assertBytes32Hex(voucherDigest, "voucherDigest")}:${assertCleanString(validatorDid, "validatorDid")}`;
523
- return keccak256(`0x${Buffer.from(payload, "utf8").toString("hex")}`).toLowerCase();
524
- }
525
- /**
526
- * Verifies a `DirectWithdrawVoucher` against the bridge EIP-712 domain, validator set, and quorum threshold.
527
- */
528
- function verifyDirectWithdrawVoucher(voucher, options) {
529
- try {
530
- if (!voucher || typeof voucher !== "object" || voucher.cancelled === true) return false;
531
- if (!Number.isSafeInteger(options.minValidatorSignatures) || options.minValidatorSignatures < 1 || options.minValidatorSignatures > options.validatorDids.length) return false;
532
- if (voucher.bridgeId !== options.bridgeId) return false;
533
- const expectedVerifyingContract = assertEvmAddress(options.verifyingContractAddress ?? voucher.verifyingContractAddress ?? DEFAULT_VERIFYING_CONTRACT_ADDRESS, "verifyingContractAddress");
534
- if (voucher.verifyingContractAddress && voucher.verifyingContractAddress.toLowerCase() !== expectedVerifyingContract) return false;
535
- assertCleanString(voucher.fromDid, "fromDid");
536
- if (!options.allowedEvmChainIds.includes(voucher.evmChainId)) return false;
537
- if (!Number.isSafeInteger(voucher.issuedAtUnixSeconds) || voucher.issuedAtUnixSeconds <= 0 || !Number.isSafeInteger(voucher.expiresAtUnixSeconds)) return false;
538
- const ttl = voucher.expiresAtUnixSeconds - voucher.issuedAtUnixSeconds;
539
- if (ttl < MIN_DIRECT_VOUCHER_TTL_SECONDS || ttl > MAX_DIRECT_VOUCHER_TTL_SECONDS) return false;
540
- if (options.nowUnixSeconds !== void 0 && options.nowUnixSeconds > voucher.expiresAtUnixSeconds) return false;
541
- if (!Array.isArray(voucher.validatorSignatures) || !Array.isArray(voucher.validatorSigners) || voucher.validatorSigners.length !== voucher.validatorSignatures.length) return false;
542
- const expectedDomainSeparator = computeEip712BridgeDomainSeparator({
543
- evmChainId: voucher.evmChainId,
544
- verifyingContractAddress: expectedVerifyingContract
545
- });
546
- const expectedStructHash = computeEip712WithdrawStructHash({
547
- bridgeId: voucher.bridgeId,
548
- ocapTxHash: voucher.ocapTxHash,
549
- recipientEvmAddress: voucher.recipientEvmAddress,
550
- amount: voucher.amount,
551
- expiresAtUnixSeconds: voucher.expiresAtUnixSeconds
552
- });
553
- const expectedDigest = keccak256(`0x1901${expectedDomainSeparator.slice(2)}${expectedStructHash.slice(2)}`).toLowerCase();
554
- if (voucher.voucherDigest.toLowerCase() !== expectedDigest) return false;
555
- if (voucher.eip712DomainSeparator && voucher.eip712DomainSeparator.toLowerCase() !== expectedDomainSeparator) return false;
556
- if (voucher.eip712StructHash && voucher.eip712StructHash.toLowerCase() !== expectedStructHash) return false;
557
- const validatorSet = new Set(options.validatorDids);
558
- const seen = /* @__PURE__ */ new Set();
559
- for (let i = 0; i < voucher.validatorSignatures.length; i++) {
560
- const sig = voucher.validatorSignatures[i];
561
- if (!sig || voucher.validatorSigners[i] !== sig.validatorDid) return false;
562
- if (!validatorSet.has(sig.validatorDid) || seen.has(sig.validatorDid)) return false;
563
- const expectedSig = computeValidatorVoucherSignatureDigest(voucher.bridgeId, expectedDigest, sig.validatorDid);
564
- if (sig.signatureDigest.toLowerCase() !== expectedSig) return false;
565
- seen.add(sig.validatorDid);
566
- }
567
- return seen.size >= options.minValidatorSignatures;
568
- } catch {
569
- return false;
570
- }
571
- }
572
- const DEPRECATED_ROLLUP_PROTOCOL_SET = new Set(DEPRECATED_ROLLUP_PROTOCOL_TYPE_URLS);
573
- function normalizeRollupProtocolTypeUrl(rawTypeUrl) {
574
- if (typeof rawTypeUrl !== "string") return "";
575
- const trimmed = rawTypeUrl.trim();
576
- if (!trimmed) return "";
577
- const snakeCased = trimmed.replace(/^(?:type\.googleapis\.com\/)?(?:forge_abi\.)?(?:fg:t:|fg:x:tx:)?/i, "").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase().replace(/_tx$/, "");
578
- if (!snakeCased) return "";
579
- return `fg:t:${snakeCased}`;
580
- }
581
- /**
582
- * Issue #1245:
583
- * Returns true if `typeUrl` belongs to the 8 deprecated Rollup write protocols
584
- * (`create_rollup`, `update_rollup`, `join_rollup`, `leave_rollup`, `create_rollup_block`,
585
- * `claim_block_reward`, `pause_rollup`, `resume_rollup`).
586
- * Normalizes case, whitespace, camelCase/PascalCase, protobuf type URLs, and bare protocol names (`RT-1245-3`).
587
- */
588
- function isDeprecatedRollupWriteProtocol(typeUrl) {
589
- const normalized = normalizeRollupProtocolTypeUrl(typeUrl);
590
- return DEPRECATED_ROLLUP_PROTOCOL_SET.has(normalized);
591
- }
592
- /**
593
- * Issue #1245:
594
- * Sunset guard for active transaction pipeline execution:
595
- * - Blocks all 8 deprecated Rollup write protocols when `currentBlockHeight >= rollupSunsetActivationHeight`.
596
- * - Allows historical block replay when `currentBlockHeight < rollupSunsetActivationHeight`.
597
- */
598
- function assertRollupProtocolNotSunset(params) {
599
- if (!params || typeof params !== "object") throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: sunset guard params must be an object");
600
- if (typeof params.typeUrl !== "string" || params.typeUrl.trim().length === 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: typeUrl must be a non-empty string");
601
- if (!Number.isSafeInteger(params.currentBlockHeight) || params.currentBlockHeight < 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: currentBlockHeight must be a non-negative safe integer");
602
- const activationHeight = params.rollupSunsetActivationHeight ?? DEFAULT_ROLLUP_SUNSET_ACTIVATION_HEIGHT;
603
- if (!Number.isSafeInteger(activationHeight) || activationHeight < 1) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: rollupSunsetActivationHeight must be a positive safe integer (>= 1)");
604
- if (isDeprecatedRollupWriteProtocol(params.typeUrl)) {
605
- if (params.currentBlockHeight >= activationHeight) {
606
- const canonicalTypeUrl = normalizeRollupProtocolTypeUrl(params.typeUrl);
607
- throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: legacy Rollup write protocol ${canonicalTypeUrl} is deprecated and disabled at block height ${params.currentBlockHeight} (>= sunset height ${activationHeight}); use Zero-Rollup-Block EIP-712 DirectWithdrawVoucher instead`);
608
- }
609
- return;
610
- }
611
- assertCleanString(params.typeUrl, "typeUrl");
612
- }
613
- /**
614
- * Issue #1245:
615
- * Strictly read-only historical parser for legacy `RollupState`, `RollupBlock`, `deposit_token_v2`,
616
- * and `withdraw_token_v2` records so block explorers, indexers, and audit tools can inspect historical
617
- * chain data after the active Rollup write protocols are removed.
618
- */
619
- function parseLegacyRollupReadOnlyRecord(rawRecord) {
620
- if (!rawRecord || typeof rawRecord !== "object" || Array.isArray(rawRecord)) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: legacy Rollup record must be a plain object");
621
- if (Object.prototype.hasOwnProperty.call(rawRecord, "__proto__") || Object.prototype.hasOwnProperty.call(rawRecord, "constructor") || Object.prototype.hasOwnProperty.call(rawRecord, "prototype")) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: prototype pollution keys rejected in legacy Rollup record");
622
- const rawKind = String(rawRecord.recordKind ?? rawRecord.typeUrl ?? "").trim();
623
- const normalizedKind = rawKind.startsWith("fg:t:") ? rawKind.slice(5) : rawKind;
624
- if (normalizedKind === "RollupState") {
625
- const rollupAddress = assertCleanString(String(rawRecord.rollupAddress ?? rawRecord.address ?? ""), "rollupAddress");
626
- const tokenAddress = assertCleanString(String(rawRecord.tokenAddress ?? ""), "tokenAddress");
627
- const rawValidators = Array.isArray(rawRecord.validatorDids ?? rawRecord.validators) ? rawRecord.validatorDids ?? rawRecord.validators : [];
628
- if (rawValidators.length > 64) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: legacy RollupState validator list too large");
629
- const validatorDids = Object.freeze(rawValidators.map((v) => assertCleanString(String(v ?? ""), "validatorDid")));
630
- const latestHeight = rawRecord.blockHeight !== void 0 ? Number(rawRecord.blockHeight) : Number(rawRecord.latestBlockHeight ?? 0);
631
- if (!Number.isSafeInteger(latestHeight) || latestHeight < 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid legacy RollupState blockHeight");
632
- return Object.freeze({
633
- recordKind: "RollupState",
634
- mode: "READ_ONLY_LEGACY_ARCHIVE",
635
- rollupAddress,
636
- tokenAddress,
637
- blockHeight: latestHeight,
638
- validatorDids
639
- });
640
- }
641
- if (normalizedKind === "RollupBlock" || normalizedKind === "create_rollup_block") {
642
- const rollupAddress = assertCleanString(String(rawRecord.rollupAddress ?? rawRecord.rollup ?? ""), "rollupAddress");
643
- const blockHeight = Number(rawRecord.blockHeight ?? rawRecord.height);
644
- if (!Number.isSafeInteger(blockHeight) || blockHeight <= 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: legacy RollupBlock height must be >= 1");
645
- const previousHash = rawRecord.previousHash ? assertBytes32Hex(String(rawRecord.previousHash), "previousHash") : ZERO_BYTES32_HASH;
646
- const merkleRoot = assertBytes32Hex(String(rawRecord.merkleRoot ?? ""), "merkleRoot");
647
- const hasExplicitTxArray = rawRecord.txHashes !== void 0 || rawRecord.txs !== void 0;
648
- const rawTxs = Array.isArray(rawRecord.txHashes ?? rawRecord.txs) ? rawRecord.txHashes ?? rawRecord.txs : [];
649
- if (rawTxs.length > DEFAULT_MAX_ROLLUP_BLOCK_SIZE) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: legacy RollupBlock txHashes exceeds max size");
650
- const txHashes = Object.freeze(rawTxs.map((h) => assertBytes32Hex(String(h ?? ""), "txHash")));
651
- const computedTxsHash = computeEvmBridgeTxsHash([...txHashes]);
652
- const txsHash = rawRecord.txsHash ? assertBytes32Hex(String(rawRecord.txsHash), "txsHash") : computedTxsHash;
653
- if (rawRecord.txsHash && hasExplicitTxArray && txsHash !== computedTxsHash) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: legacy RollupBlock #${blockHeight} txsHash mismatch against txHashes`);
654
- const computedBlockHash = computeEvmBridgeBlockHash({
655
- height: blockHeight,
656
- previousHash,
657
- merkleRoot,
658
- txsHash
659
- });
660
- const blockHash = rawRecord.blockHash ? assertBytes32Hex(String(rawRecord.blockHash), "blockHash") : computedBlockHash;
661
- if (blockHash !== computedBlockHash) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: legacy RollupBlock #${blockHeight} blockHash mismatch`);
662
- const proposerDid = rawRecord.proposerDid ? assertCleanString(String(rawRecord.proposerDid), "proposerDid") : void 0;
663
- return Object.freeze({
664
- recordKind: "RollupBlock",
665
- mode: "READ_ONLY_LEGACY_ARCHIVE",
666
- rollupAddress,
667
- blockHeight,
668
- previousHash,
669
- merkleRoot,
670
- txsHash,
671
- blockHash,
672
- txHashes,
673
- proposerDid
674
- });
675
- }
676
- if (normalizedKind === "deposit_token_v2" || normalizedKind === "withdraw_token_v2") {
677
- const rollupAddress = assertCleanString(String(rawRecord.rollupAddress ?? rawRecord.rollup ?? ""), "rollupAddress");
678
- const tokenAddress = assertCleanString(String(rawRecord.tokenAddress ?? ""), "tokenAddress");
679
- const fromDid = rawRecord.fromDid ? assertCleanString(String(rawRecord.fromDid), "fromDid") : void 0;
680
- const recipientAddress = assertCleanString(String(rawRecord.recipientAddress ?? rawRecord.to ?? ""), "recipientAddress");
681
- const amount = parseStrictUint256JsonValue(rawRecord.amount ?? rawRecord.value, "amount");
682
- if (amount <= 0n) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: legacy transfer amount must be > 0n");
683
- const evidenceHash = rawRecord.evidenceHash ? assertBytes32Hex(String(rawRecord.evidenceHash), "evidenceHash") : void 0;
684
- return Object.freeze({
685
- recordKind: normalizedKind,
686
- mode: "READ_ONLY_LEGACY_ARCHIVE",
687
- rollupAddress,
688
- tokenAddress,
689
- fromDid,
690
- recipientAddress,
691
- amount,
692
- evidenceHash
693
- });
694
- }
695
- throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: unsupported legacy Rollup record kind (${rawKind || "empty"})`);
696
- }
697
- function computeSolidityFunctionSelector(signature) {
698
- return `0x${utf8Keccak256Hex(signature).slice(2, 10)}`;
699
- }
700
- function encodeAbiDynamicUtf8String(value) {
701
- const buf = Buffer.from(value, "utf8");
702
- const lenWord = uint256ToHex64(buf.length);
703
- const paddedLen = Math.ceil(buf.length / 32) * 32;
704
- return `${lenWord}${buf.toString("hex").padEnd(paddedLen * 2, "0")}`;
705
- }
706
- function decodeAbiDynamicUtf8String(hexDataWithoutSelector, byteOffset) {
707
- const charOffset = byteOffset * 2;
708
- if (charOffset + 64 > hexDataWithoutSelector.length) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid ABI dynamic string offset");
709
- const strByteLen = Number(BigInt(`0x${hexDataWithoutSelector.slice(charOffset, charOffset + 64)}`));
710
- const startChar = charOffset + 64;
711
- const endChar = startChar + strByteLen * 2;
712
- if (strByteLen < 0 || endChar > hexDataWithoutSelector.length) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid ABI dynamic string length");
713
- return Buffer.from(hexDataWithoutSelector.slice(startChar, endChar), "hex").toString("utf8");
714
- }
715
- /**
716
- * Derives the canonical 20-byte lowercase `0x`-prefixed Ethereum address from a 32-byte `secp256k1` private key.
717
- */
718
- function deriveEvmAddressFromPrivateKeyHex(privateKeyHex) {
719
- const cleanPriv = assertBytes32Hex(privateKeyHex.startsWith("0x") ? privateKeyHex : `0x${privateKeyHex}`, "privateKeyHex").slice(2);
720
- if (/^0+$/.test(cleanPriv)) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: secp256k1 private key cannot be zero");
721
- return `0x${keccak256(`0x${secp256k1Curve.keyFromPrivate(cleanPriv, "hex").getPublic(false, "hex").slice(2)}`).slice(-40).toLowerCase()}`;
722
- }
723
- /**
724
- * Signs a 32-byte digest (`0x...`) using a real `secp256k1` private key and returns Ethereum `(v, r, s)` + `signerEvmAddress`.
725
- */
726
- function signDigestWithSecp256k1PrivateKey(digestHex, privateKeyHex) {
727
- const cleanDigest = assertBytes32Hex(digestHex, "digestHex").slice(2);
728
- const cleanPriv = assertBytes32Hex(privateKeyHex.startsWith("0x") ? privateKeyHex : `0x${privateKeyHex}`, "privateKeyHex").slice(2);
729
- const signerEvmAddress = deriveEvmAddressFromPrivateKeyHex(`0x${cleanPriv}`);
730
- const sig = secp256k1Curve.keyFromPrivate(cleanPriv, "hex").sign(cleanDigest, { canonical: true });
731
- return {
732
- v: (sig.recoveryParam ?? 0) + 27,
733
- r: `0x${sig.r.toString("hex").padStart(64, "0").toLowerCase()}`,
734
- s: `0x${sig.s.toString("hex").padStart(64, "0").toLowerCase()}`,
735
- signerEvmAddress
736
- };
737
- }
738
- const SECP256K1_N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
739
- const SECP256K1_HALF_N = SECP256K1_N / 2n;
740
- /**
741
- * Recovers the 20-byte Ethereum signer address from `(digestHex, v, r, s)` identically to OpenZeppelin `ECDSA.recover` (EIP-2 low-`s` enforced).
742
- */
743
- function ecrecoverEvmAddress(digestHex, v, rHex, sHex) {
744
- const cleanDigest = assertBytes32Hex(digestHex, "digestHex").slice(2);
745
- if (v !== 27 && v !== 28) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: invalid ecrecover v (${v}); expected 27 or 28`);
746
- const cleanR = assertBytes32Hex(rHex, "r").slice(2);
747
- const cleanS = assertBytes32Hex(sHex, "s").slice(2);
748
- const rBig = BigInt(`0x${cleanR}`);
749
- const sBig = BigInt(`0x${cleanS}`);
750
- if (rBig <= 0n || rBig >= SECP256K1_N) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid ECDSA signature r out of range");
751
- if (sBig <= 0n || sBig > SECP256K1_HALF_N) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid or malleable ECDSA signature s (EIP-2 low-s required)");
752
- try {
753
- return `0x${keccak256(`0x${secp256k1Curve.recoverPubKey(Buffer.from(cleanDigest, "hex"), {
754
- r: cleanR,
755
- s: cleanS
756
- }, v - 27, "hex").encode("hex", false).slice(2)}`).slice(-40).toLowerCase()}`;
757
- } catch (err) {
758
- throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ECDSA public key recovery failed (${err instanceof Error ? err.message : String(err)})`);
759
- }
760
- }
761
- function cloneDirectWithdrawVoucher(voucher) {
762
- return {
763
- ...voucher,
764
- validatorSigners: [...voucher.validatorSigners],
765
- validatorSignatures: voucher.validatorSignatures.map((s) => ({ ...s }))
766
- };
767
- }
768
- /**
769
- * Computes the HMAC-SHA256 signature for Cloudflare Edge webhook requests.
770
- */
771
- function computeEdgeWebhookHmac(secret, timestampSeconds, nonce, path, bodyJson) {
772
- return createHmac("sha256", secret).update(`${timestampSeconds}:${nonce}:${path}:${bodyJson}`).digest("hex");
773
- }
774
- /**
775
- * Issue #1241:
776
- * Next-Gen Simplified EVM Bridge Node (`OcapSimplifiedEvmBridgeNode`).
777
- * - Pure ARC-native & Cloudflare Workers / Durable Objects ready (zero native C++ addons, full snapshot import/export).
778
- * - Implements Track 1 (`Pay-Where-You-Are` Direct Service Cashier) and Track 2 (`1:1 Canonical ABT Gateway`).
779
- * - 100% backward-compatible with OCAP `RollupState`, `deposit_token_v2`, `withdraw_token_v2`, and `@ocap/merkle-tree`.
780
- */
781
- var OcapSimplifiedEvmBridgeNode = class OcapSimplifiedEvmBridgeNode {
782
- constructor(config) {
783
- this.paused = false;
784
- this.latestBlockHeight = 0;
785
- this.cumulativeDepositedAbt = 0n;
786
- this.cumulativeWithdrawnAbt = 0n;
787
- this.processedEventKeys = /* @__PURE__ */ new Set();
788
- this.processedServiceOrderIds = /* @__PURE__ */ new Set();
789
- this.processedWithdrawTxHashes = /* @__PURE__ */ new Set();
790
- this.cancelledWithdrawTxHashes = /* @__PURE__ */ new Set();
791
- this.dailyWithdrawnByDay = /* @__PURE__ */ new Map();
792
- this.processedWebhookNonces = /* @__PURE__ */ new Map();
793
- this.pendingWithdrawQueue = [];
794
- this.sealedBlocks = /* @__PURE__ */ new Map();
795
- this.withdrawTxToBlockHeight = /* @__PURE__ */ new Map();
796
- this.issuedDirectVouchers = /* @__PURE__ */ new Map();
797
- const bridgeId = assertCleanString(config.bridgeId, "bridgeId");
798
- const rollupAddress = assertCleanString(config.rollupAddress, "rollupAddress");
799
- const bridgeProposerDid = assertCleanString(config.bridgeProposerDid, "bridgeProposerDid");
800
- const guardianDid = assertCleanString(config.guardianDid ?? bridgeProposerDid, "guardianDid");
801
- const verifyingContractAddress = assertEvmAddress(config.verifyingContractAddress ?? DEFAULT_VERIFYING_CONTRACT_ADDRESS, "verifyingContractAddress");
802
- const ocapNativeAbtTokenAddress = assertCleanString(config.ocapNativeAbtTokenAddress, "ocapNativeAbtTokenAddress");
803
- const canonicalErc20AbtAddress = assertEvmAddress(config.canonicalErc20AbtAddress, "canonicalErc20AbtAddress");
804
- if (!Array.isArray(config.allowedEvmChainIds) || config.allowedEvmChainIds.length === 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: allowedEvmChainIds must be non-empty");
805
- const allowedEvmChainIds = config.allowedEvmChainIds.map((c) => assertCleanString(c, "allowedEvmChainId"));
806
- if (!Array.isArray(config.allowedServicePaymentTokens) || config.allowedServicePaymentTokens.length === 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: allowedServicePaymentTokens must be non-empty");
807
- const allowedServicePaymentTokens = Array.from(new Set([canonicalErc20AbtAddress, ...config.allowedServicePaymentTokens.map((t) => assertEvmAddress(t, "allowedServicePaymentToken"))]));
808
- const allowSingleSignerForTesting = config.allowSingleSignerForTesting === true;
809
- const rawValidatorDids = config.validatorDids ?? [bridgeProposerDid];
810
- if (!Array.isArray(rawValidatorDids) || rawValidatorDids.length === 0 || rawValidatorDids.length > 16) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: validatorDids must contain 1..16 DIDs");
811
- const validatorDids = Array.from(new Set(rawValidatorDids.map((v) => assertCleanString(v, "validatorDid"))));
812
- if (validatorDids.length !== rawValidatorDids.length) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: duplicate validatorDids are not allowed");
813
- if (!validatorDids.includes(bridgeProposerDid)) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: bridgeProposerDid must be included in validatorDids");
814
- const defaultMinSigs = allowSingleSignerForTesting && validatorDids.length === 1 ? 1 : 2;
815
- const minValidatorSignatures = config.minValidatorSignatures ?? defaultMinSigs;
816
- if (!Number.isSafeInteger(minValidatorSignatures) || minValidatorSignatures < 1 || minValidatorSignatures > validatorDids.length) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: minValidatorSignatures must be in 1..validatorDids.length");
817
- if (!allowSingleSignerForTesting && minValidatorSignatures < 2) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: multi-domain quorum requires minValidatorSignatures >= 2 unless allowSingleSignerForTesting is explicitly true");
818
- const minConfirmations = config.minConfirmations ?? DEFAULT_MIN_EVM_CONFIRMATIONS;
819
- if (!Number.isSafeInteger(minConfirmations) || minConfirmations < 1 || minConfirmations > 100) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: minConfirmations must be in 1..100");
820
- const maxBlockSize = config.maxBlockSize ?? DEFAULT_MAX_ROLLUP_BLOCK_SIZE;
821
- if (!Number.isSafeInteger(maxBlockSize) || maxBlockSize < 1 || maxBlockSize > DEFAULT_MAX_ROLLUP_BLOCK_SIZE) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: maxBlockSize must be in 1..${DEFAULT_MAX_ROLLUP_BLOCK_SIZE}`);
822
- if (typeof config.minDepositAmount !== "bigint" || typeof config.maxDepositAmount !== "bigint" || config.minDepositAmount <= 0n || config.maxDepositAmount < config.minDepositAmount) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid deposit amount bounds");
823
- if (typeof config.minWithdrawAmount !== "bigint" || typeof config.maxWithdrawAmount !== "bigint" || config.minWithdrawAmount <= 0n || config.maxWithdrawAmount < config.minWithdrawAmount) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid withdraw amount bounds");
824
- const maxDailyWithdrawAbt = config.maxDailyWithdrawAbt ?? config.maxWithdrawAmount * 10n;
825
- if (typeof maxDailyWithdrawAbt !== "bigint" || maxDailyWithdrawAbt < config.minWithdrawAmount) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: maxDailyWithdrawAbt must be >= minWithdrawAmount");
826
- const largeWithdrawTimelockThresholdAbt = config.largeWithdrawTimelockThresholdAbt ?? config.maxWithdrawAmount;
827
- if (typeof largeWithdrawTimelockThresholdAbt !== "bigint" || largeWithdrawTimelockThresholdAbt < config.minWithdrawAmount) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: largeWithdrawTimelockThresholdAbt must be >= minWithdrawAmount");
828
- const timelockDelaySeconds = config.timelockDelaySeconds ?? DEFAULT_WITHDRAW_TIMELOCK_DELAY_SECONDS;
829
- if (!Number.isSafeInteger(timelockDelaySeconds) || timelockDelaySeconds < 60 || timelockDelaySeconds > 604800) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: timelockDelaySeconds must be in 60..604800 seconds");
830
- const genesisBlockHash = config.genesisBlockHash ? assertBytes32Hex(config.genesisBlockHash, "genesisBlockHash") : ZERO_BYTES32_HASH;
831
- if (typeof config.webhookHmacSecret !== "string" || config.webhookHmacSecret.trim().length < 16) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: webhookHmacSecret must be at least 16 characters");
832
- this.config = {
833
- bridgeId,
834
- rollupAddress,
835
- bridgeProposerDid,
836
- guardianDid,
837
- verifyingContractAddress,
838
- ocapNativeAbtTokenAddress,
839
- canonicalErc20AbtAddress,
840
- allowedServicePaymentTokens,
841
- allowedEvmChainIds,
842
- validatorDids,
843
- minValidatorSignatures,
844
- allowSingleSignerForTesting,
845
- minConfirmations,
846
- minDepositAmount: config.minDepositAmount,
847
- maxDepositAmount: config.maxDepositAmount,
848
- minWithdrawAmount: config.minWithdrawAmount,
849
- maxWithdrawAmount: config.maxWithdrawAmount,
850
- maxDailyWithdrawAbt,
851
- largeWithdrawTimelockThresholdAbt,
852
- timelockDelaySeconds,
853
- maxBlockSize,
854
- genesisBlockHash,
855
- webhookHmacSecret: config.webhookHmacSecret
856
- };
857
- this.latestBlockHash = genesisBlockHash;
858
- this.allowedChainSet = new Set(allowedEvmChainIds);
859
- this.allowedPaymentTokenSet = new Set(allowedServicePaymentTokens);
860
- this.validatorSet = new Set(validatorDids);
861
- }
862
- assertNotPaused() {
863
- if (this.paused) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: bridge is emergency-paused by guardian");
864
- }
865
- /**
866
- * Layer 3 Anti-Drain Control: Guardian emergency pause / unpause.
867
- */
868
- setBridgePaused(params) {
869
- const guardianDid = assertCleanString(params.guardianDid, "guardianDid");
870
- if (guardianDid !== this.config.guardianDid) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: caller ${guardianDid} is not authorized guardian (${this.config.guardianDid})`);
871
- this.paused = Boolean(params.paused);
872
- return { paused: this.paused };
873
- }
874
- /**
875
- * Layer 3 Anti-Drain Control: Guardian cancels a timelocked whale withdrawal before its timelock expires,
876
- * restoring the Canary reserve watermark and daily withdrawal cap.
877
- */
878
- cancelTimelockedWithdraw(params) {
879
- const guardianDid = assertCleanString(params.guardianDid, "guardianDid");
880
- if (guardianDid !== this.config.guardianDid) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: caller ${guardianDid} is not authorized guardian (${this.config.guardianDid})`);
881
- if (!Number.isSafeInteger(params.nowUnixSeconds) || params.nowUnixSeconds <= 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: nowUnixSeconds must be a positive integer");
882
- const cleanTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
883
- const voucher = this.issuedDirectVouchers.get(cleanTxHash);
884
- if (!voucher) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: no issued direct withdraw voucher found for ${cleanTxHash}`);
885
- if (voucher.cancelled === true || this.cancelledWithdrawTxHashes.has(cleanTxHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdraw ${cleanTxHash} is already cancelled`);
886
- if (!voucher.timelocked || params.nowUnixSeconds >= voucher.unlocksAtUnixSeconds) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdraw ${cleanTxHash} cannot be cancelled because timelock window has already elapsed`);
887
- voucher.cancelled = true;
888
- this.cancelledWithdrawTxHashes.add(cleanTxHash);
889
- this.cumulativeWithdrawnAbt -= voucher.amount;
890
- const dayBucket = Math.floor(voucher.issuedAtUnixSeconds / 86400);
891
- const currentDayTotal = this.dailyWithdrawnByDay.get(dayBucket) ?? 0n;
892
- const nextDayTotal = currentDayTotal > voucher.amount ? currentDayTotal - voucher.amount : 0n;
893
- if (nextDayTotal === 0n) this.dailyWithdrawnByDay.delete(dayBucket);
894
- else this.dailyWithdrawnByDay.set(dayBucket, nextDayTotal);
895
- return {
896
- cancelledTxHash: cleanTxHash,
897
- refundedReserveAbt: voucher.amount
898
- };
899
- }
900
- assertFinalizedEvmEvent(params) {
901
- const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
902
- if (!this.allowedChainSet.has(evmChainId)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: evmChainId ${evmChainId} is not permitted by this bridge`);
903
- const evmTxHash = assertBytes32Hex(params.evmTxHash, "evmTxHash");
904
- if (!Number.isSafeInteger(params.logIndex) || params.logIndex < 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: logIndex must be a non-negative integer");
905
- if (params.reorged === true) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: reorged EVM events are rejected");
906
- if (!Number.isSafeInteger(params.confirmations) || params.confirmations < this.config.minConfirmations) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: confirmations (${params.confirmations}) below required finality threshold (${this.config.minConfirmations})`);
907
- const eventKey = `${evmChainId}:${evmTxHash}:${params.logIndex}`;
908
- if (this.processedEventKeys.has(eventKey)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate EVM event ${eventKey} replay blocked`);
909
- return {
910
- evmChainId,
911
- evmTxHash,
912
- eventKey
913
- };
914
- }
915
- /**
916
- * Track 1 — `Pay-Where-You-Are, Consume-on-OCAP`:
917
- * Ingests a finalized `OcapServicePaid` event from Ethereum/Base (paid in ERC-20 ABT or USDC)
918
- * and produces a deterministic `OcapServiceDeliveryInstruction` (`CrossChainPurchaseInput`)
919
- * without minting or bridging any foreign token onto OCAP.
920
- */
921
- ingestEvmServicePaymentEvent(input) {
922
- this.assertNotPaused();
923
- const { evmChainId, evmTxHash, eventKey } = this.assertFinalizedEvmEvent(input);
924
- const orderId = assertBytes32Hex(input.orderId, "orderId");
925
- if (orderId === ZERO_BYTES32_HASH) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: orderId cannot be zero bytes32");
926
- if (this.processedServiceOrderIds.has(orderId)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate service orderId ${orderId} replay blocked`);
927
- assertEvmAddress(input.payerEvmAddress, "payerEvmAddress");
928
- const recipientDid = assertCleanString(input.recipientDid, "recipientDid");
929
- const serviceDid = assertCleanString(input.serviceDid, "serviceDid");
930
- const paymentTokenAddress = assertEvmAddress(input.paymentTokenAddress, "paymentTokenAddress");
931
- if (!this.allowedPaymentTokenSet.has(paymentTokenAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: paymentTokenAddress ${paymentTokenAddress} is not whitelisted for service payments`);
932
- if (typeof input.amount !== "bigint" || input.amount <= 0n) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: service payment amount must be > 0n");
933
- const nftDid = input.deliverableNftDid ? assertCleanString(input.deliverableNftDid, "deliverableNftDid") : `did:abt:snft:service:${orderId.slice(2, 34)}`;
934
- const depositProofPreimage = `ocap:evm-service-pay:v1:${this.config.bridgeId}:${eventKey}:${orderId}:${recipientDid}:${serviceDid}:${paymentTokenAddress}:${input.amount.toString()}`;
935
- const depositProofDigest = keccak256(`0x${Buffer.from(depositProofPreimage, "utf8").toString("hex")}`).toLowerCase();
936
- const crossChainPurchaseInput = {
937
- id: `blk:evm-pay:${orderId.slice(2, 18)}`,
938
- relayer: this.config.bridgeProposerDid,
939
- buyer: recipientDid,
940
- deposit: {
941
- rollup: this.config.rollupAddress,
942
- proposer: this.config.bridgeProposerDid,
943
- token: {
944
- address: this.config.ocapNativeAbtTokenAddress,
945
- value: input.amount.toString()
946
- },
947
- actualFee: "0",
948
- evidence: {
949
- hash: evmTxHash,
950
- targetType: "EVM",
951
- targetChainId: evmChainId
952
- }
953
- },
954
- purchaseStatements: [{
955
- id: "purchase_1",
956
- typeUrl: "fg:t:acquire_asset_v3",
957
- from: recipientDid,
958
- to: serviceDid,
959
- tokenAddress: this.config.ocapNativeAbtTokenAddress,
960
- amount: input.amount.toString(),
961
- itx: {
962
- factory: serviceDid,
963
- assets: [nftDid]
964
- }
965
- }]
966
- };
967
- this.processedEventKeys.add(eventKey);
968
- this.processedServiceOrderIds.add(orderId);
969
- return {
970
- instructionId: `srv:${orderId.slice(2, 26)}`,
971
- eventKey,
972
- orderId,
973
- recipientDid,
974
- serviceDid,
975
- paymentTokenAddress,
976
- paidAmount: input.amount,
977
- depositProofDigest,
978
- crossChainPurchaseInput
979
- };
980
- }
981
- /**
982
- * Track 2A — `ERC-20 ABT -> OCAP Native ABT` 1:1 Relayer-Sponsored Deposit:
983
- * Ingests a finalized `NativeAbtDepositLocked` event on Ethereum/Base, increments the Canary
984
- * reserve watermark (`cumulativeDepositedAbt`), and generates a proposer-sponsored `deposit_token_v2`
985
- * instruction so even 0-gas OCAP accounts receive Native ABT in 1 click.
986
- */
987
- ingestEvmAbtDepositEvent(input) {
988
- this.assertNotPaused();
989
- const { eventKey, evmTxHash } = this.assertFinalizedEvmEvent(input);
990
- assertEvmAddress(input.depositorEvmAddress, "depositorEvmAddress");
991
- const recipientDid = assertCleanString(input.recipientDid, "recipientDid");
992
- if (assertEvmAddress(input.tokenAddress, "tokenAddress") !== this.config.canonicalErc20AbtAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: canonical deposit only accepts official ERC-20 ABT (${this.config.canonicalErc20AbtAddress})`);
993
- if (typeof input.amount !== "bigint" || input.amount < this.config.minDepositAmount || input.amount > this.config.maxDepositAmount) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: deposit amount (${String(input.amount)}) must be within [${this.config.minDepositAmount}, ${this.config.maxDepositAmount}]`);
994
- const actualFee = input.actualFee ?? 0n;
995
- if (typeof actualFee !== "bigint" || actualFee < 0n || actualFee >= input.amount) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: actualFee must be a non-negative bigint strictly less than deposit amount");
996
- const netValue = input.amount - actualFee;
997
- this.cumulativeDepositedAbt += input.amount;
998
- this.processedEventKeys.add(eventKey);
999
- return {
1000
- instructionId: `dep:${evmTxHash.slice(2, 26)}:${input.logIndex}`,
1001
- eventKey,
1002
- rollupAddress: this.config.rollupAddress,
1003
- proposerDid: this.config.bridgeProposerDid,
1004
- proposerSponsored: true,
1005
- recipientDid,
1006
- tokenAddress: this.config.ocapNativeAbtTokenAddress,
1007
- value: netValue,
1008
- actualFee,
1009
- evidenceHash: evmTxHash,
1010
- cumulativeDepositedAbt: this.cumulativeDepositedAbt
1011
- };
1012
- }
1013
- /**
1014
- * Track 2B (Step 1) — Enqueues a finalized OCAP `withdraw_token_v2` transaction for the next
1015
- * Rollup Merkle block, enforcing the Canary Net-Inflow Reserve Watermark up front.
1016
- */
1017
- enqueueOcapAbtWithdraw(withdraw) {
1018
- this.assertNotPaused();
1019
- const ocapTxHash = assertBytes32Hex(withdraw.ocapTxHash, "ocapTxHash");
1020
- if (ocapTxHash === ZERO_BYTES32_HASH) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: ocapTxHash cannot be zero bytes32");
1021
- if (this.processedWithdrawTxHashes.has(ocapTxHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate withdraw ocapTxHash ${ocapTxHash} replay blocked`);
1022
- const fromDid = assertCleanString(withdraw.fromDid, "fromDid");
1023
- const recipientEvmAddress = assertEvmAddress(withdraw.recipientEvmAddress, "recipientEvmAddress");
1024
- if (typeof withdraw.amount !== "bigint" || withdraw.amount < this.config.minWithdrawAmount || withdraw.amount > this.config.maxWithdrawAmount) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdraw amount (${String(withdraw.amount)}) must be within [${this.config.minWithdrawAmount}, ${this.config.maxWithdrawAmount}]`);
1025
- if (withdraw.amount >= this.config.largeWithdrawTimelockThresholdAbt) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: whale withdraw (${withdraw.amount} >= ${this.config.largeWithdrawTimelockThresholdAbt}) must use issueDirectWithdrawVoucher to enforce Layer 3 24h Timelock`);
1026
- const pendingWithdrawTotal = this.pendingWithdrawQueue.reduce((acc, item) => acc + item.amount, 0n);
1027
- const nextTotalWithdrawn = this.cumulativeWithdrawnAbt + pendingWithdrawTotal + withdraw.amount;
1028
- if (nextTotalWithdrawn > this.cumulativeDepositedAbt) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdraw amount (${withdraw.amount}) exceeds Canary net-inflow reserve watermark: nextTotalWithdrawn (${nextTotalWithdrawn}) > cumulativeDepositedAbt (${this.cumulativeDepositedAbt})`);
1029
- this.processedWithdrawTxHashes.add(ocapTxHash);
1030
- this.pendingWithdrawQueue.push({
1031
- ocapTxHash,
1032
- fromDid,
1033
- recipientEvmAddress,
1034
- amount: withdraw.amount
1035
- });
1036
- return {
1037
- queuedCount: this.pendingWithdrawQueue.length,
1038
- pendingWithdrawTotal: pendingWithdrawTotal + withdraw.amount
1039
- };
1040
- }
1041
- /**
1042
- * Pre-computes the next pending Rollup block header (`height`, `previousHash`, `merkleRoot`, `txsHash`, `blockHash`)
1043
- * so validators can sign `blockHash` before calling `sealRollupWithdrawBlock`.
1044
- */
1045
- previewNextRollupWithdrawBlock() {
1046
- if (this.pendingWithdrawQueue.length === 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: no pending withdraw transactions to seal");
1047
- const batchWithdrawTxs = this.pendingWithdrawQueue.slice(0, this.config.maxBlockSize).map((item) => ({ ...item }));
1048
- const height = this.latestBlockHeight + 1;
1049
- const previousHash = this.latestBlockHash;
1050
- const { merkleRoot } = buildEvmBridgeMerkleTree(batchWithdrawTxs);
1051
- const txsHash = computeEvmBridgeTxsHash(batchWithdrawTxs.map((tx) => tx.ocapTxHash));
1052
- return {
1053
- height,
1054
- previousHash,
1055
- merkleRoot,
1056
- txsHash,
1057
- blockHash: computeEvmBridgeBlockHash({
1058
- height,
1059
- previousHash,
1060
- merkleRoot,
1061
- txsHash
1062
- }),
1063
- batchWithdrawTxs
1064
- };
1065
- }
1066
- /**
1067
- * Track 2B (Step 2) — Seals a batch of pending OCAP withdrawals into a `@ocap/merkle-tree` compatible
1068
- * Rollup block verified by M-of-N distinct validators.
1069
- */
1070
- sealRollupWithdrawBlock(params) {
1071
- this.assertNotPaused();
1072
- if (!Number.isSafeInteger(params.sealedAtUnixSeconds) || params.sealedAtUnixSeconds <= 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: sealedAtUnixSeconds must be a positive integer");
1073
- if (!Array.isArray(params.validatorSignatures)) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: validatorSignatures must be an array");
1074
- const preview = this.previewNextRollupWithdrawBlock();
1075
- const seenValidators = /* @__PURE__ */ new Set();
1076
- const validatorSigners = [];
1077
- for (const sig of params.validatorSignatures) {
1078
- if (!sig || typeof sig !== "object") throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid validator signature entry");
1079
- const validatorDid = assertCleanString(sig.validatorDid, "validatorDid");
1080
- if (!this.validatorSet.has(validatorDid)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: signer ${validatorDid} is not an authorized bridge validator`);
1081
- if (seenValidators.has(validatorDid)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate validator signature from ${validatorDid}`);
1082
- const expectedDigest = computeValidatorBlockSignatureDigest(this.config.bridgeId, this.config.rollupAddress, preview.blockHash, validatorDid);
1083
- if (assertBytes32Hex(sig.signatureDigest, "signatureDigest") !== expectedDigest) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: invalid signatureDigest from validator ${validatorDid}`);
1084
- seenValidators.add(validatorDid);
1085
- validatorSigners.push(validatorDid);
1086
- }
1087
- if (validatorSigners.length < this.config.minValidatorSignatures) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: validator quorum not met (${validatorSigners.length} < ${this.config.minValidatorSignatures})`);
1088
- const batchTotal = preview.batchWithdrawTxs.reduce((acc, item) => acc + item.amount, 0n);
1089
- if (this.cumulativeWithdrawnAbt + batchTotal > this.cumulativeDepositedAbt) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: batch withdraw total exceeds Canary net-inflow reserve watermark");
1090
- const dayBucket = Math.floor(params.sealedAtUnixSeconds / 86400);
1091
- const currentDayTotal = this.dailyWithdrawnByDay.get(dayBucket) ?? 0n;
1092
- if (currentDayTotal + batchTotal > this.config.maxDailyWithdrawAbt) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: batch withdraw (${batchTotal}) exceeds 24h rolling withdrawal cap (${this.config.maxDailyWithdrawAbt})`);
1093
- this.pendingWithdrawQueue.splice(0, preview.batchWithdrawTxs.length);
1094
- this.cumulativeWithdrawnAbt += batchTotal;
1095
- this.dailyWithdrawnByDay.set(dayBucket, currentDayTotal + batchTotal);
1096
- this.latestBlockHeight = preview.height;
1097
- this.latestBlockHash = preview.blockHash;
1098
- const sealedBlock = {
1099
- height: preview.height,
1100
- previousHash: preview.previousHash,
1101
- merkleRoot: preview.merkleRoot,
1102
- txsHash: preview.txsHash,
1103
- blockHash: preview.blockHash,
1104
- withdrawTxs: preview.batchWithdrawTxs,
1105
- validatorSigners,
1106
- sealedAtUnixSeconds: params.sealedAtUnixSeconds
1107
- };
1108
- this.sealedBlocks.set(sealedBlock.height, sealedBlock);
1109
- for (const tx of sealedBlock.withdrawTxs) this.withdrawTxToBlockHeight.set(tx.ocapTxHash, sealedBlock.height);
1110
- return sealedBlock;
1111
- }
1112
- /**
1113
- * Track 2B (Step 3) — Generates the Merkle proof bundle for a sealed `ocapTxHash` so the user
1114
- * can claim their ERC-20 ABT from `ArcEvmBridgeGateway.claimWithdrawWithMerkleProof` on Ethereum/Base.
1115
- */
1116
- generateWithdrawClaimProof(ocapTxHash) {
1117
- const cleanTxHash = assertBytes32Hex(ocapTxHash, "ocapTxHash");
1118
- const blockHeight = this.withdrawTxToBlockHeight.get(cleanTxHash);
1119
- if (blockHeight === void 0) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: withdraw tx ${cleanTxHash} is not in any sealed Rollup block`);
1120
- const block = this.sealedBlocks.get(blockHeight);
1121
- const targetTx = block.withdrawTxs.find((t) => t.ocapTxHash === cleanTxHash);
1122
- const leafHash = computeEvmBridgeWithdrawLeafHash(targetTx.ocapTxHash, targetTx.recipientEvmAddress, targetTx.amount);
1123
- const merkleProof = buildEvmBridgeMerkleTree(block.withdrawTxs).getProofForLeaf(leafHash);
1124
- return {
1125
- ocapTxHash: cleanTxHash,
1126
- recipientEvmAddress: targetTx.recipientEvmAddress,
1127
- amount: targetTx.amount,
1128
- blockHeight: block.height,
1129
- blockHash: block.blockHash,
1130
- merkleRoot: block.merkleRoot,
1131
- leafHash,
1132
- merkleProof
1133
- };
1134
- }
1135
- /**
1136
- * Track 2B (Primary — Zero-Rollup-Block EIP-712 Pull Mode):
1137
- * Immediately issues a threshold-signed `DirectWithdrawVoucher` for an OCAP withdraw transaction
1138
- * without creating any `RollupBlock`, without building any Merkle tree, and without requiring the
1139
- * Cloudflare Bridge Node to submit any Ethereum transaction or hold ETH gas.
1140
- */
1141
- issueDirectWithdrawVoucher(params) {
1142
- this.assertNotPaused();
1143
- const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
1144
- if (!this.allowedChainSet.has(evmChainId)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: evmChainId ${evmChainId} is not permitted by this bridge`);
1145
- const ocapTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
1146
- if (ocapTxHash === ZERO_BYTES32_HASH) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: ocapTxHash cannot be zero bytes32");
1147
- if (this.processedWithdrawTxHashes.has(ocapTxHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate withdraw ocapTxHash ${ocapTxHash} replay blocked`);
1148
- const fromDid = assertCleanString(params.fromDid, "fromDid");
1149
- const recipientEvmAddress = assertEvmAddress(params.recipientEvmAddress, "recipientEvmAddress");
1150
- if (typeof params.amount !== "bigint" || params.amount < this.config.minWithdrawAmount || params.amount > this.config.maxWithdrawAmount) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdraw amount (${String(params.amount)}) must be within [${this.config.minWithdrawAmount}, ${this.config.maxWithdrawAmount}]`);
1151
- if (!Number.isSafeInteger(params.issuedAtUnixSeconds) || params.issuedAtUnixSeconds <= 0 || !Number.isSafeInteger(params.expiresAtUnixSeconds) || params.expiresAtUnixSeconds <= params.issuedAtUnixSeconds) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: expiresAtUnixSeconds must be strictly greater than issuedAtUnixSeconds");
1152
- const ttl = params.expiresAtUnixSeconds - params.issuedAtUnixSeconds;
1153
- if (ttl < MIN_DIRECT_VOUCHER_TTL_SECONDS || ttl > MAX_DIRECT_VOUCHER_TTL_SECONDS) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: direct voucher TTL (${ttl}s) must be within [${MIN_DIRECT_VOUCHER_TTL_SECONDS}, ${MAX_DIRECT_VOUCHER_TTL_SECONDS}]`);
1154
- const timelocked = params.amount >= this.config.largeWithdrawTimelockThresholdAbt;
1155
- const unlocksAtUnixSeconds = timelocked ? params.issuedAtUnixSeconds + this.config.timelockDelaySeconds : params.issuedAtUnixSeconds;
1156
- if (timelocked && params.expiresAtUnixSeconds <= unlocksAtUnixSeconds) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: timelocked whale withdraw voucher expiresAtUnixSeconds (${params.expiresAtUnixSeconds}) must be strictly greater than unlocksAtUnixSeconds (${unlocksAtUnixSeconds})`);
1157
- const pendingWithdrawTotal = this.pendingWithdrawQueue.reduce((acc, item) => acc + item.amount, 0n);
1158
- const nextTotalWithdrawn = this.cumulativeWithdrawnAbt + pendingWithdrawTotal + params.amount;
1159
- if (nextTotalWithdrawn > this.cumulativeDepositedAbt) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: direct voucher withdraw (${params.amount}) exceeds Canary net-inflow reserve watermark: nextTotalWithdrawn (${nextTotalWithdrawn}) > cumulativeDepositedAbt (${this.cumulativeDepositedAbt})`);
1160
- const dayBucket = Math.floor(params.issuedAtUnixSeconds / 86400);
1161
- const currentDayTotal = this.dailyWithdrawnByDay.get(dayBucket) ?? 0n;
1162
- if (currentDayTotal + params.amount > this.config.maxDailyWithdrawAbt) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: direct voucher withdraw (${params.amount}) exceeds 24h rolling withdrawal cap (${this.config.maxDailyWithdrawAbt})`);
1163
- const eip712DomainSeparator = computeEip712BridgeDomainSeparator({
1164
- evmChainId,
1165
- verifyingContractAddress: this.config.verifyingContractAddress
1166
- });
1167
- const eip712StructHash = computeEip712WithdrawStructHash({
1168
- bridgeId: this.config.bridgeId,
1169
- ocapTxHash,
1170
- recipientEvmAddress,
1171
- amount: params.amount,
1172
- expiresAtUnixSeconds: params.expiresAtUnixSeconds
1173
- });
1174
- const voucherDigest = computeDirectWithdrawVoucherDigest({
1175
- bridgeId: this.config.bridgeId,
1176
- evmChainId,
1177
- verifyingContractAddress: this.config.verifyingContractAddress,
1178
- ocapTxHash,
1179
- recipientEvmAddress,
1180
- amount: params.amount,
1181
- expiresAtUnixSeconds: params.expiresAtUnixSeconds
1182
- });
1183
- if (!Array.isArray(params.validatorSignatures)) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: validatorSignatures must be an array");
1184
- const seenValidators = /* @__PURE__ */ new Set();
1185
- const validatorSigners = [];
1186
- const normalizedSignatures = [];
1187
- for (const sig of params.validatorSignatures) {
1188
- if (!sig || typeof sig !== "object") throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid validator signature entry");
1189
- const validatorDid = assertCleanString(sig.validatorDid, "validatorDid");
1190
- if (!this.validatorSet.has(validatorDid)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: signer ${validatorDid} is not an authorized bridge validator`);
1191
- if (seenValidators.has(validatorDid)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate validator signature from ${validatorDid}`);
1192
- const expectedSig = computeValidatorVoucherSignatureDigest(this.config.bridgeId, voucherDigest, validatorDid);
1193
- const actualSig = assertBytes32Hex(sig.signatureDigest, "signatureDigest");
1194
- if (actualSig !== expectedSig) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: invalid voucher signatureDigest from validator ${validatorDid}`);
1195
- seenValidators.add(validatorDid);
1196
- validatorSigners.push(validatorDid);
1197
- const normalizedSig = {
1198
- validatorDid,
1199
- signatureDigest: actualSig
1200
- };
1201
- if (sig.v !== void 0 || sig.r !== void 0 || sig.s !== void 0 || sig.evmSignerAddress !== void 0) {
1202
- if (sig.v === void 0 || !sig.r || !sig.s) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: validator ${validatorDid} ECDSA signature must provide complete (v, r, s)`);
1203
- const recoveredAddr = ecrecoverEvmAddress(voucherDigest, sig.v, sig.r, sig.s);
1204
- if (sig.evmSignerAddress !== void 0) {
1205
- const expectedAddr = assertEvmAddress(sig.evmSignerAddress, "evmSignerAddress");
1206
- if (recoveredAddr !== expectedAddr) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: validator ${validatorDid} ecrecover (${recoveredAddr}) does not match evmSignerAddress (${expectedAddr})`);
1207
- }
1208
- normalizedSig.evmSignerAddress = recoveredAddr;
1209
- normalizedSig.v = sig.v;
1210
- normalizedSig.r = assertBytes32Hex(sig.r, "r");
1211
- normalizedSig.s = assertBytes32Hex(sig.s, "s");
1212
- }
1213
- normalizedSignatures.push(normalizedSig);
1214
- }
1215
- if (validatorSigners.length < this.config.minValidatorSignatures) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: validator quorum not met (${validatorSigners.length} < ${this.config.minValidatorSignatures})`);
1216
- this.processedWithdrawTxHashes.add(ocapTxHash);
1217
- this.cumulativeWithdrawnAbt += params.amount;
1218
- this.dailyWithdrawnByDay.set(dayBucket, currentDayTotal + params.amount);
1219
- const voucher = {
1220
- voucherDigest,
1221
- eip712DomainSeparator,
1222
- eip712StructHash,
1223
- verifyingContractAddress: this.config.verifyingContractAddress,
1224
- bridgeId: this.config.bridgeId,
1225
- evmChainId,
1226
- ocapTxHash,
1227
- fromDid,
1228
- recipientEvmAddress,
1229
- amount: params.amount,
1230
- issuedAtUnixSeconds: params.issuedAtUnixSeconds,
1231
- expiresAtUnixSeconds: params.expiresAtUnixSeconds,
1232
- timelocked,
1233
- unlocksAtUnixSeconds,
1234
- cancelled: false,
1235
- validatorSigners,
1236
- validatorSignatures: normalizedSignatures
1237
- };
1238
- this.issuedDirectVouchers.set(ocapTxHash, voucher);
1239
- return cloneDirectWithdrawVoucher(voucher);
1240
- }
1241
- /**
1242
- * Retrieves an already-issued Zero-Rollup-Block `DirectWithdrawVoucher` by `ocapTxHash`.
1243
- */
1244
- getDirectWithdrawVoucher(ocapTxHash) {
1245
- const cleanTxHash = assertBytes32Hex(ocapTxHash, "ocapTxHash");
1246
- const voucher = this.issuedDirectVouchers.get(cleanTxHash);
1247
- if (!voucher) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: no direct withdraw voucher found for ${cleanTxHash}`);
1248
- if (voucher.cancelled === true || this.cancelledWithdrawTxHashes.has(cleanTxHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: direct withdraw voucher ${cleanTxHash} was cancelled by guardian`);
1249
- return cloneDirectWithdrawVoucher(voucher);
1250
- }
1251
- getReserveWatermarkState() {
1252
- const pendingWithdrawAbt = this.pendingWithdrawQueue.reduce((acc, item) => acc + item.amount, 0n);
1253
- return {
1254
- paused: this.paused,
1255
- latestBlockHeight: this.latestBlockHeight,
1256
- latestBlockHash: this.latestBlockHash,
1257
- cumulativeDepositedAbt: this.cumulativeDepositedAbt,
1258
- cumulativeWithdrawnAbt: this.cumulativeWithdrawnAbt,
1259
- pendingWithdrawAbt,
1260
- availableWithdrawReserveAbt: this.cumulativeDepositedAbt - this.cumulativeWithdrawnAbt - pendingWithdrawAbt,
1261
- pendingWithdrawCount: this.pendingWithdrawQueue.length,
1262
- issuedDirectVoucherCount: this.issuedDirectVouchers.size,
1263
- cancelledWithdrawCount: this.cancelledWithdrawTxHashes.size
1264
- };
1265
- }
1266
- /**
1267
- * Issue #1245:
1268
- * Returns the Circle `bridge.usdc.com`-style Web Portal configuration hosted by the ArcBridge Blocklet.
1269
- * Requires zero custom native wallet code (`walletRequired: 'STANDARD_WEB_EIP1193_ONLY'`).
1270
- */
1271
- getWebPortalConfig() {
1272
- return {
1273
- portalVersion: "1.0.0",
1274
- hostPlatform: "ARC_BRIDGE_BLOCKLET",
1275
- blockletDid: this.config.bridgeProposerDid,
1276
- didConnectSessionSupported: true,
1277
- zeroBridgeFee: true,
1278
- bridgeFeeBps: 0,
1279
- walletRequired: "STANDARD_WEB_EIP1193_ONLY",
1280
- bridgeId: this.config.bridgeId,
1281
- rollupAddress: this.config.rollupAddress,
1282
- verifyingContractAddress: this.config.verifyingContractAddress,
1283
- canonicalErc20AbtAddress: this.config.canonicalErc20AbtAddress,
1284
- ocapNativeAbtTokenAddress: this.config.ocapNativeAbtTokenAddress,
1285
- allowedEvmChainIds: [...this.config.allowedEvmChainIds],
1286
- allowedServicePaymentTokens: [...this.config.allowedServicePaymentTokens],
1287
- paused: this.paused,
1288
- eip712Domain: {
1289
- name: EIP712_BRIDGE_DOMAIN_NAME,
1290
- version: EIP712_BRIDGE_DOMAIN_VERSION,
1291
- verifyingContract: this.config.verifyingContractAddress
1292
- },
1293
- limits: {
1294
- minDepositAmount: this.config.minDepositAmount.toString(),
1295
- maxDepositAmount: this.config.maxDepositAmount.toString(),
1296
- minWithdrawAmount: this.config.minWithdrawAmount.toString(),
1297
- maxWithdrawAmount: this.config.maxWithdrawAmount.toString(),
1298
- maxDailyWithdrawAbt: this.config.maxDailyWithdrawAbt.toString(),
1299
- largeWithdrawTimelockThresholdAbt: this.config.largeWithdrawTimelockThresholdAbt.toString(),
1300
- timelockDelaySeconds: this.config.timelockDelaySeconds
1301
- },
1302
- deprecatedRollupProtocols: DEPRECATED_ROLLUP_PROTOCOL_TYPE_URLS
1303
- };
1304
- }
1305
- /**
1306
- * Issue #1245:
1307
- * Builds a wallet-agnostic EIP-1193 transaction execution plan for the ArcBridge Blocklet Web Portal
1308
- * (`bridge.usdc.com`-style one-click web experience without custom wallet bridge code).
1309
- */
1310
- buildWebPortalActionBundle(input) {
1311
- this.assertNotPaused();
1312
- if (!input || typeof input !== "object") throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: portal action input must be an object");
1313
- const approveSig = "approve(address,uint256)";
1314
- const approveSelector = computeSolidityFunctionSelector(approveSig);
1315
- const gatewayWordHex64 = this.config.verifyingContractAddress.slice(2).padStart(64, "0");
1316
- if (input.action === "DEPOSIT_FOR_NATIVE_ABT") {
1317
- const evmChainId = assertCleanString(input.evmChainId, "evmChainId");
1318
- if (!this.allowedChainSet.has(evmChainId)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: evmChainId ${evmChainId} is not permitted by this bridge`);
1319
- const recipientDid = assertCleanString(input.recipientDid, "recipientDid");
1320
- if (input.userEvmAddress !== void 0) assertEvmAddress(input.userEvmAddress, "userEvmAddress");
1321
- if (typeof input.amount !== "bigint" || input.amount < this.config.minDepositAmount || input.amount > this.config.maxDepositAmount) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: portal deposit amount (${String(input.amount)}) must be within [${this.config.minDepositAmount}, ${this.config.maxDepositAmount}]`);
1322
- const amountHex64 = uint256ToHex64(input.amount);
1323
- const approveCalldata = `${approveSelector}${gatewayWordHex64}${amountHex64}`;
1324
- const depositSig = "depositForNativeAbt(string,uint256)";
1325
- const depositSelector = computeSolidityFunctionSelector(depositSig);
1326
- const depositCalldata = `${depositSelector}${uint256ToHex64(64)}${amountHex64}${encodeAbiDynamicUtf8String(recipientDid)}`;
1327
- return {
1328
- action: "DEPOSIT_FOR_NATIVE_ABT",
1329
- hostPlatform: "ARC_BRIDGE_BLOCKLET",
1330
- blockletDid: this.config.bridgeProposerDid,
1331
- walletRequired: "STANDARD_WEB_EIP1193_ONLY",
1332
- bridgeId: this.config.bridgeId,
1333
- evmChainId,
1334
- verifyingContractAddress: this.config.verifyingContractAddress,
1335
- autoRelayerSponsoredOnOcap: true,
1336
- steps: [{
1337
- stepId: "ERC20_APPROVE",
1338
- description: "Approve canonical ERC-20 ABT to ArcEvmBridgeGateway",
1339
- evmChainId,
1340
- to: this.config.canonicalErc20AbtAddress,
1341
- valueHex: "0x0",
1342
- methodSignature: approveSig,
1343
- functionSelector: approveSelector,
1344
- calldataHex: approveCalldata,
1345
- args: {
1346
- spender: this.config.verifyingContractAddress,
1347
- amount: input.amount.toString()
1348
- }
1349
- }, {
1350
- stepId: "BRIDGE_DEPOSIT",
1351
- description: "Lock ERC-20 ABT and auto-mint 1:1 Native ABT on OCAP (Relayer-Sponsored)",
1352
- evmChainId,
1353
- to: this.config.verifyingContractAddress,
1354
- valueHex: "0x0",
1355
- methodSignature: depositSig,
1356
- functionSelector: depositSelector,
1357
- calldataHex: depositCalldata,
1358
- args: {
1359
- recipientDid,
1360
- amount: input.amount.toString()
1361
- }
1362
- }]
1363
- };
1364
- }
1365
- if (input.action === "CLAIM_WITH_DIRECT_VOUCHER") {
1366
- const voucher = this.getDirectWithdrawVoucher(input.ocapTxHash);
1367
- if (input.nowUnixSeconds !== void 0) {
1368
- if (!Number.isSafeInteger(input.nowUnixSeconds) || input.nowUnixSeconds <= 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: nowUnixSeconds must be a positive integer");
1369
- if (input.nowUnixSeconds > voucher.expiresAtUnixSeconds) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: direct withdraw voucher ${voucher.ocapTxHash} has expired`);
1370
- }
1371
- const claimSig = "claimWithdrawWithDirectVoucher(bytes32,address,uint256,uint256,bytes32,uint8[],bytes32[],bytes32[])";
1372
- const claimSelector = computeSolidityFunctionSelector(claimSig);
1373
- const txHashHex64 = voucher.ocapTxHash.slice(2);
1374
- const toWordHex64 = voucher.recipientEvmAddress.slice(2).padStart(64, "0");
1375
- const amountHex64 = uint256ToHex64(voucher.amount);
1376
- const expiresHex64 = uint256ToHex64(voucher.expiresAtUnixSeconds);
1377
- const digestHex64 = voucher.voucherDigest.slice(2);
1378
- const sortedSigs = [...voucher.validatorSignatures].sort((a, b) => {
1379
- if (a.evmSignerAddress && b.evmSignerAddress) return BigInt(a.evmSignerAddress) < BigInt(b.evmSignerAddress) ? -1 : BigInt(a.evmSignerAddress) > BigInt(b.evmSignerAddress) ? 1 : 0;
1380
- return 0;
1381
- });
1382
- const sigCount = sortedSigs.length;
1383
- const vOffsetHex64 = uint256ToHex64(256);
1384
- const rOffsetHex64 = uint256ToHex64((9 + sigCount) * 32);
1385
- const sOffsetHex64 = uint256ToHex64((8 + 2 * (1 + sigCount)) * 32);
1386
- const vValues = sortedSigs.map((sig) => sig.v ?? 27);
1387
- const rValues = sortedSigs.map((sig) => sig.r ?? sig.signatureDigest);
1388
- const sValues = sortedSigs.map((sig) => sig.s ?? computeValidatorVoucherSignatureDigest(voucher.bridgeId, sig.signatureDigest, sig.validatorDid));
1389
- const claimCalldata = `${claimSelector}${txHashHex64}${toWordHex64}${amountHex64}${expiresHex64}${digestHex64}${vOffsetHex64}${rOffsetHex64}${sOffsetHex64}${`${uint256ToHex64(sigCount)}${vValues.map((v) => uint256ToHex64(v)).join("")}`}${`${uint256ToHex64(sigCount)}${rValues.map((r) => r.slice(2)).join("")}`}${`${uint256ToHex64(sigCount)}${sValues.map((s) => s.slice(2)).join("")}`}`;
1390
- const isUnlocked = !voucher.timelocked || input.nowUnixSeconds !== void 0 && input.nowUnixSeconds >= voucher.unlocksAtUnixSeconds;
1391
- const claimPhase = !voucher.timelocked ? "IMMEDIATE_CLAIM" : isUnlocked ? "FINAL_UNLOCKED_CLAIM" : "TIMELOCK_INITIATION";
1392
- return {
1393
- action: "CLAIM_WITH_DIRECT_VOUCHER",
1394
- hostPlatform: "ARC_BRIDGE_BLOCKLET",
1395
- blockletDid: this.config.bridgeProposerDid,
1396
- walletRequired: "STANDARD_WEB_EIP1193_ONLY",
1397
- bridgeId: this.config.bridgeId,
1398
- evmChainId: voucher.evmChainId,
1399
- verifyingContractAddress: this.config.verifyingContractAddress,
1400
- autoRelayerSponsoredOnOcap: false,
1401
- timelockStatus: {
1402
- timelocked: voucher.timelocked,
1403
- unlocksAtUnixSeconds: voucher.unlocksAtUnixSeconds,
1404
- isUnlocked,
1405
- claimPhase
1406
- },
1407
- steps: [{
1408
- stepId: "CLAIM_DIRECT_VOUCHER",
1409
- description: "Claim 1:1 ERC-20 ABT with EIP-712 DirectWithdrawVoucher (Zero RollupBlock)",
1410
- evmChainId: voucher.evmChainId,
1411
- to: this.config.verifyingContractAddress,
1412
- valueHex: "0x0",
1413
- methodSignature: claimSig,
1414
- functionSelector: claimSelector,
1415
- calldataHex: claimCalldata,
1416
- args: {
1417
- ocapTxHash: voucher.ocapTxHash,
1418
- to: voucher.recipientEvmAddress,
1419
- amount: voucher.amount.toString(),
1420
- expiresAt: voucher.expiresAtUnixSeconds,
1421
- voucherDigest: voucher.voucherDigest,
1422
- v: vValues,
1423
- r: rValues,
1424
- s: sValues,
1425
- validatorSignatures: voucher.validatorSignatures.map((s) => ({ ...s }))
1426
- }
1427
- }]
1428
- };
1429
- }
1430
- if (input.action === "PAY_FOR_OCAP_SERVICE") {
1431
- const evmChainId = assertCleanString(input.evmChainId, "evmChainId");
1432
- if (!this.allowedChainSet.has(evmChainId)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: evmChainId ${evmChainId} is not permitted by this bridge`);
1433
- const orderId = assertBytes32Hex(input.orderId, "orderId");
1434
- if (orderId === ZERO_BYTES32_HASH) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: orderId cannot be zero bytes32");
1435
- if (this.processedServiceOrderIds.has(orderId)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: service orderId ${orderId} has already been paid`);
1436
- const recipientDid = assertCleanString(input.recipientDid, "recipientDid");
1437
- const serviceDid = assertCleanString(input.serviceDid, "serviceDid");
1438
- const paymentTokenAddress = assertEvmAddress(input.paymentTokenAddress, "paymentTokenAddress");
1439
- if (!this.allowedPaymentTokenSet.has(paymentTokenAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: paymentTokenAddress ${paymentTokenAddress} is not whitelisted for service payments`);
1440
- if (input.userEvmAddress !== void 0) assertEvmAddress(input.userEvmAddress, "userEvmAddress");
1441
- if (typeof input.amount !== "bigint" || input.amount <= 0n) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: service payment amount must be > 0n");
1442
- const amountHex64 = uint256ToHex64(input.amount);
1443
- const approveCalldata = `${approveSelector}${gatewayWordHex64}${amountHex64}`;
1444
- const paySig = "payForOcapService(bytes32,string,string,address,uint256)";
1445
- const paySelector = computeSolidityFunctionSelector(paySig);
1446
- const tokenWordHex64 = paymentTokenAddress.slice(2).padStart(64, "0");
1447
- const encodedRecipientHex = encodeAbiDynamicUtf8String(recipientDid);
1448
- const encodedServiceHex = encodeAbiDynamicUtf8String(serviceDid);
1449
- const offset1Hex64 = uint256ToHex64(160);
1450
- const offset2Hex64 = uint256ToHex64(160 + encodedRecipientHex.length / 2);
1451
- const payCalldata = `${paySelector}${orderId.slice(2)}${offset1Hex64}${offset2Hex64}${tokenWordHex64}${amountHex64}${encodedRecipientHex}${encodedServiceHex}`;
1452
- return {
1453
- action: "PAY_FOR_OCAP_SERVICE",
1454
- hostPlatform: "ARC_BRIDGE_BLOCKLET",
1455
- blockletDid: this.config.bridgeProposerDid,
1456
- walletRequired: "STANDARD_WEB_EIP1193_ONLY",
1457
- bridgeId: this.config.bridgeId,
1458
- evmChainId,
1459
- verifyingContractAddress: this.config.verifyingContractAddress,
1460
- autoRelayerSponsoredOnOcap: true,
1461
- steps: [{
1462
- stepId: "ERC20_APPROVE",
1463
- description: "Approve service payment token to ArcEvmBridgeGateway",
1464
- evmChainId,
1465
- to: paymentTokenAddress,
1466
- valueHex: "0x0",
1467
- methodSignature: approveSig,
1468
- functionSelector: approveSelector,
1469
- calldataHex: approveCalldata,
1470
- args: {
1471
- spender: this.config.verifyingContractAddress,
1472
- amount: input.amount.toString()
1473
- }
1474
- }, {
1475
- stepId: "PAY_FOR_SERVICE",
1476
- description: "Pay-Where-You-Are on EVM and auto-deliver service on OCAP",
1477
- evmChainId,
1478
- to: this.config.verifyingContractAddress,
1479
- valueHex: "0x0",
1480
- methodSignature: paySig,
1481
- functionSelector: paySelector,
1482
- calldataHex: payCalldata,
1483
- args: {
1484
- orderId,
1485
- recipientDid,
1486
- serviceDid,
1487
- paymentTokenAddress,
1488
- amount: input.amount.toString()
1489
- }
1490
- }]
1491
- };
1492
- }
1493
- throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: unsupported portal action");
1494
- }
1495
- /**
1496
- * Cloudflare Workers / Durable Objects / ArcBridge Blocklet Edge Handler (`fetch` & `scheduled` entry point):
1497
- * Verifies HMAC-SHA256 webhook authentication and anti-replay nonces for all mutating endpoints.
1498
- */
1499
- handleCloudflareEdgeRequest(req) {
1500
- if (req.method === "GET" && req.path === "/health") {
1501
- const state = this.getReserveWatermarkState();
1502
- return {
1503
- status: 200,
1504
- body: {
1505
- ok: true,
1506
- bridgeId: this.config.bridgeId,
1507
- rollupAddress: this.config.rollupAddress,
1508
- paused: state.paused,
1509
- latestBlockHeight: state.latestBlockHeight,
1510
- latestBlockHash: state.latestBlockHash,
1511
- cumulativeDepositedAbt: state.cumulativeDepositedAbt.toString(),
1512
- cumulativeWithdrawnAbt: state.cumulativeWithdrawnAbt.toString(),
1513
- pendingWithdrawAbt: state.pendingWithdrawAbt.toString(),
1514
- availableWithdrawReserveAbt: state.availableWithdrawReserveAbt.toString(),
1515
- pendingWithdrawCount: state.pendingWithdrawCount,
1516
- issuedDirectVoucherCount: state.issuedDirectVoucherCount,
1517
- cancelledWithdrawCount: state.cancelledWithdrawCount
1518
- }
1519
- };
1520
- }
1521
- if (req.method === "GET" && req.path === "/portal/config") return {
1522
- status: 200,
1523
- body: {
1524
- ok: true,
1525
- portalConfig: this.getWebPortalConfig()
1526
- }
1527
- };
1528
- const bodyJson = req.bodyJson ?? "";
1529
- if (Buffer.byteLength(bodyJson, "utf8") > MAX_EDGE_WEBHOOK_BODY_BYTES) return {
1530
- status: 413,
1531
- body: {
1532
- ok: false,
1533
- error: "SimplifiedEvmBridge: request body exceeds maximum allowed size"
1534
- }
1535
- };
1536
- if (req.method === "POST" && req.path === "/portal/build-tx") try {
1537
- const parsed = JSON.parse(bodyJson || "{}");
1538
- const action = String(parsed.action ?? "");
1539
- let actionInput;
1540
- if (action === "DEPOSIT_FOR_NATIVE_ABT") actionInput = {
1541
- action: "DEPOSIT_FOR_NATIVE_ABT",
1542
- evmChainId: String(parsed.evmChainId ?? ""),
1543
- recipientDid: String(parsed.recipientDid ?? ""),
1544
- amount: parseStrictUint256JsonValue(parsed.amount, "amount"),
1545
- userEvmAddress: parsed.userEvmAddress !== void 0 ? String(parsed.userEvmAddress) : void 0
1546
- };
1547
- else if (action === "CLAIM_WITH_DIRECT_VOUCHER") {
1548
- let resolvedNowUnixSeconds = req.nowUnixSeconds;
1549
- if (parsed.nowUnixSeconds !== void 0) {
1550
- if (typeof parsed.nowUnixSeconds !== "number" || !Number.isSafeInteger(parsed.nowUnixSeconds)) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: nowUnixSeconds must be a positive integer");
1551
- resolvedNowUnixSeconds = parsed.nowUnixSeconds;
1552
- }
1553
- actionInput = {
1554
- action: "CLAIM_WITH_DIRECT_VOUCHER",
1555
- ocapTxHash: String(parsed.ocapTxHash ?? ""),
1556
- nowUnixSeconds: resolvedNowUnixSeconds
1557
- };
1558
- } else if (action === "PAY_FOR_OCAP_SERVICE") actionInput = {
1559
- action: "PAY_FOR_OCAP_SERVICE",
1560
- evmChainId: String(parsed.evmChainId ?? ""),
1561
- orderId: String(parsed.orderId ?? ""),
1562
- recipientDid: String(parsed.recipientDid ?? ""),
1563
- serviceDid: String(parsed.serviceDid ?? ""),
1564
- paymentTokenAddress: String(parsed.paymentTokenAddress ?? ""),
1565
- amount: parseStrictUint256JsonValue(parsed.amount, "amount"),
1566
- userEvmAddress: parsed.userEvmAddress !== void 0 ? String(parsed.userEvmAddress) : void 0
1567
- };
1568
- else throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: unsupported portal action ${action}`);
1569
- return {
1570
- status: 200,
1571
- body: {
1572
- ok: true,
1573
- actionBundle: this.buildWebPortalActionBundle(actionInput)
1574
- }
1575
- };
1576
- } catch (err) {
1577
- return {
1578
- status: 400,
1579
- body: {
1580
- ok: false,
1581
- error: err instanceof Error ? err.message : String(err)
1582
- }
1583
- };
1584
- }
1585
- if (req.method === "POST" && req.path === "/query/withdraw-voucher") try {
1586
- const parsed = JSON.parse(bodyJson || "{}");
1587
- const voucher = this.getDirectWithdrawVoucher(String(parsed.ocapTxHash ?? ""));
1588
- return {
1589
- status: 200,
1590
- body: {
1591
- ok: true,
1592
- voucher: {
1593
- ...voucher,
1594
- amount: voucher.amount.toString()
1595
- }
1596
- }
1597
- };
1598
- } catch (err) {
1599
- return {
1600
- status: 400,
1601
- body: {
1602
- ok: false,
1603
- error: err instanceof Error ? err.message : String(err)
1604
- }
1605
- };
1606
- }
1607
- if (req.method === "POST" && req.path === "/query/withdraw-proof") try {
1608
- const parsed = JSON.parse(bodyJson || "{}");
1609
- const bundle = this.generateWithdrawClaimProof(String(parsed.ocapTxHash ?? ""));
1610
- return {
1611
- status: 200,
1612
- body: {
1613
- ok: true,
1614
- proofBundle: {
1615
- ...bundle,
1616
- amount: bundle.amount.toString()
1617
- }
1618
- }
1619
- };
1620
- } catch (err) {
1621
- return {
1622
- status: 400,
1623
- body: {
1624
- ok: false,
1625
- error: err instanceof Error ? err.message : String(err)
1626
- }
1627
- };
1628
- }
1629
- const normalizedHeaders = {};
1630
- for (const [k, v] of Object.entries(req.headers ?? {})) normalizedHeaders[k.toLowerCase()] = v;
1631
- const sigHeader = normalizedHeaders["x-arc-bridge-signature"] ?? "";
1632
- const tsHeader = normalizedHeaders["x-arc-bridge-timestamp"] ?? "";
1633
- const rawNonceHeader = normalizedHeaders["x-arc-bridge-nonce"] ?? "";
1634
- const nowUnixSeconds = req.nowUnixSeconds ?? Math.floor(Date.now() / 1e3);
1635
- let nonceHeader = "";
1636
- try {
1637
- nonceHeader = assertCleanString(rawNonceHeader, "nonceHeader");
1638
- } catch {
1639
- nonceHeader = "";
1640
- }
1641
- const tsSeconds = Number(tsHeader);
1642
- if (!Number.isSafeInteger(tsSeconds) || Math.abs(nowUnixSeconds - tsSeconds) > MAX_EDGE_WEBHOOK_SKEW_SECONDS || nonceHeader.length < 8 || nonceHeader.length > 128 || !/^[a-fA-F0-9]{64}$/.test(sigHeader)) return {
1643
- status: 401,
1644
- body: {
1645
- ok: false,
1646
- error: "SimplifiedEvmBridge: invalid or expired edge webhook authentication headers"
1647
- }
1648
- };
1649
- for (const [oldNonce, oldTs] of this.processedWebhookNonces.entries()) if (nowUnixSeconds - oldTs > MAX_EDGE_WEBHOOK_SKEW_SECONDS * 2) this.processedWebhookNonces.delete(oldNonce);
1650
- if (this.processedWebhookNonces.has(nonceHeader)) return {
1651
- status: 401,
1652
- body: {
1653
- ok: false,
1654
- error: "SimplifiedEvmBridge: duplicate webhook nonce replay rejected"
1655
- }
1656
- };
1657
- if (this.processedWebhookNonces.size >= MAX_TRACKED_WEBHOOK_NONCES) return {
1658
- status: 429,
1659
- body: {
1660
- ok: false,
1661
- error: "SimplifiedEvmBridge: webhook nonce rate limit capacity reached"
1662
- }
1663
- };
1664
- const expectedHmac = computeEdgeWebhookHmac(this.config.webhookHmacSecret, tsSeconds, nonceHeader, req.path, bodyJson);
1665
- const sigBuf = Buffer.from(sigHeader.toLowerCase(), "hex");
1666
- const expBuf = Buffer.from(expectedHmac.toLowerCase(), "hex");
1667
- if (sigBuf.length !== expBuf.length || !timingSafeEqual(sigBuf, expBuf)) return {
1668
- status: 401,
1669
- body: {
1670
- ok: false,
1671
- error: "SimplifiedEvmBridge: webhook HMAC signature mismatch"
1672
- }
1673
- };
1674
- try {
1675
- const payload = JSON.parse(bodyJson || "{}");
1676
- if (req.method === "POST" && req.path === "/webhook/evm-service-pay") {
1677
- const instruction = this.ingestEvmServicePaymentEvent({
1678
- evmChainId: String(payload.evmChainId ?? ""),
1679
- evmTxHash: String(payload.evmTxHash ?? ""),
1680
- logIndex: Number(payload.logIndex),
1681
- confirmations: Number(payload.confirmations),
1682
- reorged: Boolean(payload.reorged),
1683
- orderId: String(payload.orderId ?? ""),
1684
- payerEvmAddress: String(payload.payerEvmAddress ?? ""),
1685
- recipientDid: String(payload.recipientDid ?? ""),
1686
- serviceDid: String(payload.serviceDid ?? ""),
1687
- paymentTokenAddress: String(payload.paymentTokenAddress ?? ""),
1688
- amount: parseStrictUint256JsonValue(payload.amount, "amount"),
1689
- deliverableNftDid: payload.deliverableNftDid ? String(payload.deliverableNftDid) : void 0
1690
- });
1691
- this.processedWebhookNonces.set(nonceHeader, tsSeconds);
1692
- return {
1693
- status: 200,
1694
- body: {
1695
- ok: true,
1696
- instructionId: instruction.instructionId,
1697
- depositProofDigest: instruction.depositProofDigest,
1698
- paidAmount: instruction.paidAmount.toString()
1699
- }
1700
- };
1701
- }
1702
- if (req.method === "POST" && req.path === "/webhook/evm-abt-deposit") {
1703
- const instruction = this.ingestEvmAbtDepositEvent({
1704
- evmChainId: String(payload.evmChainId ?? ""),
1705
- evmTxHash: String(payload.evmTxHash ?? ""),
1706
- logIndex: Number(payload.logIndex),
1707
- confirmations: Number(payload.confirmations),
1708
- reorged: Boolean(payload.reorged),
1709
- depositorEvmAddress: String(payload.depositorEvmAddress ?? ""),
1710
- recipientDid: String(payload.recipientDid ?? ""),
1711
- tokenAddress: String(payload.tokenAddress ?? ""),
1712
- amount: parseStrictUint256JsonValue(payload.amount, "amount"),
1713
- actualFee: payload.actualFee !== void 0 ? parseStrictUint256JsonValue(payload.actualFee, "actualFee") : 0n
1714
- });
1715
- this.processedWebhookNonces.set(nonceHeader, tsSeconds);
1716
- return {
1717
- status: 200,
1718
- body: {
1719
- ok: true,
1720
- instructionId: instruction.instructionId,
1721
- value: instruction.value.toString(),
1722
- cumulativeDepositedAbt: instruction.cumulativeDepositedAbt.toString()
1723
- }
1724
- };
1725
- }
1726
- if (req.method === "POST" && req.path === "/webhook/ocap-abt-withdraw-voucher") {
1727
- const issuedAtUnixSeconds = Number(payload.issuedAtUnixSeconds ?? nowUnixSeconds);
1728
- const expiresAtUnixSeconds = Number(payload.expiresAtUnixSeconds ?? nowUnixSeconds + 86400);
1729
- if (!Number.isSafeInteger(issuedAtUnixSeconds) || Math.abs(nowUnixSeconds - issuedAtUnixSeconds) > MAX_EDGE_WEBHOOK_SKEW_SECONDS || expiresAtUnixSeconds <= nowUnixSeconds) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: voucher issuedAtUnixSeconds/expiresAtUnixSeconds outside valid edge window");
1730
- const voucher = this.issueDirectWithdrawVoucher({
1731
- evmChainId: String(payload.evmChainId ?? ""),
1732
- ocapTxHash: String(payload.ocapTxHash ?? ""),
1733
- fromDid: String(payload.fromDid ?? ""),
1734
- recipientEvmAddress: String(payload.recipientEvmAddress ?? ""),
1735
- amount: parseStrictUint256JsonValue(payload.amount, "amount"),
1736
- issuedAtUnixSeconds,
1737
- expiresAtUnixSeconds,
1738
- validatorSignatures: Array.isArray(payload.validatorSignatures) ? payload.validatorSignatures : []
1739
- });
1740
- this.processedWebhookNonces.set(nonceHeader, tsSeconds);
1741
- return {
1742
- status: 200,
1743
- body: {
1744
- ok: true,
1745
- voucher: {
1746
- ...voucher,
1747
- amount: voucher.amount.toString()
1748
- }
1749
- }
1750
- };
1751
- }
1752
- if (req.method === "POST" && req.path === "/webhook/guardian-pause") {
1753
- const res = this.setBridgePaused({
1754
- guardianDid: String(payload.guardianDid ?? ""),
1755
- paused: Boolean(payload.paused)
1756
- });
1757
- this.processedWebhookNonces.set(nonceHeader, tsSeconds);
1758
- return {
1759
- status: 200,
1760
- body: {
1761
- ok: true,
1762
- paused: res.paused
1763
- }
1764
- };
1765
- }
1766
- if (req.method === "POST" && req.path === "/webhook/guardian-cancel-withdraw") {
1767
- const res = this.cancelTimelockedWithdraw({
1768
- guardianDid: String(payload.guardianDid ?? ""),
1769
- ocapTxHash: String(payload.ocapTxHash ?? ""),
1770
- nowUnixSeconds
1771
- });
1772
- this.processedWebhookNonces.set(nonceHeader, tsSeconds);
1773
- return {
1774
- status: 200,
1775
- body: {
1776
- ok: true,
1777
- cancelledTxHash: res.cancelledTxHash,
1778
- refundedReserveAbt: res.refundedReserveAbt.toString()
1779
- }
1780
- };
1781
- }
1782
- if (req.method === "POST" && req.path === "/webhook/ocap-abt-withdraw") {
1783
- const res = this.enqueueOcapAbtWithdraw({
1784
- ocapTxHash: String(payload.ocapTxHash ?? ""),
1785
- fromDid: String(payload.fromDid ?? ""),
1786
- recipientEvmAddress: String(payload.recipientEvmAddress ?? ""),
1787
- amount: parseStrictUint256JsonValue(payload.amount, "amount")
1788
- });
1789
- this.processedWebhookNonces.set(nonceHeader, tsSeconds);
1790
- return {
1791
- status: 200,
1792
- body: {
1793
- ok: true,
1794
- queuedCount: res.queuedCount,
1795
- pendingWithdrawTotal: res.pendingWithdrawTotal.toString()
1796
- }
1797
- };
1798
- }
1799
- if (req.method === "POST" && req.path === "/cron/seal-withdraw-block") {
1800
- const block = this.sealRollupWithdrawBlock({
1801
- validatorSignatures: Array.isArray(payload.validatorSignatures) ? payload.validatorSignatures : [],
1802
- sealedAtUnixSeconds: nowUnixSeconds
1803
- });
1804
- this.processedWebhookNonces.set(nonceHeader, tsSeconds);
1805
- return {
1806
- status: 200,
1807
- body: {
1808
- ok: true,
1809
- height: block.height,
1810
- blockHash: block.blockHash,
1811
- merkleRoot: block.merkleRoot,
1812
- txsHash: block.txsHash
1813
- }
1814
- };
1815
- }
1816
- return {
1817
- status: 404,
1818
- body: {
1819
- ok: false,
1820
- error: `Unsupported route ${req.method} ${req.path}`
1821
- }
1822
- };
1823
- } catch (err) {
1824
- return {
1825
- status: 400,
1826
- body: {
1827
- ok: false,
1828
- error: err instanceof Error ? err.message : String(err)
1829
- }
1830
- };
1831
- }
1832
- }
1833
- /**
1834
- * Exports a JSON-serializable state snapshot for Cloudflare Durable Object storage (`ctx.storage.put`).
1835
- */
1836
- exportDurableStateSnapshot() {
1837
- return {
1838
- schemaVersion: 1,
1839
- config: {
1840
- ...this.config,
1841
- minDepositAmount: this.config.minDepositAmount.toString(),
1842
- maxDepositAmount: this.config.maxDepositAmount.toString(),
1843
- minWithdrawAmount: this.config.minWithdrawAmount.toString(),
1844
- maxWithdrawAmount: this.config.maxWithdrawAmount.toString(),
1845
- maxDailyWithdrawAbt: this.config.maxDailyWithdrawAbt.toString(),
1846
- largeWithdrawTimelockThresholdAbt: this.config.largeWithdrawTimelockThresholdAbt.toString()
1847
- },
1848
- paused: this.paused,
1849
- latestBlockHeight: this.latestBlockHeight,
1850
- latestBlockHash: this.latestBlockHash,
1851
- cumulativeDepositedAbt: this.cumulativeDepositedAbt.toString(),
1852
- cumulativeWithdrawnAbt: this.cumulativeWithdrawnAbt.toString(),
1853
- processedEventKeys: Array.from(this.processedEventKeys),
1854
- processedServiceOrderIds: Array.from(this.processedServiceOrderIds),
1855
- processedWithdrawTxHashes: Array.from(this.processedWithdrawTxHashes),
1856
- cancelledWithdrawTxHashes: Array.from(this.cancelledWithdrawTxHashes),
1857
- dailyWithdrawnByDay: Array.from(this.dailyWithdrawnByDay.entries()).map(([dayBucket, withdrawnAbt]) => ({
1858
- dayBucket,
1859
- withdrawnAbt: withdrawnAbt.toString()
1860
- })),
1861
- processedWebhookNonces: Array.from(this.processedWebhookNonces.entries()).map(([nonce, timestampSeconds]) => ({
1862
- nonce,
1863
- timestampSeconds
1864
- })),
1865
- pendingWithdrawQueue: this.pendingWithdrawQueue.map((item) => ({
1866
- ...item,
1867
- amount: item.amount.toString()
1868
- })),
1869
- sealedBlocks: Array.from(this.sealedBlocks.values()).map((b) => ({
1870
- ...b,
1871
- withdrawTxs: b.withdrawTxs.map((tx) => ({
1872
- ...tx,
1873
- amount: tx.amount.toString()
1874
- }))
1875
- })),
1876
- issuedDirectVouchers: Array.from(this.issuedDirectVouchers.values()).map((v) => ({
1877
- ...v,
1878
- amount: v.amount.toString()
1879
- }))
1880
- };
1881
- }
1882
- /**
1883
- * Restores an `OcapSimplifiedEvmBridgeNode` instance from a Cloudflare Durable Object state snapshot.
1884
- * Enforces full Red-Team conservation of value, replay-set synchronization, block hash linkage, and
1885
- * direct voucher EIP-712 signature verification (`RT-1241-1`).
1886
- */
1887
- static fromDurableStateSnapshot(snapshot) {
1888
- if (!snapshot || snapshot.schemaVersion !== 1 || !snapshot.config) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid durable state snapshot");
1889
- const node = new OcapSimplifiedEvmBridgeNode({
1890
- ...snapshot.config,
1891
- minDepositAmount: parseStrictUint256JsonValue(snapshot.config.minDepositAmount, "snapshot.minDepositAmount"),
1892
- maxDepositAmount: parseStrictUint256JsonValue(snapshot.config.maxDepositAmount, "snapshot.maxDepositAmount"),
1893
- minWithdrawAmount: parseStrictUint256JsonValue(snapshot.config.minWithdrawAmount, "snapshot.minWithdrawAmount"),
1894
- maxWithdrawAmount: parseStrictUint256JsonValue(snapshot.config.maxWithdrawAmount, "snapshot.maxWithdrawAmount"),
1895
- maxDailyWithdrawAbt: snapshot.config.maxDailyWithdrawAbt !== void 0 ? parseStrictUint256JsonValue(snapshot.config.maxDailyWithdrawAbt, "snapshot.maxDailyWithdrawAbt") : void 0,
1896
- largeWithdrawTimelockThresholdAbt: snapshot.config.largeWithdrawTimelockThresholdAbt !== void 0 ? parseStrictUint256JsonValue(snapshot.config.largeWithdrawTimelockThresholdAbt, "snapshot.largeWithdrawTimelockThresholdAbt") : void 0
1897
- });
1898
- node.paused = Boolean(snapshot.paused);
1899
- if (!Number.isSafeInteger(snapshot.latestBlockHeight) || snapshot.latestBlockHeight < 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid snapshot.latestBlockHeight");
1900
- node.latestBlockHeight = snapshot.latestBlockHeight;
1901
- node.latestBlockHash = assertBytes32Hex(snapshot.latestBlockHash, "snapshot.latestBlockHash");
1902
- node.cumulativeDepositedAbt = parseStrictUint256JsonValue(snapshot.cumulativeDepositedAbt, "snapshot.cumulativeDepositedAbt");
1903
- node.cumulativeWithdrawnAbt = parseStrictUint256JsonValue(snapshot.cumulativeWithdrawnAbt, "snapshot.cumulativeWithdrawnAbt");
1904
- for (const k of snapshot.processedEventKeys) node.processedEventKeys.add(assertCleanString(k, "snapshot.eventKey"));
1905
- for (const id of snapshot.processedServiceOrderIds) {
1906
- const cleanId = assertBytes32Hex(id, "snapshot.orderId");
1907
- if (cleanId === ZERO_BYTES32_HASH) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: snapshot orderId cannot be zero bytes32");
1908
- node.processedServiceOrderIds.add(cleanId);
1909
- }
1910
- for (const txHash of snapshot.processedWithdrawTxHashes) {
1911
- const cleanHash = assertBytes32Hex(txHash, "snapshot.withdrawTxHash");
1912
- if (cleanHash === ZERO_BYTES32_HASH) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: snapshot withdrawTxHash cannot be zero bytes32");
1913
- node.processedWithdrawTxHashes.add(cleanHash);
1914
- }
1915
- for (const txHash of snapshot.cancelledWithdrawTxHashes ?? []) {
1916
- const cleanHash = assertBytes32Hex(txHash, "snapshot.cancelledWithdrawTxHash");
1917
- node.cancelledWithdrawTxHashes.add(cleanHash);
1918
- }
1919
- for (const entry of snapshot.dailyWithdrawnByDay ?? []) {
1920
- if (!Number.isSafeInteger(entry.dayBucket) || entry.dayBucket < 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid snapshot dayBucket");
1921
- if (node.dailyWithdrawnByDay.has(entry.dayBucket)) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: duplicate snapshot dayBucket");
1922
- const withdrawnAbt = parseStrictUint256JsonValue(entry.withdrawnAbt, "snapshot.dailyWithdrawnAbt");
1923
- if (withdrawnAbt <= 0n || withdrawnAbt > node.config.maxDailyWithdrawAbt) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: snapshot dailyWithdrawnAbt outside valid range (1..maxDailyWithdrawAbt)");
1924
- node.dailyWithdrawnByDay.set(entry.dayBucket, withdrawnAbt);
1925
- }
1926
- for (const entry of snapshot.processedWebhookNonces ?? []) {
1927
- const cleanNonce = assertCleanString(entry.nonce, "snapshot.nonce");
1928
- if (!Number.isSafeInteger(entry.timestampSeconds) || entry.timestampSeconds <= 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid snapshot nonce timestamp");
1929
- node.processedWebhookNonces.set(cleanNonce, entry.timestampSeconds);
1930
- }
1931
- const seenWithdrawTxsAcrossCollections = /* @__PURE__ */ new Set();
1932
- const assertValidSnapshotWithdrawAmount = (amt, label) => {
1933
- if (amt < node.config.minWithdrawAmount || amt > node.config.maxWithdrawAmount) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: ${label} (${amt}) outside configured withdraw bounds`);
1934
- };
1935
- const registerCollectionTxHash = (rawHash, label) => {
1936
- const cleanHash = assertBytes32Hex(rawHash, label);
1937
- if (cleanHash === ZERO_BYTES32_HASH) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} cannot be zero bytes32`);
1938
- if (seenWithdrawTxsAcrossCollections.has(cleanHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate withdraw tx ${cleanHash} across snapshot collections`);
1939
- if (!node.processedWithdrawTxHashes.has(cleanHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot withdraw tx ${cleanHash} missing from processedWithdrawTxHashes`);
1940
- seenWithdrawTxsAcrossCollections.add(cleanHash);
1941
- return cleanHash;
1942
- };
1943
- let pendingTotal = 0n;
1944
- for (const item of snapshot.pendingWithdrawQueue) {
1945
- const cleanTxHash = registerCollectionTxHash(item.ocapTxHash, "snapshot.pending.ocapTxHash");
1946
- const amount = parseStrictUint256JsonValue(item.amount, "snapshot.pending.amount");
1947
- assertValidSnapshotWithdrawAmount(amount, "snapshot.pending.amount");
1948
- pendingTotal += amount;
1949
- node.pendingWithdrawQueue.push({
1950
- ocapTxHash: cleanTxHash,
1951
- fromDid: assertCleanString(item.fromDid, "snapshot.pending.fromDid"),
1952
- recipientEvmAddress: assertEvmAddress(item.recipientEvmAddress, "snapshot.pending.recipientEvmAddress"),
1953
- amount
1954
- });
1955
- }
1956
- let sealedTotal = 0n;
1957
- const expectedDailyTotals = /* @__PURE__ */ new Map();
1958
- const addExpectedDailyWithdraw = (unixSeconds, amt, label) => {
1959
- if (!Number.isSafeInteger(unixSeconds) || unixSeconds <= 0) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: invalid ${label} timestamp`);
1960
- const dayBucket = Math.floor(unixSeconds / 86400);
1961
- const next = (expectedDailyTotals.get(dayBucket) ?? 0n) + amt;
1962
- if (next > node.config.maxDailyWithdrawAbt) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot dayBucket ${dayBucket} withdraw total (${next}) exceeds maxDailyWithdrawAbt (${node.config.maxDailyWithdrawAbt})`);
1963
- expectedDailyTotals.set(dayBucket, next);
1964
- };
1965
- let expectedPrevHash = node.config.genesisBlockHash;
1966
- const sortedBlocks = [...snapshot.sealedBlocks].sort((a, b) => a.height - b.height);
1967
- if (sortedBlocks.length !== node.latestBlockHeight) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: snapshot sealedBlocks count does not match latestBlockHeight");
1968
- for (let idx = 0; idx < sortedBlocks.length; idx++) {
1969
- const b = sortedBlocks[idx];
1970
- const expectedHeight = idx + 1;
1971
- if (b.height !== expectedHeight) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: non-contiguous sealed block height ${b.height} (expected ${expectedHeight})`);
1972
- if (!Array.isArray(b.withdrawTxs) || b.withdrawTxs.length === 0 || b.withdrawTxs.length > node.config.maxBlockSize) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid sealed block withdrawTxs count");
1973
- let blockBatchTotal = 0n;
1974
- const withdrawTxs = b.withdrawTxs.map((tx) => {
1975
- const cleanTxHash = registerCollectionTxHash(tx.ocapTxHash, "snapshot.sealed.ocapTxHash");
1976
- const amount = parseStrictUint256JsonValue(tx.amount, "snapshot.sealed.amount");
1977
- assertValidSnapshotWithdrawAmount(amount, "snapshot.sealed.amount");
1978
- sealedTotal += amount;
1979
- blockBatchTotal += amount;
1980
- return {
1981
- ocapTxHash: cleanTxHash,
1982
- fromDid: assertCleanString(tx.fromDid, "snapshot.sealed.fromDid"),
1983
- recipientEvmAddress: assertEvmAddress(tx.recipientEvmAddress, "snapshot.sealed.recipientEvmAddress"),
1984
- amount
1985
- };
1986
- });
1987
- addExpectedDailyWithdraw(b.sealedAtUnixSeconds, blockBatchTotal, "snapshot.sealed.sealedAtUnixSeconds");
1988
- const previousHash = assertBytes32Hex(b.previousHash, "snapshot.sealed.previousHash");
1989
- if (previousHash !== expectedPrevHash) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: sealed block ${b.height} previousHash mismatch`);
1990
- const merkleRoot = assertBytes32Hex(b.merkleRoot, "snapshot.sealed.merkleRoot");
1991
- const txsHash = assertBytes32Hex(b.txsHash, "snapshot.sealed.txsHash");
1992
- const blockHash = assertBytes32Hex(b.blockHash, "snapshot.sealed.blockHash");
1993
- const computedTree = buildEvmBridgeMerkleTree(withdrawTxs);
1994
- const computedTxsHash = computeEvmBridgeTxsHash(withdrawTxs.map((tx) => tx.ocapTxHash));
1995
- const computedBlockHash = computeEvmBridgeBlockHash({
1996
- height: b.height,
1997
- previousHash,
1998
- merkleRoot: computedTree.merkleRoot,
1999
- txsHash: computedTxsHash
2000
- });
2001
- if (merkleRoot !== computedTree.merkleRoot || txsHash !== computedTxsHash || blockHash !== computedBlockHash) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: sealed block ${b.height} cryptographic header verification failed`);
2002
- if (!Array.isArray(b.validatorSigners) || b.validatorSigners.length < node.config.minValidatorSignatures) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: sealed block ${b.height} validatorSigners quorum not met`);
2003
- const seenBlockSigners = /* @__PURE__ */ new Set();
2004
- for (const signerDid of b.validatorSigners) {
2005
- const cleanSigner = assertCleanString(signerDid, "snapshot.sealed.validatorSigner");
2006
- if (!node.validatorSet.has(cleanSigner) || seenBlockSigners.has(cleanSigner)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: sealed block ${b.height} contains unauthorized or duplicate validatorSigner`);
2007
- seenBlockSigners.add(cleanSigner);
2008
- }
2009
- const sealed = {
2010
- height: b.height,
2011
- previousHash,
2012
- merkleRoot,
2013
- txsHash,
2014
- blockHash,
2015
- withdrawTxs,
2016
- validatorSigners: [...b.validatorSigners],
2017
- sealedAtUnixSeconds: b.sealedAtUnixSeconds
2018
- };
2019
- node.sealedBlocks.set(sealed.height, sealed);
2020
- for (const tx of withdrawTxs) node.withdrawTxToBlockHeight.set(tx.ocapTxHash, sealed.height);
2021
- expectedPrevHash = blockHash;
2022
- }
2023
- if (node.latestBlockHash !== expectedPrevHash) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: snapshot latestBlockHash does not match tip of sealedBlocks");
2024
- let voucherTotal = 0n;
2025
- const seenCancelledVouchers = /* @__PURE__ */ new Set();
2026
- for (const v of snapshot.issuedDirectVouchers ?? []) {
2027
- const cleanTxHash = registerCollectionTxHash(v.ocapTxHash, "snapshot.voucher.ocapTxHash");
2028
- const amount = parseStrictUint256JsonValue(v.amount, "snapshot.voucher.amount");
2029
- assertValidSnapshotWithdrawAmount(amount, "snapshot.voucher.amount");
2030
- const isCancelledFlag = Boolean(v.cancelled);
2031
- if (isCancelledFlag !== node.cancelledWithdrawTxHashes.has(cleanTxHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot voucher ${cleanTxHash} cancelled state desynchronized from cancelledWithdrawTxHashes`);
2032
- const expectedTimelocked = amount >= node.config.largeWithdrawTimelockThresholdAbt;
2033
- const expectedUnlocksAt = expectedTimelocked ? v.issuedAtUnixSeconds + node.config.timelockDelaySeconds : v.issuedAtUnixSeconds;
2034
- if (Boolean(v.timelocked) !== expectedTimelocked || v.unlocksAtUnixSeconds !== expectedUnlocksAt || expectedTimelocked && v.expiresAtUnixSeconds <= expectedUnlocksAt) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot voucher ${cleanTxHash} timelock metadata tampered`);
2035
- if (isCancelledFlag) {
2036
- if (!expectedTimelocked) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: non-timelocked voucher ${cleanTxHash} cannot be marked cancelled in snapshot`);
2037
- seenCancelledVouchers.add(cleanTxHash);
2038
- } else {
2039
- voucherTotal += amount;
2040
- addExpectedDailyWithdraw(v.issuedAtUnixSeconds, amount, "snapshot.voucher.issuedAtUnixSeconds");
2041
- }
2042
- const voucherDigest = assertBytes32Hex(v.voucherDigest, "snapshot.voucher.voucherDigest");
2043
- const restoredVoucher = {
2044
- voucherDigest,
2045
- eip712DomainSeparator: assertBytes32Hex(v.eip712DomainSeparator, "snapshot.voucher.eip712DomainSeparator"),
2046
- eip712StructHash: assertBytes32Hex(v.eip712StructHash, "snapshot.voucher.eip712StructHash"),
2047
- verifyingContractAddress: assertEvmAddress(v.verifyingContractAddress, "snapshot.voucher.verifyingContractAddress"),
2048
- bridgeId: assertCleanString(v.bridgeId, "snapshot.voucher.bridgeId"),
2049
- evmChainId: assertCleanString(v.evmChainId, "snapshot.voucher.evmChainId"),
2050
- ocapTxHash: cleanTxHash,
2051
- fromDid: assertCleanString(v.fromDid, "snapshot.voucher.fromDid"),
2052
- recipientEvmAddress: assertEvmAddress(v.recipientEvmAddress, "snapshot.voucher.recipientEvmAddress"),
2053
- amount,
2054
- issuedAtUnixSeconds: v.issuedAtUnixSeconds,
2055
- expiresAtUnixSeconds: v.expiresAtUnixSeconds,
2056
- timelocked: expectedTimelocked,
2057
- unlocksAtUnixSeconds: expectedUnlocksAt,
2058
- cancelled: isCancelledFlag,
2059
- validatorSigners: [...v.validatorSigners],
2060
- validatorSignatures: v.validatorSignatures.map((s) => {
2061
- const restoredSig = {
2062
- validatorDid: assertCleanString(s.validatorDid, "snapshot.voucher.validatorDid"),
2063
- signatureDigest: assertBytes32Hex(s.signatureDigest, "snapshot.voucher.signatureDigest")
2064
- };
2065
- if (s.v !== void 0 && s.r && s.s) {
2066
- restoredSig.evmSignerAddress = ecrecoverEvmAddress(voucherDigest, s.v, s.r, s.s);
2067
- restoredSig.v = s.v;
2068
- restoredSig.r = assertBytes32Hex(s.r, "snapshot.voucher.r");
2069
- restoredSig.s = assertBytes32Hex(s.s, "snapshot.voucher.s");
2070
- }
2071
- return restoredSig;
2072
- })
2073
- };
2074
- if (!verifyDirectWithdrawVoucher({
2075
- ...restoredVoucher,
2076
- cancelled: false
2077
- }, {
2078
- bridgeId: node.config.bridgeId,
2079
- verifyingContractAddress: node.config.verifyingContractAddress,
2080
- allowedEvmChainIds: node.config.allowedEvmChainIds,
2081
- validatorDids: node.config.validatorDids,
2082
- minValidatorSignatures: node.config.minValidatorSignatures
2083
- })) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: restored direct withdraw voucher ${cleanTxHash} failed cryptographic verification`);
2084
- node.issuedDirectVouchers.set(cleanTxHash, restoredVoucher);
2085
- }
2086
- if (seenCancelledVouchers.size !== node.cancelledWithdrawTxHashes.size) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: snapshot cancelledWithdrawTxHashes contains orphan tx hashes");
2087
- if (node.dailyWithdrawnByDay.size !== expectedDailyTotals.size) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: snapshot dailyWithdrawnByDay desynchronized from sealed blocks and active vouchers");
2088
- for (const [dayBucket, expectedAmt] of expectedDailyTotals.entries()) if (node.dailyWithdrawnByDay.get(dayBucket) !== expectedAmt) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot dailyWithdrawnByDay mismatch for dayBucket ${dayBucket}`);
2089
- if (sealedTotal + voucherTotal !== node.cumulativeWithdrawnAbt) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot cumulativeWithdrawnAbt (${node.cumulativeWithdrawnAbt}) does not match sealedTotal + voucherTotal (${sealedTotal + voucherTotal})`);
2090
- if (node.cumulativeWithdrawnAbt + pendingTotal > node.cumulativeDepositedAbt) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot violates Canary net-inflow reserve watermark: cumulativeWithdrawnAbt + pendingTotal (${node.cumulativeWithdrawnAbt + pendingTotal}) > cumulativeDepositedAbt (${node.cumulativeDepositedAbt})`);
2091
- return node;
2092
- }
2093
- };
2094
- /**
2095
- * Computes the deterministic EVM-side Two-Phase Challenge Hash (`seq: 500`):
2096
- * When a large withdrawal (`amount >= largeWithdrawThreshold`) is submitted to the Ethereum contract
2097
- * in Phase 1, the contract does NOT release funds. Instead, it records the pending withdrawal state
2098
- * and computes a fresh `challengeHash` incorporating Ethereum on-chain state (`phase1BlockNumber`):
2099
- * `keccak256(abi.encode(TWO_PHASE_CHALLENGE_TYPEHASH, chainId, verifyingContract, ocapTxHash, recipient, amount, phase1BlockNumber))`
2100
- * Because `phase1BlockNumber` is determined on Ethereum when Phase 1 is mined, an attacker with stolen
2101
- * Phase-1 hot keys (`Key_Hot`) cannot pre-forge Phase 2 offline and must expose Phase 1 on Ethereum first,
2102
- * after which `challengeHash` must be verified against the OCAP burn ledger and signed by a separate
2103
- * Sentinel/Cold key (`Key_Sentinel`).
2104
- */
2105
- const TWO_PHASE_CHALLENGE_TYPEHASH = utf8Keccak256Hex("EvmTwoPhaseWithdrawChallenge(uint256 chainId,address verifyingContract,bytes32 ocapTxHash,address recipient,uint256 amount,uint256 phase1BlockNumber)");
2106
- function computeEvmTwoPhaseChallengeHash(params) {
2107
- const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
2108
- const verifyingContractAddress = assertEvmAddress(params.verifyingContractAddress, "verifyingContractAddress");
2109
- const ocapTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
2110
- const recipientEvmAddress = assertEvmAddress(params.recipientEvmAddress, "recipientEvmAddress");
2111
- if (typeof params.amount !== "bigint" || params.amount <= 0n) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: challenge amount must be > 0n");
2112
- if (!Number.isSafeInteger(params.phase1BlockNumber) || params.phase1BlockNumber <= 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: phase1BlockNumber must be a positive safe integer");
2113
- const chainIdHex64 = CANONICAL_UINT256_DECIMAL_REGEX.test(evmChainId) ? uint256ToHex64(BigInt(evmChainId)) : utf8Keccak256Hex(evmChainId).slice(2);
2114
- const contractWordHex64 = verifyingContractAddress.slice(2).padStart(64, "0");
2115
- const recipientWordHex64 = recipientEvmAddress.slice(2).padStart(64, "0");
2116
- const amountHex64 = uint256ToHex64(params.amount);
2117
- const blockHex64 = uint256ToHex64(params.phase1BlockNumber);
2118
- return keccak256(`0x${TWO_PHASE_CHALLENGE_TYPEHASH.slice(2)}${chainIdHex64}${contractWordHex64}${ocapTxHash.slice(2)}${recipientWordHex64}${amountHex64}${blockHex64}`).toLowerCase();
2119
- }
2120
- /**
2121
- * Issue #1245 & #1243 (`seq: 500`):
2122
- * Deterministic Local EVM + OCAP End-to-End Testnet Harness (`OcapLocalEvmBridgeTestnetHarness`).
2123
- * - Executes raw EIP-1193 ABI `calldataHex` produced by `OcapSimplifiedEvmBridgeNode.buildWebPortalActionBundle`
2124
- * against an in-memory EVM state machine implementing `ArcEvmBridgeGateway.sol` + `MultiSigVault.sol` + `IERC20Minimal`.
2125
- * - Uses authentic `secp256k1` ECDSA `(v, r, s)` signing and `ecrecover(digest, v, r, s)` public-key recovery.
2126
- * - Supports `MultiSigVault` Cold Reserve + Hot `allowance` Isolation (`ERC20Rollup.sol:162-170` & `MultiSigVault.sol:447-473`)
2127
- * and EVM-Anchored Two-Phase Challenge-Response (`challengeHash` + independent `Key_Sentinel` co-signature).
2128
- */
2129
- var OcapLocalEvmBridgeTestnetHarness = class {
2130
- constructor(params) {
2131
- this.blockNumber = 1e3;
2132
- this.blockTimestampSeconds = 1782e6;
2133
- this.txSequence = 0;
2134
- this.erc20Balances = /* @__PURE__ */ new Map();
2135
- this.erc20Allowances = /* @__PURE__ */ new Map();
2136
- this.validatorEvmSet = /* @__PURE__ */ new Set();
2137
- this.processedServiceOrders = /* @__PURE__ */ new Set();
2138
- this.claimedWithdrawTxs = /* @__PURE__ */ new Set();
2139
- this.cancelledWithdrawTxs = /* @__PURE__ */ new Set();
2140
- this.timelockUnlockAt = /* @__PURE__ */ new Map();
2141
- this.pendingTwoPhaseChallenges = /* @__PURE__ */ new Map();
2142
- this.dailyWithdrawnAbt = /* @__PURE__ */ new Map();
2143
- this.multiSigColdVaultAddress = null;
2144
- this.coldVaultSignerEvmAddress = null;
2145
- this.sentinelSignerDid = null;
2146
- this.sentinelSignerEvmAddress = null;
2147
- this.evmPaused = false;
2148
- this.evmCumulativeDepositedAbt = 0n;
2149
- this.evmCumulativeWithdrawnAbt = 0n;
2150
- this.ocapNativeAbtBalances = /* @__PURE__ */ new Map();
2151
- this.ocapBurnedWithdrawTxs = /* @__PURE__ */ new Map();
2152
- this.ocapDeliveredServiceAssets = /* @__PURE__ */ new Map();
2153
- this.evmChainId = params.evmChainId ?? "84532";
2154
- this.gatewayContractAddress = assertEvmAddress(params.gatewayContractAddress ?? params.bridgeNode.config.verifyingContractAddress, "gatewayContractAddress");
2155
- this.canonicalAbtTokenAddress = assertEvmAddress(params.canonicalAbtTokenAddress, "canonicalAbtTokenAddress");
2156
- this.bridgeNode = params.bridgeNode;
2157
- const specs = params.validatorPrivateKeys.map((v) => {
2158
- const evmSignerAddress = deriveEvmAddressFromPrivateKeyHex(v.privateKeyHex);
2159
- this.validatorEvmSet.add(evmSignerAddress);
2160
- return {
2161
- validatorDid: assertCleanString(v.validatorDid, "validatorDid"),
2162
- privateKeyHex: v.privateKeyHex,
2163
- evmSignerAddress
2164
- };
2165
- });
2166
- this.validators = Object.freeze(specs);
2167
- }
2168
- getBlockTimestampSeconds() {
2169
- return this.blockTimestampSeconds;
2170
- }
2171
- advanceTimeSeconds(deltaSeconds) {
2172
- if (!Number.isSafeInteger(deltaSeconds) || deltaSeconds < 0) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: deltaSeconds must be a non-negative integer");
2173
- this.blockTimestampSeconds += deltaSeconds;
2174
- this.blockNumber += Math.max(1, Math.floor(deltaSeconds / 12));
2175
- return this.blockTimestampSeconds;
2176
- }
2177
- mintTestErc20(tokenAddress, toEvmAddress, amount) {
2178
- const token = assertEvmAddress(tokenAddress, "tokenAddress");
2179
- const to = assertEvmAddress(toEvmAddress, "toEvmAddress");
2180
- if (amount <= 0n) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: mint amount must be > 0n");
2181
- let tokenMap = this.erc20Balances.get(token);
2182
- if (!tokenMap) {
2183
- tokenMap = /* @__PURE__ */ new Map();
2184
- this.erc20Balances.set(token, tokenMap);
2185
- }
2186
- tokenMap.set(to, (tokenMap.get(to) ?? 0n) + amount);
2187
- }
2188
- getErc20Balance(tokenAddress, ownerEvmAddress) {
2189
- const token = assertEvmAddress(tokenAddress, "tokenAddress");
2190
- const owner = assertEvmAddress(ownerEvmAddress, "ownerEvmAddress");
2191
- return this.erc20Balances.get(token)?.get(owner) ?? 0n;
2192
- }
2193
- getOcapNativeAbtBalance(did) {
2194
- return this.ocapNativeAbtBalances.get(assertCleanString(did, "did")) ?? 0n;
2195
- }
2196
- getOcapDeliveredAssets(did) {
2197
- return [...this.ocapDeliveredServiceAssets.get(assertCleanString(did, "did")) ?? []];
2198
- }
2199
- /**
2200
- * Executes a user-signed OCAP `withdraw_token_v2` burn on the OCAP ledger and collects M-of-N
2201
- * real `secp256k1` EIP-712 signatures (`v, r, s`) from the bridge validators.
2202
- */
2203
- initiateOcapWithdrawAndIssueEip712Voucher(params) {
2204
- const fromDid = assertCleanString(params.fromDid, "fromDid");
2205
- const recipientEvmAddress = assertEvmAddress(params.recipientEvmAddress, "recipientEvmAddress");
2206
- const currentBal = this.getOcapNativeAbtBalance(fromDid);
2207
- if (params.amount <= 0n || currentBal < params.amount) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: insufficient OCAP Native ABT balance (${currentBal} < ${params.amount})`);
2208
- this.ocapNativeAbtBalances.set(fromDid, currentBal - params.amount);
2209
- this.txSequence += 1;
2210
- const ocapTxHash = utf8Keccak256Hex(`ocap:withdraw:${this.txSequence}:${fromDid}:${recipientEvmAddress}:${params.amount}`);
2211
- this.ocapBurnedWithdrawTxs.set(ocapTxHash, {
2212
- fromDid,
2213
- recipientEvmAddress,
2214
- amount: params.amount
2215
- });
2216
- const issuedAtUnixSeconds = this.blockTimestampSeconds;
2217
- const expiresAtUnixSeconds = issuedAtUnixSeconds + (params.ttlSeconds ?? 172800);
2218
- const voucherDigest = computeDirectWithdrawVoucherDigest({
2219
- bridgeId: this.bridgeNode.config.bridgeId,
2220
- evmChainId: this.evmChainId,
2221
- verifyingContractAddress: this.gatewayContractAddress,
2222
- ocapTxHash,
2223
- recipientEvmAddress,
2224
- amount: params.amount,
2225
- expiresAtUnixSeconds
2226
- });
2227
- const validatorSignatures = this.validators.slice(0, this.bridgeNode.config.minValidatorSignatures).map((val) => {
2228
- const ecdsa = signDigestWithSecp256k1PrivateKey(voucherDigest, val.privateKeyHex);
2229
- return {
2230
- validatorDid: val.validatorDid,
2231
- signatureDigest: computeValidatorVoucherSignatureDigest(this.bridgeNode.config.bridgeId, voucherDigest, val.validatorDid),
2232
- evmSignerAddress: ecdsa.signerEvmAddress,
2233
- v: ecdsa.v,
2234
- r: ecdsa.r,
2235
- s: ecdsa.s
2236
- };
2237
- });
2238
- return this.bridgeNode.issueDirectWithdrawVoucher({
2239
- evmChainId: this.evmChainId,
2240
- ocapTxHash,
2241
- fromDid,
2242
- recipientEvmAddress,
2243
- amount: params.amount,
2244
- issuedAtUnixSeconds,
2245
- expiresAtUnixSeconds,
2246
- validatorSignatures
2247
- });
2248
- }
2249
- /**
2250
- * Executes a raw EIP-1193 transaction step (`to`, `calldataHex`) on the Local EVM Testnet,
2251
- * decoding the raw ABI hex calldata and enforcing all `ArcEvmBridgeGateway.sol` invariants.
2252
- */
2253
- executeEip1193Step(senderEvmAddress, step) {
2254
- const sender = assertEvmAddress(senderEvmAddress, "senderEvmAddress");
2255
- const to = assertEvmAddress(step.to, "step.to");
2256
- if (typeof step.calldataHex !== "string" || !/^0x[0-9a-fA-F]{8,}$/.test(step.calldataHex)) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid step.calldataHex");
2257
- const selector = step.calldataHex.slice(0, 10).toLowerCase();
2258
- const dataHex = step.calldataHex.slice(10).toLowerCase();
2259
- this.txSequence += 1;
2260
- this.blockNumber += 1;
2261
- const evmTxHash = utf8Keccak256Hex(`evm:tx:${this.blockNumber}:${this.txSequence}:${sender}:${to}:${selector}`);
2262
- if (selector === computeSolidityFunctionSelector("approve(address,uint256)")) {
2263
- const spender = assertEvmAddress(`0x${dataHex.slice(24, 64)}`, "spender");
2264
- const amount = BigInt(`0x${dataHex.slice(64, 128)}`);
2265
- let allowMap = this.erc20Allowances.get(to);
2266
- if (!allowMap) {
2267
- allowMap = /* @__PURE__ */ new Map();
2268
- this.erc20Allowances.set(to, allowMap);
2269
- }
2270
- allowMap.set(`${sender}:${spender}`, amount);
2271
- return {
2272
- evmTxHash,
2273
- blockNumber: this.blockNumber,
2274
- blockTimestampSeconds: this.blockTimestampSeconds,
2275
- from: sender,
2276
- to,
2277
- functionSelector: selector,
2278
- eventEmitted: "ERC20Approval",
2279
- details: {
2280
- tokenAddress: to,
2281
- owner: sender,
2282
- spender,
2283
- amount: amount.toString()
2284
- }
2285
- };
2286
- }
2287
- if (to !== this.gatewayContractAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: unknown target contract ${to}`);
2288
- if (this.evmPaused || this.bridgeNode.getReserveWatermarkState().paused) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: BRIDGE_PAUSED");
2289
- if (selector === computeSolidityFunctionSelector("depositForNativeAbt(string,uint256)")) {
2290
- const strByteOffset = Number(BigInt(`0x${dataHex.slice(0, 64)}`));
2291
- const amount = BigInt(`0x${dataHex.slice(64, 128)}`);
2292
- const recipientDid = decodeAbiDynamicUtf8String(dataHex, strByteOffset);
2293
- const depositVaultTarget = this.multiSigColdVaultAddress ?? this.gatewayContractAddress;
2294
- this.transferFromErc20(this.canonicalAbtTokenAddress, sender, depositVaultTarget, amount);
2295
- this.evmCumulativeDepositedAbt += amount;
2296
- const instruction = this.bridgeNode.ingestEvmAbtDepositEvent({
2297
- evmChainId: this.evmChainId,
2298
- evmTxHash,
2299
- logIndex: 0,
2300
- confirmations: this.bridgeNode.config.minConfirmations,
2301
- depositorEvmAddress: sender,
2302
- recipientDid,
2303
- tokenAddress: this.canonicalAbtTokenAddress,
2304
- amount,
2305
- actualFee: 0n
2306
- });
2307
- this.ocapNativeAbtBalances.set(recipientDid, (this.ocapNativeAbtBalances.get(recipientDid) ?? 0n) + instruction.value);
2308
- return {
2309
- evmTxHash,
2310
- blockNumber: this.blockNumber,
2311
- blockTimestampSeconds: this.blockTimestampSeconds,
2312
- from: sender,
2313
- to,
2314
- functionSelector: selector,
2315
- eventEmitted: "NativeAbtDepositLocked",
2316
- details: {
2317
- depositor: sender,
2318
- recipientDid,
2319
- amount: amount.toString(),
2320
- mintedOnOcap: instruction.value.toString(),
2321
- custodiedInVault: depositVaultTarget,
2322
- zeroBridgeFee: instruction.actualFee === 0n
2323
- }
2324
- };
2325
- }
2326
- if (selector === computeSolidityFunctionSelector("payForOcapService(bytes32,string,string,address,uint256)")) {
2327
- const orderId = `0x${dataHex.slice(0, 64)}`;
2328
- const offset1 = Number(BigInt(`0x${dataHex.slice(64, 128)}`));
2329
- const offset2 = Number(BigInt(`0x${dataHex.slice(128, 192)}`));
2330
- const paymentToken = assertEvmAddress(`0x${dataHex.slice(216, 256)}`, "paymentToken");
2331
- const amount = BigInt(`0x${dataHex.slice(256, 320)}`);
2332
- const recipientDid = decodeAbiDynamicUtf8String(dataHex, offset1);
2333
- const serviceDid = decodeAbiDynamicUtf8String(dataHex, offset2);
2334
- if (this.processedServiceOrders.has(orderId)) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: INVALID_OR_DUPLICATE_ORDER");
2335
- this.processedServiceOrders.add(orderId);
2336
- this.transferFromErc20(paymentToken, sender, this.gatewayContractAddress, amount);
2337
- const delivery = this.bridgeNode.ingestEvmServicePaymentEvent({
2338
- evmChainId: this.evmChainId,
2339
- evmTxHash,
2340
- logIndex: 0,
2341
- confirmations: this.bridgeNode.config.minConfirmations,
2342
- orderId,
2343
- payerEvmAddress: sender,
2344
- recipientDid,
2345
- serviceDid,
2346
- paymentTokenAddress: paymentToken,
2347
- amount
2348
- });
2349
- const existingAssets = this.ocapDeliveredServiceAssets.get(recipientDid) ?? [];
2350
- existingAssets.push(...delivery.crossChainPurchaseInput.purchaseStatements[0].itx.assets);
2351
- this.ocapDeliveredServiceAssets.set(recipientDid, existingAssets);
2352
- return {
2353
- evmTxHash,
2354
- blockNumber: this.blockNumber,
2355
- blockTimestampSeconds: this.blockTimestampSeconds,
2356
- from: sender,
2357
- to,
2358
- functionSelector: selector,
2359
- eventEmitted: "OcapServicePaid",
2360
- details: {
2361
- orderId,
2362
- payer: sender,
2363
- recipientDid,
2364
- serviceDid,
2365
- paymentToken,
2366
- amount: amount.toString(),
2367
- deliveredNftDid: delivery.crossChainPurchaseInput.purchaseStatements[0].itx.assets[0]
2368
- }
2369
- };
2370
- }
2371
- if (selector === computeSolidityFunctionSelector("claimWithdrawWithDirectVoucher(bytes32,address,uint256,uint256,bytes32,uint8[],bytes32[],bytes32[])")) {
2372
- const ocapTxHash = `0x${dataHex.slice(0, 64)}`;
2373
- const recipient = assertEvmAddress(`0x${dataHex.slice(88, 128)}`, "recipient");
2374
- const amount = BigInt(`0x${dataHex.slice(128, 192)}`);
2375
- const expiresAt = Number(BigInt(`0x${dataHex.slice(192, 256)}`));
2376
- const voucherDigest = `0x${dataHex.slice(256, 320)}`;
2377
- const vOffset = Number(BigInt(`0x${dataHex.slice(320, 384)}`)) * 2;
2378
- const rOffset = Number(BigInt(`0x${dataHex.slice(384, 448)}`)) * 2;
2379
- const sOffset = Number(BigInt(`0x${dataHex.slice(448, 512)}`)) * 2;
2380
- const vLen = Number(BigInt(`0x${dataHex.slice(vOffset, vOffset + 64)}`));
2381
- const rLen = Number(BigInt(`0x${dataHex.slice(rOffset, rOffset + 64)}`));
2382
- const sLen = Number(BigInt(`0x${dataHex.slice(sOffset, sOffset + 64)}`));
2383
- if (vLen < this.bridgeNode.config.minValidatorSignatures || vLen !== rLen || vLen !== sLen) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: QUORUM_NOT_MET");
2384
- if (this.claimedWithdrawTxs.has(ocapTxHash) || this.cancelledWithdrawTxs.has(ocapTxHash)) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: ALREADY_CLAIMED_OR_CANCELLED");
2385
- if (this.blockTimestampSeconds > expiresAt) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: VOUCHER_EXPIRED");
2386
- if (this.evmCumulativeWithdrawnAbt + amount > this.evmCumulativeDepositedAbt) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: CANARY_RESERVE_WATERMARK_EXCEEDED");
2387
- if (voucherDigest !== computeDirectWithdrawVoucherDigest({
2388
- bridgeId: this.bridgeNode.config.bridgeId,
2389
- evmChainId: this.evmChainId,
2390
- verifyingContractAddress: this.gatewayContractAddress,
2391
- ocapTxHash,
2392
- recipientEvmAddress: recipient,
2393
- amount,
2394
- expiresAtUnixSeconds: expiresAt
2395
- })) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: INVALID_EIP712_VOUCHER_DIGEST");
2396
- let lastSignerBig = 0n;
2397
- for (let i = 0; i < vLen; i++) {
2398
- const recovered = ecrecoverEvmAddress(voucherDigest, Number(BigInt(`0x${dataHex.slice(vOffset + 64 + i * 64, vOffset + 128 + i * 64)}`)), `0x${dataHex.slice(rOffset + 64 + i * 64, rOffset + 128 + i * 64)}`, `0x${dataHex.slice(sOffset + 64 + i * 64, sOffset + 128 + i * 64)}`);
2399
- const signerBig = BigInt(recovered);
2400
- if (signerBig <= lastSignerBig || !this.validatorEvmSet.has(recovered)) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: INVALID_OR_UNSORTED_SIGNER");
2401
- lastSignerBig = signerBig;
2402
- }
2403
- if (amount >= this.bridgeNode.config.largeWithdrawTimelockThresholdAbt) {
2404
- const unlockAt = this.timelockUnlockAt.get(ocapTxHash) ?? 0;
2405
- if (unlockAt === 0) {
2406
- const newUnlockAt = this.blockTimestampSeconds + this.bridgeNode.config.timelockDelaySeconds;
2407
- const challengeHash = computeEvmTwoPhaseChallengeHash({
2408
- evmChainId: this.evmChainId,
2409
- verifyingContractAddress: this.gatewayContractAddress,
2410
- ocapTxHash,
2411
- recipientEvmAddress: recipient,
2412
- amount,
2413
- phase1BlockNumber: this.blockNumber
2414
- });
2415
- this.timelockUnlockAt.set(ocapTxHash, newUnlockAt);
2416
- this.pendingTwoPhaseChallenges.set(ocapTxHash, {
2417
- ocapTxHash,
2418
- recipientEvmAddress: recipient,
2419
- amount,
2420
- phase1BlockNumber: this.blockNumber,
2421
- unlockAtUnixSeconds: newUnlockAt,
2422
- challengeHash,
2423
- sentinelCoSigned: false
2424
- });
2425
- return {
2426
- evmTxHash,
2427
- blockNumber: this.blockNumber,
2428
- blockTimestampSeconds: this.blockTimestampSeconds,
2429
- from: sender,
2430
- to,
2431
- functionSelector: selector,
2432
- eventEmitted: "LargeWithdrawTimelocked",
2433
- details: {
2434
- ocapTxHash,
2435
- recipient,
2436
- amount: amount.toString(),
2437
- unlockAt: newUnlockAt,
2438
- phase1BlockNumber: this.blockNumber,
2439
- challengeHash
2440
- }
2441
- };
2442
- }
2443
- const pendingChallenge = this.pendingTwoPhaseChallenges.get(ocapTxHash);
2444
- if (!pendingChallenge || pendingChallenge.recipientEvmAddress.toLowerCase() !== recipient.toLowerCase() || pendingChallenge.amount !== amount) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: PHASE1_CHALLENGE_PARAMETER_MISMATCH");
2445
- if (this.sentinelSignerEvmAddress !== null && !pendingChallenge.sentinelCoSigned) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: TWO_PHASE_SENTINEL_COSIGN_REQUIRED");
2446
- if (this.blockTimestampSeconds < unlockAt && !pendingChallenge.sentinelCoSigned) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: TIMELOCK_ACTIVE");
2447
- }
2448
- return this.settleEvmWithdrawTransfer({
2449
- evmTxHash,
2450
- sender,
2451
- to,
2452
- selector,
2453
- ocapTxHash,
2454
- recipient,
2455
- amount
2456
- });
2457
- }
2458
- throw new CustomError(ErrorCode.InvalidBridge, `ArcEvmBridgeGateway: unsupported selector ${selector}`);
2459
- }
2460
- /**
2461
- * Configures the `MultiSigVault.sol` Cold Reserve + Hot `allowance` Isolation & Independent
2462
- * Sentinel Second-Factor Key Domain (`seq: 500`, matching `ArcBlock/contracts/src/ERC20Rollup.sol:162-170`
2463
- * and `MultiSigVault.sol:447-473`):
2464
- * - The Bridge Gateway contract (`gatewayContractAddress`) holds 0 ERC-20 ABT directly.
2465
- * - All reserves sit in `vaultAddress` (`MultiSigVault`), which grants `gatewayContractAddress` a bounded
2466
- * ERC-20 `allowance(vaultAddress, gatewayContractAddress)` (`initialHotAllowanceAbt`).
2467
- * - Enforces strict cryptographic key-domain separation: neither `coldVaultPrivateKeyHex` nor
2468
- * `sentinelPrivateKeyHex` may overlap with any Phase-1 hot bridge validator key (`validatorEvmSet`).
2469
- */
2470
- configureMultiSigColdVault(params) {
2471
- const vaultAddress = assertEvmAddress(params.vaultAddress, "vaultAddress");
2472
- if (vaultAddress === this.gatewayContractAddress) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: MultiSigVault address must be isolated from gatewayContractAddress");
2473
- const coldVaultSignerEvmAddress = deriveEvmAddressFromPrivateKeyHex(params.coldVaultPrivateKeyHex);
2474
- const sentinelDid = assertCleanString(params.sentinelDid, "sentinelDid");
2475
- const sentinelEvmAddress = deriveEvmAddressFromPrivateKeyHex(params.sentinelPrivateKeyHex);
2476
- if (this.validatorEvmSet.has(coldVaultSignerEvmAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: coldVaultPrivateKeyHex must be strictly disjoint from Phase-1 hot validator keys");
2477
- if (this.validatorEvmSet.has(sentinelEvmAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: sentinelPrivateKeyHex must be strictly disjoint from Phase-1 hot validator keys");
2478
- if (coldVaultSignerEvmAddress === sentinelEvmAddress) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: coldVaultPrivateKeyHex and sentinelPrivateKeyHex must be distinct keys");
2479
- if (vaultAddress === this.canonicalAbtTokenAddress) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: MultiSigVault address must be distinct from canonicalAbtTokenAddress");
2480
- if (this.multiSigColdVaultAddress !== null) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: MultiSigColdVault is already configured");
2481
- if (params.initialColdReserveAbt < 0n || params.initialHotAllowanceAbt < 0n) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: vault amounts must be non-negative");
2482
- if (params.initialHotAllowanceAbt > params.initialColdReserveAbt) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: initialHotAllowanceAbt cannot exceed initialColdReserveAbt");
2483
- this.multiSigColdVaultAddress = vaultAddress;
2484
- this.coldVaultSignerEvmAddress = coldVaultSignerEvmAddress;
2485
- this.sentinelSignerDid = sentinelDid;
2486
- this.sentinelSignerEvmAddress = sentinelEvmAddress;
2487
- if (params.initialColdReserveAbt > 0n) {
2488
- this.mintTestErc20(this.canonicalAbtTokenAddress, vaultAddress, params.initialColdReserveAbt);
2489
- this.evmCumulativeDepositedAbt += params.initialColdReserveAbt;
2490
- this.bridgeNode.ingestEvmAbtDepositEvent({
2491
- evmChainId: this.evmChainId,
2492
- evmTxHash: utf8Keccak256Hex(`evm:cold-vault-init:${vaultAddress}:${params.initialColdReserveAbt}`),
2493
- logIndex: 0,
2494
- confirmations: this.bridgeNode.config.minConfirmations,
2495
- depositorEvmAddress: vaultAddress,
2496
- recipientDid: this.bridgeNode.config.bridgeProposerDid,
2497
- tokenAddress: this.canonicalAbtTokenAddress,
2498
- amount: params.initialColdReserveAbt,
2499
- actualFee: 0n
2500
- });
2501
- this.ocapNativeAbtBalances.set(this.bridgeNode.config.bridgeProposerDid, (this.ocapNativeAbtBalances.get(this.bridgeNode.config.bridgeProposerDid) ?? 0n) + params.initialColdReserveAbt);
2502
- }
2503
- let allowMap = this.erc20Allowances.get(this.canonicalAbtTokenAddress);
2504
- if (!allowMap) {
2505
- allowMap = /* @__PURE__ */ new Map();
2506
- this.erc20Allowances.set(this.canonicalAbtTokenAddress, allowMap);
2507
- }
2508
- allowMap.set(`${vaultAddress}:${this.gatewayContractAddress}`, params.initialHotAllowanceAbt);
2509
- return {
2510
- vaultAddress,
2511
- coldVaultSignerEvmAddress,
2512
- sentinelDid,
2513
- sentinelEvmAddress,
2514
- coldReserveAbt: this.getErc20Balance(this.canonicalAbtTokenAddress, vaultAddress),
2515
- hotAllowanceAbt: params.initialHotAllowanceAbt
2516
- };
2517
- }
2518
- getMultiSigVaultState() {
2519
- const vaultAddress = this.multiSigColdVaultAddress;
2520
- return {
2521
- vaultAddress,
2522
- coldReserveAbt: vaultAddress ? this.getErc20Balance(this.canonicalAbtTokenAddress, vaultAddress) : 0n,
2523
- hotAllowanceAbt: vaultAddress ? this.erc20Allowances.get(this.canonicalAbtTokenAddress)?.get(`${vaultAddress}:${this.gatewayContractAddress}`) ?? 0n : 0n,
2524
- gatewayDirectBalanceAbt: this.getErc20Balance(this.canonicalAbtTokenAddress, this.gatewayContractAddress),
2525
- sentinelEvmAddress: this.sentinelSignerEvmAddress
2526
- };
2527
- }
2528
- /**
2529
- * Mirrors `MultiSigVault.approveERC20(token, spender, ApproveAction, amount, signatures)`:
2530
- * Only the independent Cold Vault signer (`coldVaultPrivateKeyHex`) can increase or decrease
2531
- * the ERC-20 `allowance(vaultAddress, gatewayContractAddress)` hot exposure cap.
2532
- */
2533
- approveColdVaultHotAllowance(params) {
2534
- if (!this.multiSigColdVaultAddress || !this.coldVaultSignerEvmAddress) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: MultiSigColdVault is not configured");
2535
- if (params.action !== "INCREASE" && params.action !== "DECREASE") throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: action must be INCREASE or DECREASE");
2536
- if (typeof params.amount !== "bigint" || params.amount <= 0n) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: allowance change amount must be > 0n");
2537
- const opHash = utf8Keccak256Hex(`multisig-vault:approve:${this.canonicalAbtTokenAddress}:${this.gatewayContractAddress}:${params.action}:${params.amount}`);
2538
- const sig = signDigestWithSecp256k1PrivateKey(opHash, params.coldVaultPrivateKeyHex);
2539
- const recovered = ecrecoverEvmAddress(opHash, sig.v, sig.r, sig.s);
2540
- if (recovered !== this.coldVaultSignerEvmAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `MultiSigVault: unauthorized cold vault signer (${recovered} !== ${this.coldVaultSignerEvmAddress})`);
2541
- const allowKey = `${this.multiSigColdVaultAddress}:${this.gatewayContractAddress}`;
2542
- const allowMap = this.erc20Allowances.get(this.canonicalAbtTokenAddress);
2543
- const currentAllow = allowMap.get(allowKey) ?? 0n;
2544
- const coldReserve = this.getErc20Balance(this.canonicalAbtTokenAddress, this.multiSigColdVaultAddress);
2545
- const nextAllow = params.action === "INCREASE" ? currentAllow + params.amount : currentAllow > params.amount ? currentAllow - params.amount : 0n;
2546
- if (params.action === "INCREASE" && nextAllow > coldReserve) throw new CustomError(ErrorCode.ForbiddenBridge, `MultiSigVault: hot allowance (${nextAllow}) cannot exceed cold vault reserve (${coldReserve})`);
2547
- allowMap.set(allowKey, nextAllow);
2548
- return {
2549
- vaultAddress: this.multiSigColdVaultAddress,
2550
- newHotAllowanceAbt: nextAllow
2551
- };
2552
- }
2553
- getPendingTwoPhaseChallenge(ocapTxHash) {
2554
- const cleanHash = assertBytes32Hex(ocapTxHash, "ocapTxHash");
2555
- const rec = this.pendingTwoPhaseChallenges.get(cleanHash);
2556
- return rec ? { ...rec } : void 0;
2557
- }
2558
- /**
2559
- * Intermediate Cross-Chain Handshake (`seq: 500`):
2560
- * Takes the `challengeHash` emitted on Ethereum during Phase 1 back to the OCAP / Sentinel control plane:
2561
- * 1. Verifies that `ocapTxHash` exists in `pendingTwoPhaseChallenges` on Ethereum and its `challengeHash` matches.
2562
- * 2. Verifies against the OCAP ledger (`ocapBurnedWithdrawTxs`) that `ocapTxHash` genuinely burned the exact
2563
- * `amount` for `recipientEvmAddress`. If an attacker forged Phase 1 with stolen `Key_Hot` without a matching
2564
- * OCAP burn, Sentinel immediately cancels the withdrawal on EVM, pauses the bridge, and aborts!
2565
- * 3. Uses the independent Second-Factor key (`sentinelPrivateKeyHex`, disjoint from `Key_Hot`) to sign `challengeHash`,
2566
- * and optionally replenishes the `MultiSigVault` hot `allowance` if `coldVaultPrivateKeyHex` is provided.
2567
- */
2568
- coSignEvmWithdrawalChallenge(params) {
2569
- if (this.evmPaused || this.bridgeNode.getReserveWatermarkState().paused) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: bridge is paused");
2570
- if (!this.sentinelSignerEvmAddress || !this.sentinelSignerDid) throw new CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: Sentinel second-factor key not configured");
2571
- const cleanTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
2572
- if (this.claimedWithdrawTxs.has(cleanTxHash) || this.cancelledWithdrawTxs.has(cleanTxHash)) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: withdrawal already claimed or cancelled");
2573
- const cleanChallengeHash = assertBytes32Hex(params.challengeHash, "challengeHash");
2574
- const derivedSentinelAddr = deriveEvmAddressFromPrivateKeyHex(params.sentinelPrivateKeyHex);
2575
- if (derivedSentinelAddr !== this.sentinelSignerEvmAddress || this.validatorEvmSet.has(derivedSentinelAddr)) throw new CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: unauthorized or non-isolated Sentinel second-factor key");
2576
- const pending = this.pendingTwoPhaseChallenges.get(cleanTxHash);
2577
- if (!pending) throw new CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: no Phase-1 pending withdrawal challenge on EVM for ${cleanTxHash}`);
2578
- if (pending.challengeHash !== cleanChallengeHash) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: challengeHash mismatch (${cleanChallengeHash} !== ${pending.challengeHash})`);
2579
- const ocapBurn = this.ocapBurnedWithdrawTxs.get(cleanTxHash);
2580
- if (!ocapBurn || ocapBurn.recipientEvmAddress.toLowerCase() !== pending.recipientEvmAddress.toLowerCase() || ocapBurn.amount !== pending.amount) {
2581
- this.cancelledWithdrawTxs.add(cleanTxHash);
2582
- this.evmPaused = true;
2583
- this.bridgeNode.setBridgePaused({
2584
- guardianDid: this.bridgeNode.config.guardianDid,
2585
- paused: true
2586
- });
2587
- throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: Sentinel detected forged Phase-1 withdrawal ${cleanTxHash} without matching OCAP burn; withdrawal cancelled and bridge paused`);
2588
- }
2589
- let replenishedHotAllowanceAbt = 0n;
2590
- if (this.multiSigColdVaultAddress) {
2591
- const vaultState = this.getMultiSigVaultState();
2592
- if (vaultState.hotAllowanceAbt < pending.amount) {
2593
- const deficit = pending.amount - vaultState.hotAllowanceAbt;
2594
- if (!params.coldVaultPrivateKeyHexForAllowanceTopUp) throw new CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdrawal amount (${pending.amount}) exceeds current MultiSigVault hot allowance (${vaultState.hotAllowanceAbt}); coldVaultPrivateKeyHexForAllowanceTopUp required`);
2595
- this.approveColdVaultHotAllowance({
2596
- action: "INCREASE",
2597
- amount: deficit,
2598
- coldVaultPrivateKeyHex: params.coldVaultPrivateKeyHexForAllowanceTopUp
2599
- });
2600
- replenishedHotAllowanceAbt = deficit;
2601
- }
2602
- }
2603
- const sig = signDigestWithSecp256k1PrivateKey(cleanChallengeHash, params.sentinelPrivateKeyHex);
2604
- pending.sentinelCoSigned = true;
2605
- return {
2606
- ocapTxHash: cleanTxHash,
2607
- challengeHash: cleanChallengeHash,
2608
- sentinelDid: this.sentinelSignerDid,
2609
- sentinelEvmAddress: derivedSentinelAddr,
2610
- v: sig.v,
2611
- r: sig.r,
2612
- s: sig.s,
2613
- replenishedHotAllowanceAbt
2614
- };
2615
- }
2616
- /**
2617
- * Phase 2 on Ethereum (`seq: 500`):
2618
- * Submits the independent second-factor signature (`sig_Phase2` over `challengeHash`) to the Ethereum
2619
- * gateway contract. The contract verifies:
2620
- * 1. The withdrawal completed Phase 1 on Ethereum (`pendingTwoPhaseChallenges.get(ocapTxHash)`) and its
2621
- * on-chain `challengeHash` matches.
2622
- * 2. `ecrecover(challengeHash, v, r, s)` recovers the authorized independent `sentinelSignerEvmAddress`.
2623
- * 3. Transfers `amount` from `MultiSigVault` (`safeTransferFrom(token, vaultAddress, recipient, amount)`)
2624
- * within the approved `allowance(vaultAddress, gatewayContractAddress)`.
2625
- */
2626
- finalizeChallengedWithdrawOnEvm(params) {
2627
- const sender = assertEvmAddress(params.senderEvmAddress, "senderEvmAddress");
2628
- const cleanTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
2629
- const cleanChallengeHash = assertBytes32Hex(params.challengeHash, "challengeHash");
2630
- if (this.evmPaused || this.bridgeNode.getReserveWatermarkState().paused) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: BRIDGE_PAUSED");
2631
- if (!this.sentinelSignerEvmAddress) throw new CustomError(ErrorCode.InvalidBridge, "ArcEvmBridgeGateway: SENTINEL_SIGNER_NOT_CONFIGURED");
2632
- if (this.claimedWithdrawTxs.has(cleanTxHash) || this.cancelledWithdrawTxs.has(cleanTxHash)) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: ALREADY_CLAIMED_OR_CANCELLED");
2633
- const pending = this.pendingTwoPhaseChallenges.get(cleanTxHash);
2634
- if (!pending) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: PHASE1_CHALLENGE_NOT_FOUND");
2635
- const expectedChallengeHash = computeEvmTwoPhaseChallengeHash({
2636
- evmChainId: this.evmChainId,
2637
- verifyingContractAddress: this.gatewayContractAddress,
2638
- ocapTxHash: cleanTxHash,
2639
- recipientEvmAddress: pending.recipientEvmAddress,
2640
- amount: pending.amount,
2641
- phase1BlockNumber: pending.phase1BlockNumber
2642
- });
2643
- if (cleanChallengeHash !== pending.challengeHash || cleanChallengeHash !== expectedChallengeHash) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: INVALID_PHASE2_CHALLENGE_HASH");
2644
- const recoveredSentinel = ecrecoverEvmAddress(cleanChallengeHash, params.v, params.r, params.s);
2645
- if (recoveredSentinel !== this.sentinelSignerEvmAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `ArcEvmBridgeGateway: INVALID_PHASE2_SENTINEL_SIGNATURE (${recoveredSentinel} !== ${this.sentinelSignerEvmAddress})`);
2646
- this.txSequence += 1;
2647
- this.blockNumber += 1;
2648
- const selector = computeSolidityFunctionSelector("finalizeChallengedWithdraw(bytes32,bytes32,uint8,bytes32,bytes32)");
2649
- const evmTxHash = utf8Keccak256Hex(`evm:tx:${this.blockNumber}:${this.txSequence}:${sender}:${this.gatewayContractAddress}:${selector}`);
2650
- const receipt = this.settleEvmWithdrawTransfer({
2651
- evmTxHash,
2652
- sender,
2653
- to: this.gatewayContractAddress,
2654
- selector,
2655
- ocapTxHash: cleanTxHash,
2656
- recipient: pending.recipientEvmAddress,
2657
- amount: pending.amount,
2658
- challengeHash: cleanChallengeHash,
2659
- sentinelSigner: recoveredSentinel
2660
- });
2661
- pending.sentinelCoSigned = true;
2662
- return receipt;
2663
- }
2664
- settleEvmWithdrawTransfer(params) {
2665
- const { evmTxHash, sender, to, selector, ocapTxHash, recipient, amount } = params;
2666
- const currentDay = Math.floor(this.blockTimestampSeconds / 86400);
2667
- const dayTotal = this.dailyWithdrawnAbt.get(currentDay) ?? 0n;
2668
- if (dayTotal + amount > this.bridgeNode.config.maxDailyWithdrawAbt) throw new CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: DAILY_WITHDRAW_CAP_EXCEEDED");
2669
- if (this.multiSigColdVaultAddress) {
2670
- if (this.getErc20Balance(this.canonicalAbtTokenAddress, this.multiSigColdVaultAddress) < amount) throw new CustomError(ErrorCode.ForbiddenBridge, "ERC20Rollup: E243_INSUFFICIENT_VAULT_BALANCE");
2671
- const allowKey = `${this.multiSigColdVaultAddress}:${this.gatewayContractAddress}`;
2672
- const currentAllow = this.erc20Allowances.get(this.canonicalAbtTokenAddress)?.get(allowKey) ?? 0n;
2673
- if (currentAllow < amount) throw new CustomError(ErrorCode.ForbiddenBridge, `ERC20Rollup: E220_HOT_VAULT_ALLOWANCE_EXCEEDED (requested ${amount} > remaining hot allowance ${currentAllow})`);
2674
- this.transferFromErc20(this.canonicalAbtTokenAddress, this.multiSigColdVaultAddress, recipient, amount);
2675
- } else this.transferDirectErc20(this.canonicalAbtTokenAddress, this.gatewayContractAddress, recipient, amount);
2676
- this.dailyWithdrawnAbt.set(currentDay, dayTotal + amount);
2677
- this.claimedWithdrawTxs.add(ocapTxHash);
2678
- this.evmCumulativeWithdrawnAbt += amount;
2679
- return {
2680
- evmTxHash,
2681
- blockNumber: this.blockNumber,
2682
- blockTimestampSeconds: this.blockTimestampSeconds,
2683
- from: sender,
2684
- to,
2685
- functionSelector: selector,
2686
- eventEmitted: "NativeAbtWithdrawClaimed",
2687
- details: {
2688
- ocapTxHash,
2689
- recipient,
2690
- amount: amount.toString(),
2691
- zeroBridgeFee: true,
2692
- ...params.challengeHash ? { challengeHash: params.challengeHash } : {},
2693
- ...params.sentinelSigner ? { sentinelSigner: params.sentinelSigner } : {}
2694
- }
2695
- };
2696
- }
2697
- /**
2698
- * Crowdsourced User-Wallet Watchtower Witness (`seq: 463`):
2699
- * Any user wallet or Blocklet can inspect pending timelocked withdrawals on the EVM gateway contract
2700
- * against the authentic OCAP chain burn ledger (`ocapBurnedWithdrawTxs`).
2701
- * If a timelocked withdrawal on EVM does not exist on OCAP (or has a mismatched amount/recipient),
2702
- * the Watchtower Witness flags the anomaly and triggers Guardian cancellation + pause.
2703
- */
2704
- verifyWatchtowerStateConsistency(witnessWalletDid) {
2705
- const cleanWitness = assertCleanString(witnessWalletDid, "witnessWalletDid");
2706
- const flaggedTxHashes = [];
2707
- for (const [ocapTxHash] of this.timelockUnlockAt.entries()) {
2708
- if (this.cancelledWithdrawTxs.has(ocapTxHash) || this.claimedWithdrawTxs.has(ocapTxHash)) continue;
2709
- const ocapBurn = this.ocapBurnedWithdrawTxs.get(ocapTxHash);
2710
- const pendingChallenge = this.pendingTwoPhaseChallenges.get(ocapTxHash);
2711
- if (!ocapBurn || pendingChallenge && (ocapBurn.recipientEvmAddress.toLowerCase() !== pendingChallenge.recipientEvmAddress.toLowerCase() || ocapBurn.amount !== pendingChallenge.amount)) flaggedTxHashes.push(ocapTxHash);
2712
- }
2713
- if (flaggedTxHashes.length > 0) {
2714
- for (const txHash of flaggedTxHashes) {
2715
- this.cancelledWithdrawTxs.add(txHash);
2716
- try {
2717
- this.bridgeNode.cancelTimelockedWithdraw({
2718
- guardianDid: this.bridgeNode.config.guardianDid,
2719
- ocapTxHash: txHash,
2720
- nowUnixSeconds: this.blockTimestampSeconds
2721
- });
2722
- } catch {}
2723
- }
2724
- this.evmPaused = true;
2725
- this.bridgeNode.setBridgePaused({
2726
- guardianDid: this.bridgeNode.config.guardianDid,
2727
- paused: true
2728
- });
2729
- return {
2730
- consistent: false,
2731
- witnessWalletDid: cleanWitness,
2732
- flaggedTxHashes,
2733
- autoCancelledAndPaused: true
2734
- };
2735
- }
2736
- return {
2737
- consistent: true,
2738
- witnessWalletDid: cleanWitness,
2739
- flaggedTxHashes: [],
2740
- autoCancelledAndPaused: false
2741
- };
2742
- }
2743
- transferFromErc20(tokenAddress, from, to, amount) {
2744
- const allowKey = `${from}:${this.gatewayContractAddress}`;
2745
- const allowMap = this.erc20Allowances.get(tokenAddress);
2746
- const currentAllow = allowMap?.get(allowKey) ?? 0n;
2747
- if (currentAllow < amount) throw new CustomError(ErrorCode.ForbiddenBridge, "ERC20: insufficient allowance");
2748
- allowMap.set(allowKey, currentAllow - amount);
2749
- this.transferDirectErc20(tokenAddress, from, to, amount);
2750
- }
2751
- transferDirectErc20(tokenAddress, from, to, amount) {
2752
- const tokenMap = this.erc20Balances.get(tokenAddress);
2753
- const fromBal = tokenMap?.get(from) ?? 0n;
2754
- if (fromBal < amount) throw new CustomError(ErrorCode.ForbiddenBridge, "ERC20: transfer amount exceeds balance");
2755
- tokenMap.set(from, fromBal - amount);
2756
- tokenMap.set(to, (tokenMap.get(to) ?? 0n) + amount);
2757
- }
2758
- };
2759
- const MULTISIG_OP_TYPEHASH = utf8Keccak256Hex("MultiSigOperation(address targetContract,bytes4 selector,uint256 nonce,bytes32 paramsHash)");
2760
- const BRIDGE_CHARTER_KIND = "BridgeGovernanceCharter";
2761
- const MULTISIG_SELECTOR_HEX_MAP = {
2762
- SEND_ETHER: computeSolidityFunctionSelector("sendEther(address,uint256,bytes)"),
2763
- SEND_ERC20: computeSolidityFunctionSelector("sendERC20(address,address,uint256,bytes)"),
2764
- APPROVE_ERC20: computeSolidityFunctionSelector("approveERC20(address,address,uint8,uint256,bytes)"),
2765
- ADD_SIGNER: computeSolidityFunctionSelector("addSigner(address,bytes)"),
2766
- REMOVE_SIGNER: computeSolidityFunctionSelector("removeSigner(address,bytes)"),
2767
- SET_THRESHOLD: computeSolidityFunctionSelector("setThreshold(uint8,bytes)"),
2768
- REPLACE_SEED_SIGNER: computeSolidityFunctionSelector("replaceSeedSigner(address,address,bytes)"),
2769
- MIGRATE_VAULT: computeSolidityFunctionSelector("migrateVault(address,bytes)")
2770
- };
2771
- /**
2772
- * Hardened `SignerManagerV2` + `MultiSigVaultV2` EIP-712 Digest (`seq: 504`):
2773
- * Fixes the 4 Critical/High vulnerabilities identified in legacy `SignerManager.sol` & `MultiSigVault.sol`:
2774
- * 1. CRITICAL-1 (Cross-Contract / Cross-Method Replay & Front-Run Nonce Burn):
2775
- * Binds `targetContract` (`msg.sender`, e.g., `vaultAddress` vs `signerManagerAddress`), `selector` (`bytes4`),
2776
- * and a contract-wide sequential `nonce` into the EIP-712 struct hash. Calling `ensureSignatures` directly
2777
- * from an EOA or unauthorized contract produces a different `targetContract` (`msg.sender`) and fails recovery.
2778
- * 2. CRITICAL-2 (Permanent Vault Lockout on Single Lost Seed Signer):
2779
- * Supports `seedThreshold` (M-of-K seed quorum) and `REPLACE_SEED_SIGNER` recovery rotation.
2780
- * 3. HIGH-1 (Opaque Raw-Hash Signing & `abi.encodePacked` Collision):
2781
- * Uses EIP-712 Typed Structured Data with fixed-width 32-byte `abi.encode` words for wallet Clear-Signing.
2782
- * 4. HIGH-2 (Per-Signer Nonce Desynchronization Under Partial Subset Signing):
2783
- * Uses a single Safe-style sequential `nonce` per target contract and strictly ascending signer address order (`O(N)`).
2784
- */
2785
- function computeHardenedMultiSigOpDigest(params) {
2786
- const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
2787
- const signerManagerAddress = assertEvmAddress(params.signerManagerAddress, "signerManagerAddress");
2788
- const targetContractAddress = assertEvmAddress(params.targetContractAddress, "targetContractAddress");
2789
- const selectorHex = MULTISIG_SELECTOR_HEX_MAP[params.operation];
2790
- if (!selectorHex) throw new CustomError(ErrorCode.InvalidBridge, `MultiSigVaultV2: unsupported operation ${params.operation}`);
2791
- if (!Number.isSafeInteger(params.nonce) || params.nonce < 0) throw new CustomError(ErrorCode.InvalidBridge, "MultiSigVaultV2: nonce must be a non-negative safe integer");
2792
- const paramsHash = assertBytes32Hex(params.paramsHash, "paramsHash");
2793
- const nameHash = utf8Keccak256Hex("ArcMultiSigSignerManagerV2").slice(2);
2794
- const versionHash = utf8Keccak256Hex("2").slice(2);
2795
- const chainIdHex64 = CANONICAL_UINT256_DECIMAL_REGEX.test(evmChainId) ? uint256ToHex64(BigInt(evmChainId)) : utf8Keccak256Hex(evmChainId).slice(2);
2796
- const signerManagerWord64 = signerManagerAddress.slice(2).padStart(64, "0");
2797
- const domainSeparator = keccak256(`0x${EIP712_DOMAIN_TYPEHASH.slice(2)}${nameHash}${versionHash}${chainIdHex64}${signerManagerWord64}`).toLowerCase();
2798
- const selectorWord = selectorHex.slice(2).toLowerCase().padEnd(64, "0");
2799
- const targetWord64 = targetContractAddress.slice(2).padStart(64, "0");
2800
- const structHash = keccak256(`0x${MULTISIG_OP_TYPEHASH.slice(2)}${targetWord64}${selectorWord}${uint256ToHex64(params.nonce)}${paramsHash.slice(2)}`).toLowerCase();
2801
- return {
2802
- domainSeparator,
2803
- structHash,
2804
- digest: keccak256(`0x1901${domainSeparator.slice(2)}${structHash.slice(2)}`).toLowerCase(),
2805
- selectorHex
2806
- };
2807
- }
2808
- var HardenedMultiSigSignerManagerV2 = class {
2809
- constructor(params) {
2810
- this.signers = /* @__PURE__ */ new Set();
2811
- this.seedSigners = /* @__PURE__ */ new Set();
2812
- this.noncesByTarget = /* @__PURE__ */ new Map();
2813
- this.vetoedProposalHashes = /* @__PURE__ */ new Set();
2814
- this.evmChainId = assertCleanString(params.evmChainId, "evmChainId");
2815
- this.signerManagerAddress = assertEvmAddress(params.signerManagerAddress, "signerManagerAddress");
2816
- if (!Array.isArray(params.signers) || params.signers.length === 0 || params.signers.length > 32) throw new CustomError(ErrorCode.InvalidBridge, "SignerManagerV2: signers must contain 1..32 addresses");
2817
- for (const s of params.signers) {
2818
- const addr = assertEvmAddress(s, "signerAddress");
2819
- if (this.signers.has(addr)) throw new CustomError(ErrorCode.InvalidBridge, `SignerManagerV2: duplicate signer ${addr}`);
2820
- this.signers.add(addr);
2821
- }
2822
- if (!Array.isArray(params.seedSigners) || params.seedSigners.length === 0) throw new CustomError(ErrorCode.InvalidBridge, "SignerManagerV2: seedSigners must be non-empty");
2823
- for (const s of params.seedSigners) {
2824
- const addr = assertEvmAddress(s, "seedSignerAddress");
2825
- if (!this.signers.has(addr)) throw new CustomError(ErrorCode.InvalidBridge, `SignerManagerV2: seedSigner ${addr} must also be in signers`);
2826
- this.seedSigners.add(addr);
2827
- }
2828
- if (!Number.isSafeInteger(params.threshold) || params.threshold < 1 || params.threshold > this.signers.size) throw new CustomError(ErrorCode.InvalidBridge, "SignerManagerV2: invalid threshold (1..signers.length)");
2829
- const seedThreshold = params.seedThreshold ?? Math.min(params.threshold, this.seedSigners.size);
2830
- if (!Number.isSafeInteger(seedThreshold) || seedThreshold < 1 || seedThreshold > this.seedSigners.size) throw new CustomError(ErrorCode.InvalidBridge, "SignerManagerV2: invalid seedThreshold (1..seedSigners.length)");
2831
- this.threshold = params.threshold;
2832
- this.seedThreshold = seedThreshold;
2833
- }
2834
- getTargetNonce(targetContractAddress) {
2835
- const cleanTarget = assertEvmAddress(targetContractAddress, "targetContractAddress");
2836
- return this.noncesByTarget.get(cleanTarget) ?? 0;
2837
- }
2838
- getState() {
2839
- return {
2840
- evmChainId: this.evmChainId,
2841
- signerManagerAddress: this.signerManagerAddress,
2842
- signers: Array.from(this.signers),
2843
- seedSigners: Array.from(this.seedSigners),
2844
- threshold: this.threshold,
2845
- seedThreshold: this.seedThreshold
2846
- };
2847
- }
2848
- /**
2849
- * Verifies EIP-712 signatures bound to `(evmChainId, signerManagerAddress, callerTargetContract, operation, nonce, paramsHash)`
2850
- * in O(N) time with strictly ascending signer order (`currentSigner > lastSigner`) and `seedThreshold` check,
2851
- * then atomically increments the target contract's sequential nonce.
2852
- */
2853
- ensureSignaturesForTarget(params) {
2854
- const callerTarget = assertEvmAddress(params.callerTargetContract, "callerTargetContract");
2855
- if (!Array.isArray(params.signatures) || params.signatures.length < this.threshold) throw new CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E113_INSUFFICIENT_SIGNATURES");
2856
- const currentNonce = this.getTargetNonce(callerTarget);
2857
- const { digest } = computeHardenedMultiSigOpDigest({
2858
- evmChainId: this.evmChainId,
2859
- signerManagerAddress: this.signerManagerAddress,
2860
- targetContractAddress: callerTarget,
2861
- operation: params.operation,
2862
- nonce: currentNonce,
2863
- paramsHash: params.paramsHash
2864
- });
2865
- let lastSignerBig = 0n;
2866
- let seedSignedCount = 0;
2867
- const verifiedSigners = [];
2868
- for (const sig of params.signatures) {
2869
- const recovered = ecrecoverEvmAddress(digest, sig.v, sig.r, sig.s);
2870
- if (recovered !== assertEvmAddress(sig.signerEvmAddress, "sig.signerEvmAddress")) throw new CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E117_SIGNATURE_RECOVERY_MISMATCH");
2871
- if (!this.signers.has(recovered)) throw new CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E115_UNAUTHORIZED_SIGNER");
2872
- const signerBig = BigInt(recovered);
2873
- if (signerBig <= lastSignerBig) throw new CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E116_DUPLICATE_OR_UNSORTED_SIGNER");
2874
- lastSignerBig = signerBig;
2875
- if (this.seedSigners.has(recovered)) seedSignedCount += 1;
2876
- verifiedSigners.push(recovered);
2877
- }
2878
- if (seedSignedCount < this.seedThreshold) throw new CustomError(ErrorCode.ForbiddenBridge, `SignerManagerV2: E114_SEED_QUORUM_NOT_MET (${seedSignedCount} < ${this.seedThreshold})`);
2879
- this.noncesByTarget.set(callerTarget, currentNonce + 1);
2880
- return {
2881
- consumedNonce: currentNonce,
2882
- digest,
2883
- verifiedSigners
2884
- };
2885
- }
2886
- /**
2887
- * Recoverable Seed Signer Rotation (`CRITICAL-2` fix):
2888
- * Replaces a lost or rotated `oldSeedSigner` with `newSeedSigner` when authorized by a valid quorum
2889
- * meeting `threshold` and `seedThreshold` (so losing 1 seed key in a 2-of-3 seed quorum never bricks the vault).
2890
- */
2891
- replaceSeedSigner(params) {
2892
- const oldSeed = assertEvmAddress(params.oldSeedSigner, "oldSeedSigner");
2893
- const newSeed = assertEvmAddress(params.newSeedSigner, "newSeedSigner");
2894
- if (!this.seedSigners.has(oldSeed)) throw new CustomError(ErrorCode.InvalidBridge, `SignerManagerV2: ${oldSeed} is not an existing seed signer`);
2895
- if (this.seedSigners.has(newSeed)) throw new CustomError(ErrorCode.InvalidBridge, `SignerManagerV2: ${newSeed} is already a seed signer`);
2896
- if (this.signers.has(newSeed)) throw new CustomError(ErrorCode.InvalidBridge, `SignerManagerV2: ${newSeed} is already an active signer; replaceSeedSigner requires a distinct replacement address`);
2897
- const paramsHash = keccak256(`0x${oldSeed.slice(2).padStart(64, "0")}${newSeed.slice(2).padStart(64, "0")}`).toLowerCase();
2898
- const { consumedNonce } = this.ensureSignaturesForTarget({
2899
- callerTargetContract: this.signerManagerAddress,
2900
- operation: "REPLACE_SEED_SIGNER",
2901
- paramsHash,
2902
- signatures: params.signatures
2903
- });
2904
- this.seedSigners.delete(oldSeed);
2905
- this.signers.delete(oldSeed);
2906
- this.signers.add(newSeed);
2907
- this.seedSigners.add(newSeed);
2908
- if (this.signers.size < this.threshold || this.seedSigners.size < this.seedThreshold) throw new CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: post-rotation quorum invariant violated");
2909
- return {
2910
- oldSeedSigner: oldSeed,
2911
- newSeedSigner: newSeed,
2912
- consumedNonce
2913
- };
2914
- }
2915
- isProposalVetoed(vledgerProposalHash) {
2916
- const cleanHash = assertBytes32Hex(vledgerProposalHash, "vledgerProposalHash");
2917
- return this.vetoedProposalHashes.has(cleanHash);
2918
- }
2919
- /**
2920
- * Cross-Chain Seed Signer Veto Attestation (`RT-1262-8` & `RT-1262-9`):
2921
- * Verifies an EIP-712 `MultiSigVetoAttestation` signed by an active Seed Signer and permanently blocks
2922
- * `vledgerProposalHash` on the foreign chain `SignerManagerV2` contract, preventing a rogue signer from
2923
- * scraping pre-veto voter signatures off VLedger and submitting them directly to the EVM contract.
2924
- */
2925
- recordVetoAttestation(params) {
2926
- const vledgerProposalHash = assertBytes32Hex(params.vledgerProposalHash, "vledgerProposalHash");
2927
- const targetContractAddress = assertEvmAddress(params.targetContractAddress, "targetContractAddress");
2928
- const seedEvmAddress = assertEvmAddress(params.seedEvmAddress, "seedEvmAddress");
2929
- if (!this.seedSigners.has(seedEvmAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, `SignerManagerV2: ${seedEvmAddress} is not an authorized seed signer for veto attestation`);
2930
- if (this.vetoedProposalHashes.has(vledgerProposalHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `SignerManagerV2: proposal ${vledgerProposalHash} is already vetoed`);
2931
- const currentNonce = this.getTargetNonce(targetContractAddress);
2932
- if (!Number.isSafeInteger(params.nonce) || params.nonce < currentNonce) throw new CustomError(ErrorCode.ForbiddenBridge, `SignerManagerV2: cannot record veto attestation for stale nonce (${params.nonce} < ${currentNonce})`);
2933
- const { digest } = computeMultiSigVetoAttestationDigest({
2934
- evmChainId: this.evmChainId,
2935
- signerManagerAddress: this.signerManagerAddress,
2936
- vledgerProposalHash,
2937
- targetContractAddress,
2938
- nonce: params.nonce,
2939
- seedEvmAddress
2940
- });
2941
- const recovered = ecrecoverEvmAddress(digest, params.v, params.r, params.s);
2942
- if (recovered !== seedEvmAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `SignerManagerV2: veto attestation signature recovery mismatch (${recovered} !== ${seedEvmAddress})`);
2943
- this.vetoedProposalHashes.add(vledgerProposalHash);
2944
- return {
2945
- vledgerProposalHash,
2946
- seedEvmAddress,
2947
- digest
2948
- };
2949
- }
2950
- /**
2951
- * Stateless Foreign-Chain Certificate Verification & Nonce Consumption (`RT-1262-8`, `RT-1262-11..15`):
2952
- * Models the on-chain EVM `SignerManagerV2` contract verification without relying on VLedger's in-memory map.
2953
- * Enforces:
2954
- * - Cryptographic veto check (`!this.vetoedProposalHashes.has(cert.vledgerProposalHash)`)
2955
- * - EIP-712 bound cooldown & TTL window (`executableAfterUnixSeconds <= nowUnixSeconds <= expiresAtUnixSeconds`)
2956
- * - Full `vledgerProposalHash`, `certificateHash`, and optional `clearSigningPreview` (`paramsHash`) integrity
2957
- * - Active proposer check + Seed Executor & Proposer-Executor Separation (`executor !== proposer`) for critical ops
2958
- * - Holder Hardware Final Release signature + M-of-N EIP-712 voter signatures with `seedThreshold`
2959
- */
2960
- verifyAndConsumePublishedCertificate(params) {
2961
- if (!params || typeof params !== "object" || !params.certificate || typeof params.certificate !== "object") throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: certificate object is required");
2962
- if (!params.holderReleaseSignature || typeof params.holderReleaseSignature !== "object") throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: holderReleaseSignature object is required");
2963
- if (!Number.isSafeInteger(params.nowUnixSeconds) || params.nowUnixSeconds <= 0) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: nowUnixSeconds must be a positive integer");
2964
- const cert = params.certificate;
2965
- if (cert.kind !== "OcapPublishedMultiSigCert" || cert.schemaVersion !== 1) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: invalid certificate kind or version");
2966
- if (cert.evmChainId !== this.evmChainId || assertEvmAddress(cert.signerManagerAddress, "cert.signerManagerAddress") !== this.signerManagerAddress) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: certificate chainId or signerManagerAddress domain mismatch");
2967
- const vledgerProposalHash = assertBytes32Hex(cert.vledgerProposalHash, "cert.vledgerProposalHash");
2968
- if (this.vetoedProposalHashes.has(vledgerProposalHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal ${vledgerProposalHash} was vetoed by a seed signer`);
2969
- const minCooldown = params.minCooldownSeconds ?? HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS;
2970
- const cooldownSeconds = cert.executableAfterUnixSeconds - cert.proposedAtUnixSeconds;
2971
- const ttlSeconds = cert.expiresAtUnixSeconds - cert.executableAfterUnixSeconds;
2972
- if (cooldownSeconds < minCooldown) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: cooldownSeconds (${cooldownSeconds}) is below minimum (${minCooldown})`);
2973
- if (params.nowUnixSeconds < cert.executableAfterUnixSeconds) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: pre-execution cooldown active until ${cert.executableAfterUnixSeconds}`);
2974
- if (cert.issuedAtUnixSeconds < cert.executableAfterUnixSeconds) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate issued before cooldown expiry (${cert.executableAfterUnixSeconds})`);
2975
- if (params.nowUnixSeconds > cert.expiresAtUnixSeconds || cert.issuedAtUnixSeconds > cert.expiresAtUnixSeconds) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate expired at ${cert.expiresAtUnixSeconds} (zombie certificate rejected)`);
2976
- if (computeVLedgerMultiSigProposalHash({
2977
- proposalId: cert.proposalId,
2978
- ledgerMode: cert.ledgerMode,
2979
- proposerDid: cert.proposerDid,
2980
- proposerEvmAddress: cert.proposerEvmAddress,
2981
- title: cert.title,
2982
- rationale: cert.rationale,
2983
- category: cert.category,
2984
- evmChainId: cert.evmChainId,
2985
- signerManagerAddress: cert.signerManagerAddress,
2986
- targetContractAddress: cert.targetContractAddress,
2987
- operation: cert.operation,
2988
- nonce: cert.nonce,
2989
- paramsHash: cert.paramsHash,
2990
- proposedAtUnixSeconds: cert.proposedAtUnixSeconds,
2991
- cooldownSeconds,
2992
- ttlSeconds,
2993
- decodedParams: cert.clearSigningPreview?.decodedParams
2994
- }, { minCooldownSeconds: minCooldown }) !== vledgerProposalHash) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: vledgerProposalHash integrity or cross-proposal binding mismatch");
2995
- if (computePublishedMultiSigCertificateHash(cert) !== cert.certificateHash) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: certificateHash integrity mismatch");
2996
- if (cert.clearSigningPreview !== void 0) {
2997
- const expectedPreview = buildPublishedMultiSigClearSigningPreview({
2998
- targetContractAddress: cert.targetContractAddress,
2999
- nonce: cert.nonce,
3000
- decodedParams: cert.clearSigningPreview.decodedParams
3001
- });
3002
- if (JSON.stringify(expectedPreview) !== JSON.stringify(cert.clearSigningPreview)) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: clearSigningPreview structural integrity mismatch");
3003
- }
3004
- const proposerEvmAddress = assertEvmAddress(cert.proposerEvmAddress, "cert.proposerEvmAddress");
3005
- if (!this.signers.has(proposerEvmAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposer ${proposerEvmAddress} is no longer an active vault signer`);
3006
- const executorEvmAddress = assertEvmAddress(params.executorEvmAddress, "executorEvmAddress");
3007
- if (!this.signers.has(executorEvmAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: executor ${executorEvmAddress} is not an authorized vault signer`);
3008
- if (CRITICAL_SEED_EXECUTOR_OPERATIONS.has(cert.operation)) {
3009
- if (!this.seedSigners.has(executorEvmAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: critical operation ${cert.operation} requires a Seed Signer executor`);
3010
- if (this.signers.size > 1 && executorEvmAddress === proposerEvmAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: critical operation ${cert.operation} requires Proposer-Executor Separation (executor !== proposer)`);
3011
- }
3012
- const targetContractAddress = assertEvmAddress(cert.targetContractAddress, "cert.targetContractAddress");
3013
- const expectedNonce = this.getTargetNonce(targetContractAddress);
3014
- if (cert.nonce !== expectedNonce) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate nonce (${cert.nonce}) mismatch with current contract nonce (${expectedNonce})`);
3015
- const recoveredExecutor = ecrecoverEvmAddress(computeHolderFinalReleaseDigest({
3016
- evmChainId: this.evmChainId,
3017
- signerManagerAddress: this.signerManagerAddress,
3018
- certificateHash: cert.certificateHash,
3019
- vledgerProposalHash,
3020
- targetContractAddress,
3021
- nonce: cert.nonce,
3022
- executableAfterUnixSeconds: cert.executableAfterUnixSeconds,
3023
- expiresAtUnixSeconds: cert.expiresAtUnixSeconds,
3024
- executorEvmAddress
3025
- }), params.holderReleaseSignature.v, params.holderReleaseSignature.r, params.holderReleaseSignature.s);
3026
- if (recoveredExecutor !== executorEvmAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: invalid holder hardware release signature (${recoveredExecutor} !== ${executorEvmAddress})`);
3027
- const { digest: expectedVoteDigest } = computePublishedMultiSigVoteDigest({
3028
- evmChainId: this.evmChainId,
3029
- signerManagerAddress: this.signerManagerAddress,
3030
- vledgerProposalHash,
3031
- targetContractAddress,
3032
- operation: cert.operation,
3033
- nonce: cert.nonce,
3034
- paramsHash: cert.paramsHash,
3035
- executableAfterUnixSeconds: cert.executableAfterUnixSeconds,
3036
- expiresAtUnixSeconds: cert.expiresAtUnixSeconds
3037
- });
3038
- let lastSignerBig = 0n;
3039
- let seedSignedCount = 0;
3040
- const verifiedSigners = [];
3041
- for (const vote of cert.votes) {
3042
- if (vote.eip712Digest !== expectedVoteDigest) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: vote eip712Digest mismatch");
3043
- const recoveredVoter = ecrecoverEvmAddress(expectedVoteDigest, vote.v, vote.r, vote.s);
3044
- if (recoveredVoter !== assertEvmAddress(vote.voterEvmAddress, "vote.voterEvmAddress")) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: E117_VOTE_SIGNATURE_MISMATCH");
3045
- if (!this.signers.has(recoveredVoter)) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: E115_UNAUTHORIZED_VOTER");
3046
- const signerBig = BigInt(recoveredVoter);
3047
- if (signerBig <= lastSignerBig) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: E116_UNSORTED_OR_DUPLICATE_VOTER");
3048
- lastSignerBig = signerBig;
3049
- if (this.seedSigners.has(recoveredVoter)) seedSignedCount += 1;
3050
- verifiedSigners.push(recoveredVoter);
3051
- }
3052
- if (verifiedSigners.length < this.threshold || seedSignedCount < this.seedThreshold) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: E113_E114_QUORUM_NOT_MET");
3053
- const decoded = cert.clearSigningPreview?.decodedParams;
3054
- if (cert.operation === "ADD_SIGNER" || cert.operation === "REMOVE_SIGNER" || cert.operation === "REPLACE_SEED_SIGNER" || cert.operation === "SET_THRESHOLD") {
3055
- if (targetContractAddress !== this.signerManagerAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: ${cert.operation} must target signerManagerAddress (${this.signerManagerAddress})`);
3056
- if (!decoded) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: ${cert.operation} requires clearSigningPreview.decodedParams for SignerManagerV2 invariant verification`);
3057
- if (cert.operation === "ADD_SIGNER") {
3058
- const newSigner = assertEvmAddress(decoded.signerAddress, "decodedParams.signerAddress");
3059
- if (this.signers.has(newSigner) || this.signers.size >= 32) throw new CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E105_E106_INVALID_ADD_SIGNER");
3060
- this.signers.add(newSigner);
3061
- } else if (cert.operation === "REMOVE_SIGNER") {
3062
- const oldSigner = assertEvmAddress(decoded.signerAddress, "decodedParams.signerAddress");
3063
- if (this.seedSigners.has(oldSigner)) throw new CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E107_CANNOT_REMOVE_SEED_SIGNER");
3064
- if (!this.signers.has(oldSigner) || this.signers.size - 1 < this.threshold) throw new CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E104_E108_INVALID_REMOVE_SIGNER");
3065
- this.signers.delete(oldSigner);
3066
- } else if (cert.operation === "REPLACE_SEED_SIGNER") {
3067
- const oldSeed = assertEvmAddress(decoded.oldSeedSignerAddress, "decodedParams.oldSeedSignerAddress");
3068
- const newSeed = assertEvmAddress(decoded.newSeedSignerAddress, "decodedParams.newSeedSignerAddress");
3069
- if (!this.seedSigners.has(oldSeed) || this.seedSigners.has(newSeed) || this.signers.has(newSeed)) throw new CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: INVALID_REPLACE_SEED_SIGNER");
3070
- this.seedSigners.delete(oldSeed);
3071
- this.signers.delete(oldSeed);
3072
- this.signers.add(newSeed);
3073
- this.seedSigners.add(newSeed);
3074
- } else if (cert.operation === "SET_THRESHOLD") {
3075
- const newThreshold = decoded.newThreshold;
3076
- if (!Number.isSafeInteger(newThreshold) || newThreshold < 1 || newThreshold > this.signers.size) throw new CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E104_INVALID_THRESHOLD");
3077
- this.threshold = newThreshold;
3078
- }
3079
- }
3080
- this.noncesByTarget.set(targetContractAddress, expectedNonce + 1);
3081
- return {
3082
- consumedNonce: expectedNonce,
3083
- verifiedSigners,
3084
- certificateHash: cert.certificateHash,
3085
- vledgerProposalHash,
3086
- executorEvmAddress
3087
- };
3088
- }
3089
- };
3090
- function computeBridgeGovernanceCharterHash(state) {
3091
- const validatorSummary = state.validators.map((v) => `${v.did}:${v.evmSignerAddress.toLowerCase()}:${v.role}:${v.endpoint ?? ""}`).join("|");
3092
- const reserveSummary = Object.keys(state.reserves).sort().map((k) => `${k}:${state.reserves[k].totalDeposited}:${state.reserves[k].totalWithdrawn}`).join("|");
3093
- const limitsSummary = [
3094
- state.limits.minDepositAmount,
3095
- state.limits.maxDepositAmount,
3096
- state.limits.minWithdrawAmount,
3097
- state.limits.maxWithdrawAmount,
3098
- state.limits.maxDailyWithdrawAmount,
3099
- state.limits.largeWithdrawTimelockThreshold,
3100
- String(state.limits.timelockDelaySeconds)
3101
- ].join("|");
3102
- return utf8Keccak256Hex([
3103
- state.kind,
3104
- state.schemaVersion,
3105
- state.bridgeId,
3106
- state.rollupAddress,
3107
- state.ocapTokenAddress,
3108
- state.supportedTokens.join(","),
3109
- state.foreignChainType,
3110
- state.foreignChainId,
3111
- state.foreignChainName,
3112
- state.foreignTokenContractAddress.toLowerCase(),
3113
- state.verifyingContractAddress.toLowerCase(),
3114
- state.vaultAddress.toLowerCase(),
3115
- state.signerManagerAddress.toLowerCase(),
3116
- state.sentinelDid,
3117
- state.sentinelEvmAddress.toLowerCase(),
3118
- state.guardianDid,
3119
- state.migrateHistory.join(","),
3120
- state.vaultHistory.join(","),
3121
- validatorSummary,
3122
- state.minValidatorSignatures,
3123
- state.seedValidatorQuorum,
3124
- state.minConfirmations,
3125
- limitsSummary,
3126
- state.paused ? "1" : "0",
3127
- state.closed ? "1" : "0",
3128
- reserveSummary,
3129
- state.governanceVersion,
3130
- state.lastGovernanceAction.action,
3131
- state.lastGovernanceAction.ocapTxHash.toLowerCase(),
3132
- state.lastGovernanceAction.blockHeight
3133
- ].join("::"));
3134
- }
3135
- var OcapOnChainBridgeGovernanceRegistry = class {
3136
- constructor() {
3137
- this.chartersByBridgeId = /* @__PURE__ */ new Map();
3138
- }
3139
- publishBridgeCharter(params) {
3140
- const bridgeId = assertCleanString(params.bridgeId, "bridgeId");
3141
- if (this.chartersByBridgeId.has(bridgeId)) throw new CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: charter for ${bridgeId} already published`);
3142
- const verifyingContractAddress = assertEvmAddress(params.verifyingContractAddress, "verifyingContractAddress");
3143
- const vaultAddress = assertEvmAddress(params.vaultAddress, "vaultAddress");
3144
- const signerManagerAddress = assertEvmAddress(params.signerManagerAddress, "signerManagerAddress");
3145
- const foreignTokenContractAddress = assertEvmAddress(params.foreignTokenContractAddress, "foreignTokenContractAddress");
3146
- const sentinelEvmAddress = assertEvmAddress(params.sentinelEvmAddress, "sentinelEvmAddress");
3147
- if (new Set([
3148
- verifyingContractAddress,
3149
- vaultAddress,
3150
- signerManagerAddress,
3151
- foreignTokenContractAddress,
3152
- sentinelEvmAddress
3153
- ]).size !== 5) throw new CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: verifyingContractAddress, vaultAddress, signerManagerAddress, foreignTokenContractAddress, and sentinelEvmAddress must be pairwise distinct");
3154
- if (!Array.isArray(params.validators) || params.validators.length < 2 || params.validators.length > 16) throw new CustomError(ErrorCode.InvalidBridge, "BridgeGovernance: validators must contain 2..16 entries");
3155
- const normalizedValidators = [];
3156
- const seenDids = /* @__PURE__ */ new Set();
3157
- const seenEvmAddrs = /* @__PURE__ */ new Set();
3158
- let seedCount = 0;
3159
- for (const v of params.validators) {
3160
- const did = assertCleanString(v.did, "validator.did");
3161
- const evmAddr = assertEvmAddress(v.evmSignerAddress, "validator.evmSignerAddress");
3162
- if (seenDids.has(did) || seenEvmAddrs.has(evmAddr)) throw new CustomError(ErrorCode.InvalidBridge, `BridgeGovernance: duplicate validator ${did} / ${evmAddr}`);
3163
- if (evmAddr === sentinelEvmAddress) throw new CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: sentinelEvmAddress must be strictly disjoint from hot validator signers");
3164
- seenDids.add(did);
3165
- seenEvmAddrs.add(evmAddr);
3166
- if (v.role === "seed") seedCount += 1;
3167
- normalizedValidators.push({
3168
- did,
3169
- evmSignerAddress: evmAddr,
3170
- endpoint: v.endpoint,
3171
- role: v.role
3172
- });
3173
- }
3174
- if (seedCount === 0) throw new CustomError(ErrorCode.InvalidBridge, "BridgeGovernance: at least one seed validator is required");
3175
- if (params.minValidatorSignatures < 2 || params.minValidatorSignatures > normalizedValidators.length) throw new CustomError(ErrorCode.InvalidBridge, "BridgeGovernance: minValidatorSignatures must be 2..validators");
3176
- const seedValidatorQuorum = params.seedValidatorQuorum ?? Math.min(seedCount, params.minValidatorSignatures);
3177
- if (seedValidatorQuorum < 1 || seedValidatorQuorum > seedCount) throw new CustomError(ErrorCode.InvalidBridge, "BridgeGovernance: invalid seedValidatorQuorum");
3178
- const ocapTokenAddress = assertCleanString(params.ocapTokenAddress, "ocapTokenAddress");
3179
- const supportedTokens = Array.from(new Set([ocapTokenAddress, ...params.supportedTokens ?? []]));
3180
- const reserves = {};
3181
- for (const t of supportedTokens) reserves[t] = {
3182
- totalDeposited: "0",
3183
- totalWithdrawn: "0"
3184
- };
3185
- const baseState = {
3186
- kind: BRIDGE_CHARTER_KIND,
3187
- schemaVersion: 1,
3188
- bridgeId,
3189
- rollupAddress: assertCleanString(params.rollupAddress, "rollupAddress"),
3190
- ocapTokenAddress,
3191
- supportedTokens,
3192
- foreignChainType: params.foreignChainType ?? "EVM",
3193
- foreignChainId: assertCleanString(params.foreignChainId, "foreignChainId"),
3194
- foreignChainName: assertCleanString(params.foreignChainName, "foreignChainName"),
3195
- foreignTokenContractAddress,
3196
- verifyingContractAddress,
3197
- vaultAddress,
3198
- signerManagerAddress,
3199
- sentinelDid: assertCleanString(params.sentinelDid, "sentinelDid"),
3200
- sentinelEvmAddress,
3201
- guardianDid: assertCleanString(params.guardianDid, "guardianDid"),
3202
- migrateHistory: [],
3203
- vaultHistory: [],
3204
- validators: normalizedValidators,
3205
- minValidatorSignatures: params.minValidatorSignatures,
3206
- seedValidatorQuorum,
3207
- minConfirmations: params.minConfirmations ?? DEFAULT_MIN_EVM_CONFIRMATIONS,
3208
- limits: { ...params.limits },
3209
- zeroBridgeFee: true,
3210
- bridgeFeeBps: 0,
3211
- paused: false,
3212
- closed: false,
3213
- enforceReserveWatermark: true,
3214
- reserves,
3215
- governanceVersion: 1,
3216
- lastGovernanceAction: {
3217
- action: "PUBLISH",
3218
- ocapTxHash: assertBytes32Hex(params.ocapTxHash, "ocapTxHash"),
3219
- blockHeight: params.blockHeight
3220
- }
3221
- };
3222
- const fullState = {
3223
- ...baseState,
3224
- stateCommitmentHash: computeBridgeGovernanceCharterHash(baseState)
3225
- };
3226
- this.chartersByBridgeId.set(bridgeId, fullState);
3227
- return cloneDeepCharter(fullState);
3228
- }
3229
- getBridgeCharter(bridgeId) {
3230
- const charter = this.chartersByBridgeId.get(bridgeId);
3231
- if (!charter) throw new CustomError(ErrorCode.InvalidBridge, `BridgeGovernance: charter not found for ${bridgeId}`);
3232
- return cloneDeepCharter(charter);
3233
- }
3234
- /**
3235
- * Executes an on-chain M-of-N governed bridge state transition (`PAUSE`, `RESUME`, `MIGRATE_CONTRACT`,
3236
- * `MIGRATE_VAULT`, `CLOSE`), enforcing the exact production invariants from `core/state/src/states/rollup.ts:527-630`:
3237
- * - Requires `minValidatorSignatures` distinct validator DIDs and at least `seedValidatorQuorum` seed validators.
3238
- * - `MIGRATE_CONTRACT` and `MIGRATE_VAULT` require `paused === true && closed === false`, reject self-migration
3239
- * and cyclic reuse of any historical address in `migrateHistory` / `vaultHistory`, and append the old address
3240
- * to the public on-chain linear history.
3241
- */
3242
- applyGovernedTransition(params) {
3243
- const charter = this.chartersByBridgeId.get(params.bridgeId);
3244
- if (!charter) throw new CustomError(ErrorCode.InvalidBridge, `BridgeGovernance: charter not found for ${params.bridgeId}`);
3245
- if (charter.closed) throw new CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge is permanently closed");
3246
- this.verifyGovernanceSigners(charter, params.signerValidatorDids);
3247
- const nextBase = {
3248
- ...cloneDeepCharter(charter),
3249
- governanceVersion: charter.governanceVersion + 1,
3250
- lastGovernanceAction: {
3251
- action: params.action,
3252
- ocapTxHash: assertBytes32Hex(params.ocapTxHash, "ocapTxHash"),
3253
- blockHeight: params.blockHeight
3254
- }
3255
- };
3256
- if (params.action === "PAUSE") {
3257
- if (charter.paused) throw new CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge is already paused");
3258
- nextBase.paused = true;
3259
- } else if (params.action === "RESUME") {
3260
- if (!charter.paused) throw new CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge is not paused");
3261
- nextBase.paused = false;
3262
- } else if (params.action === "CLOSE") {
3263
- if (!charter.paused) throw new CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge must be paused before closing");
3264
- nextBase.closed = true;
3265
- } else if (params.action === "MIGRATE_CONTRACT") {
3266
- if (!charter.paused) throw new CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge must be paused before migrating verifyingContractAddress");
3267
- const nextContract = assertEvmAddress(params.newAddress ?? "", "newContractAddress");
3268
- if (nextContract === charter.verifyingContractAddress || charter.migrateHistory.includes(nextContract) || nextContract === charter.vaultAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: invalid or cyclic contract migration target ${nextContract}`);
3269
- nextBase.migrateHistory = [...charter.migrateHistory, charter.verifyingContractAddress];
3270
- nextBase.verifyingContractAddress = nextContract;
3271
- } else if (params.action === "MIGRATE_VAULT") {
3272
- if (!charter.paused) throw new CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge must be paused before migrating MultiSigVault address");
3273
- const nextVault = assertEvmAddress(params.newAddress ?? "", "newVaultAddress");
3274
- if (nextVault === charter.vaultAddress || charter.vaultHistory.includes(nextVault) || nextVault === charter.verifyingContractAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: invalid or cyclic vault migration target ${nextVault}`);
3275
- nextBase.vaultHistory = [...charter.vaultHistory, charter.vaultAddress];
3276
- nextBase.vaultAddress = nextVault;
3277
- }
3278
- const updated = {
3279
- ...nextBase,
3280
- stateCommitmentHash: computeBridgeGovernanceCharterHash(nextBase)
3281
- };
3282
- this.chartersByBridgeId.set(params.bridgeId, updated);
3283
- return cloneDeepCharter(updated);
3284
- }
3285
- verifyGovernanceSigners(charter, signerDids) {
3286
- if (!Array.isArray(signerDids) || signerDids.length < charter.minValidatorSignatures) throw new CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: insufficient validator signatures");
3287
- const byDid = new Map(charter.validators.map((v) => [v.did, v]));
3288
- const uniqueSigners = /* @__PURE__ */ new Set();
3289
- let seedSigned = 0;
3290
- for (const rawDid of signerDids) {
3291
- const did = assertCleanString(rawDid, "signerDid");
3292
- if (uniqueSigners.has(did)) throw new CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: duplicate governance signer ${did}`);
3293
- const spec = byDid.get(did);
3294
- if (!spec) throw new CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: unauthorized governance signer ${did}`);
3295
- uniqueSigners.add(did);
3296
- if (spec.role === "seed") seedSigned += 1;
3297
- }
3298
- if (seedSigned < charter.seedValidatorQuorum) throw new CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: seed validator quorum not met (${seedSigned} < ${charter.seedValidatorQuorum})`);
3299
- }
3300
- };
3301
- function cloneDeepCharter(c) {
3302
- return JSON.parse(JSON.stringify(c));
3303
- }
3304
- const PUBLISHED_MULTISIG_CERT_OP_TYPEHASH = utf8Keccak256Hex("PublishedMultiSigOperation(bytes32 vledgerProposalHash,address targetContract,bytes4 selector,uint256 nonce,bytes32 paramsHash,uint256 executableAfter,uint256 expiresAt)");
3305
- const HOLDER_RELEASE_INTENT_TYPEHASH = utf8Keccak256Hex("HolderReleaseIntent(bytes32 certificateHash,bytes32 vledgerProposalHash,address targetContract,uint256 nonce,uint256 executableAfter,uint256 expiresAt,address executor)");
3306
- const MULTISIG_VETO_ATTESTATION_TYPEHASH = utf8Keccak256Hex("MultiSigVetoAttestation(bytes32 vledgerProposalHash,address targetContract,uint256 nonce,address seedSigner)");
3307
- const HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS = 60;
3308
- const DEFAULT_MIN_MULTISIG_COOLDOWN_SECONDS = 3600;
3309
- const MIN_MULTISIG_CERT_TTL_SECONDS = 300;
3310
- const MAX_MULTISIG_CERT_TTL_SECONDS = 30 * 86400;
3311
- const DEFAULT_MULTISIG_CERT_TTL_SECONDS = 7 * 86400;
3312
- const MAX_PUBLISHED_MULTISIG_PROPOSALS = 1024;
3313
- const MAX_MULTISIG_VOTES_PER_CERT = 32;
3314
- const ALLOWED_LEDGER_MODES = new Set(["VLEDGER", "OCAP_MAIN_CHAIN"]);
3315
- const ALLOWED_PROPOSAL_CATEGORIES = new Set([
3316
- "TREASURY_TRANSFER",
3317
- "ALLOWANCE_UPDATE",
3318
- "SIGNER_ROTATION",
3319
- "BRIDGE_GOVERNANCE",
3320
- "VAULT_MIGRATION"
3321
- ]);
3322
- const EXPECTED_CATEGORY_BY_OPERATION = {
3323
- SEND_ETHER: "TREASURY_TRANSFER",
3324
- SEND_ERC20: "TREASURY_TRANSFER",
3325
- APPROVE_ERC20: "ALLOWANCE_UPDATE",
3326
- ADD_SIGNER: "SIGNER_ROTATION",
3327
- REMOVE_SIGNER: "SIGNER_ROTATION",
3328
- REPLACE_SEED_SIGNER: "SIGNER_ROTATION",
3329
- SET_THRESHOLD: "BRIDGE_GOVERNANCE",
3330
- MIGRATE_VAULT: "VAULT_MIGRATION"
3331
- };
3332
- const CRITICAL_SEED_EXECUTOR_OPERATIONS = new Set([
3333
- "MIGRATE_VAULT",
3334
- "REPLACE_SEED_SIGNER",
3335
- "ADD_SIGNER",
3336
- "REMOVE_SIGNER",
3337
- "SET_THRESHOLD"
3338
- ]);
3339
- function parsePositiveUint256(value, label) {
3340
- const parsed = parseStrictUint256JsonValue(value, label);
3341
- if (parsed <= 0n) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: ${label} must be > 0`);
3342
- return parsed;
3343
- }
3344
- /**
3345
- * Deterministic ABI-style parameter hash computation from structured `MultiSigDecodedParams` (`RT-1262-11`):
3346
- * Eliminates Bybit-style blind-signing by proving that human-readable Clear-Signing fields (`tokenAddress`,
3347
- * `recipientOrSpenderAddress`, `amountWei`, `newVaultAddress`, etc.) hash to the exact `paramsHash` in EIP-712.
3348
- */
3349
- function computeMultiSigOperationParamsHash(decoded) {
3350
- if (!decoded || typeof decoded !== "object") throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: decodedParams must be an object");
3351
- switch (decoded.operation) {
3352
- case "SEND_ETHER": {
3353
- const recipient = assertEvmAddress(decoded.recipientOrSpenderAddress ?? "", "decoded.recipientOrSpenderAddress");
3354
- const amount = parsePositiveUint256(decoded.amountWei ?? "", "decoded.amountWei");
3355
- return keccak256(`0x${recipient.slice(2).padStart(64, "0")}${uint256ToHex64(amount)}`).toLowerCase();
3356
- }
3357
- case "SEND_ERC20":
3358
- case "APPROVE_ERC20": {
3359
- const token = assertEvmAddress(decoded.tokenAddress ?? "", "decoded.tokenAddress");
3360
- const target = assertEvmAddress(decoded.recipientOrSpenderAddress ?? "", "decoded.recipientOrSpenderAddress");
3361
- const amount = parsePositiveUint256(decoded.amountWei ?? "", "decoded.amountWei");
3362
- return keccak256(`0x${token.slice(2).padStart(64, "0")}${target.slice(2).padStart(64, "0")}${uint256ToHex64(amount)}`).toLowerCase();
3363
- }
3364
- case "ADD_SIGNER":
3365
- case "REMOVE_SIGNER": return keccak256(`0x${assertEvmAddress(decoded.signerAddress ?? "", "decoded.signerAddress").slice(2).padStart(64, "0")}`).toLowerCase();
3366
- case "REPLACE_SEED_SIGNER": {
3367
- const oldSeed = assertEvmAddress(decoded.oldSeedSignerAddress ?? "", "decoded.oldSeedSignerAddress");
3368
- const newSeed = assertEvmAddress(decoded.newSeedSignerAddress ?? "", "decoded.newSeedSignerAddress");
3369
- return keccak256(`0x${oldSeed.slice(2).padStart(64, "0")}${newSeed.slice(2).padStart(64, "0")}`).toLowerCase();
3370
- }
3371
- case "SET_THRESHOLD":
3372
- if (!Number.isSafeInteger(decoded.newThreshold) || (decoded.newThreshold ?? 0) < 1) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: decoded.newThreshold must be a positive integer");
3373
- return keccak256(`0x${uint256ToHex64(decoded.newThreshold)}`).toLowerCase();
3374
- case "MIGRATE_VAULT": return keccak256(`0x${assertEvmAddress(decoded.newVaultAddress ?? "", "decoded.newVaultAddress").slice(2).padStart(64, "0")}`).toLowerCase();
3375
- default: throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: unsupported decodedParams operation ${String(decoded.operation)}`);
3376
- }
3377
- }
3378
- function buildPublishedMultiSigClearSigningPreview(params) {
3379
- const targetVault = assertEvmAddress(params.targetContractAddress, "targetContractAddress");
3380
- const d = params.decodedParams;
3381
- computeMultiSigOperationParamsHash(d);
3382
- let youAuthorize = "";
3383
- let exactOutflow = "0";
3384
- let maxTokenOutflowWei = "0";
3385
- let allowedRecipientOrSpender;
3386
- if (d.operation === "SEND_ETHER") {
3387
- allowedRecipientOrSpender = assertEvmAddress(d.recipientOrSpenderAddress, "recipientOrSpenderAddress");
3388
- maxTokenOutflowWei = String(parsePositiveUint256(d.amountWei, "amountWei"));
3389
- exactOutflow = `${maxTokenOutflowWei} wei NATIVE_ETH -> ${allowedRecipientOrSpender}`;
3390
- youAuthorize = `SEND_ETHER (${exactOutflow}) at nonce ${params.nonce}`;
3391
- } else if (d.operation === "SEND_ERC20") {
3392
- const token = assertEvmAddress(d.tokenAddress, "tokenAddress");
3393
- allowedRecipientOrSpender = assertEvmAddress(d.recipientOrSpenderAddress, "recipientOrSpenderAddress");
3394
- maxTokenOutflowWei = String(parsePositiveUint256(d.amountWei, "amountWei"));
3395
- exactOutflow = `${maxTokenOutflowWei} units of ${token} -> ${allowedRecipientOrSpender}`;
3396
- youAuthorize = `SEND_ERC20 (${exactOutflow}) at nonce ${params.nonce}`;
3397
- } else if (d.operation === "APPROVE_ERC20") {
3398
- const token = assertEvmAddress(d.tokenAddress, "tokenAddress");
3399
- allowedRecipientOrSpender = assertEvmAddress(d.recipientOrSpenderAddress, "recipientOrSpenderAddress");
3400
- maxTokenOutflowWei = String(parsePositiveUint256(d.amountWei, "amountWei"));
3401
- exactOutflow = `ALLOWANCE ${maxTokenOutflowWei} units of ${token} for spender ${allowedRecipientOrSpender}`;
3402
- youAuthorize = `APPROVE_ERC20 (${exactOutflow}) at nonce ${params.nonce}`;
3403
- } else if (d.operation === "MIGRATE_VAULT") {
3404
- const newVault = assertEvmAddress(d.newVaultAddress, "newVaultAddress");
3405
- allowedRecipientOrSpender = newVault;
3406
- exactOutflow = `ZERO_FUND_MOVEMENT_MIGRATE -> ${newVault}`;
3407
- youAuthorize = `MIGRATE_VAULT to ${newVault} at nonce ${params.nonce}`;
3408
- } else if (d.operation === "REPLACE_SEED_SIGNER") youAuthorize = `REPLACE_SEED_SIGNER ${assertEvmAddress(d.oldSeedSignerAddress, "oldSeedSignerAddress")} -> ${assertEvmAddress(d.newSeedSignerAddress, "newSeedSignerAddress")} at nonce ${params.nonce}`;
3409
- else if (d.operation === "ADD_SIGNER" || d.operation === "REMOVE_SIGNER") {
3410
- const signer = assertEvmAddress(d.signerAddress, "signerAddress");
3411
- youAuthorize = `${d.operation} ${signer} at nonce ${params.nonce}`;
3412
- } else if (d.operation === "SET_THRESHOLD") youAuthorize = `SET_THRESHOLD to ${d.newThreshold} at nonce ${params.nonce}`;
3413
- return Object.freeze({
3414
- youAuthorize,
3415
- targetVault,
3416
- exactOutflow,
3417
- decodedParams: Object.freeze({ ...d }),
3418
- postConditions: Object.freeze({
3419
- strictZeroUnlistedOutflow: true,
3420
- maxTokenOutflowWei,
3421
- ...allowedRecipientOrSpender ? { allowedRecipientOrSpender } : {}
3422
- })
3423
- });
3424
- }
3425
- function assertHumanText(value, label, maxLen = 512) {
3426
- if (typeof value !== "string" || value.trim().length === 0) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: ${label} must be a non-empty string`);
3427
- const trimmed = value.trim();
3428
- if (trimmed.length > maxLen || /[\x00-\x1f\x7f]|::|\|/.test(trimmed)) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: ${label} exceeds max length or contains forbidden delimiters`);
3429
- return trimmed;
3430
- }
3431
- function computeVLedgerMultiSigProposalHash(input, options) {
3432
- if (!input || typeof input !== "object") throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: proposal input must be an object");
3433
- if (!ALLOWED_LEDGER_MODES.has(input.ledgerMode)) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: invalid ledgerMode ${String(input.ledgerMode)}`);
3434
- if (!ALLOWED_PROPOSAL_CATEGORIES.has(input.category)) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: invalid category ${String(input.category)}`);
3435
- const selectorHex = MULTISIG_SELECTOR_HEX_MAP[input.operation];
3436
- if (!selectorHex) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: invalid operation ${input.operation}`);
3437
- const expectedCategory = EXPECTED_CATEGORY_BY_OPERATION[input.operation];
3438
- if (input.category !== expectedCategory) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: semantic spoofing blocked — operation ${input.operation} requires category ${expectedCategory}, got ${input.category}`);
3439
- const proposalId = assertCleanString(input.proposalId, "proposalId");
3440
- const proposerDid = assertCleanString(input.proposerDid, "proposerDid");
3441
- const proposerEvmAddress = assertEvmAddress(input.proposerEvmAddress, "proposerEvmAddress");
3442
- const title = assertHumanText(input.title, "title", 200);
3443
- const rationale = assertHumanText(input.rationale, "rationale", 1e3);
3444
- const evmChainId = assertCleanString(input.evmChainId, "evmChainId");
3445
- const signerManagerAddress = assertEvmAddress(input.signerManagerAddress, "signerManagerAddress");
3446
- const targetContractAddress = assertEvmAddress(input.targetContractAddress, "targetContractAddress");
3447
- if (!Number.isSafeInteger(input.nonce) || input.nonce < 0) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: nonce must be a non-negative integer");
3448
- const paramsHash = assertBytes32Hex(input.paramsHash, "paramsHash");
3449
- if (input.decodedParams !== void 0) {
3450
- if (input.decodedParams.operation !== input.operation) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: decodedParams.operation (${input.decodedParams.operation}) does not match proposal operation (${input.operation})`);
3451
- const computedFromDecoded = computeMultiSigOperationParamsHash(input.decodedParams);
3452
- if (computedFromDecoded !== paramsHash) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: Bybit blind-signing defense triggered — decodedParams hash (${computedFromDecoded}) does not match paramsHash (${paramsHash})`);
3453
- }
3454
- if (!Number.isSafeInteger(input.proposedAtUnixSeconds) || input.proposedAtUnixSeconds <= 0) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: proposedAtUnixSeconds must be a positive integer");
3455
- const minCooldown = Math.max(HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS, options?.minCooldownSeconds ?? HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS);
3456
- const cooldownSeconds = input.cooldownSeconds ?? DEFAULT_MIN_MULTISIG_COOLDOWN_SECONDS;
3457
- if (!Number.isSafeInteger(cooldownSeconds) || cooldownSeconds < minCooldown) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: cooldownSeconds (${cooldownSeconds}) must be an integer >= ${minCooldown}s`);
3458
- const ttlSeconds = input.ttlSeconds ?? DEFAULT_MULTISIG_CERT_TTL_SECONDS;
3459
- if (!Number.isSafeInteger(ttlSeconds) || ttlSeconds < MIN_MULTISIG_CERT_TTL_SECONDS || ttlSeconds > MAX_MULTISIG_CERT_TTL_SECONDS) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: ttlSeconds (${ttlSeconds}) must be within [${MIN_MULTISIG_CERT_TTL_SECONDS}, ${MAX_MULTISIG_CERT_TTL_SECONDS}]`);
3460
- const clearSigningPreviewHash = input.decodedParams !== void 0 ? utf8Keccak256Hex(JSON.stringify(buildPublishedMultiSigClearSigningPreview({
3461
- targetContractAddress,
3462
- nonce: input.nonce,
3463
- decodedParams: input.decodedParams
3464
- }))) : ZERO_BYTES32_HASH;
3465
- return utf8Keccak256Hex([
3466
- "ocap:published-multisig-proposal:v1",
3467
- input.ledgerMode,
3468
- proposalId,
3469
- proposerDid,
3470
- proposerEvmAddress,
3471
- input.category,
3472
- title,
3473
- rationale,
3474
- evmChainId,
3475
- signerManagerAddress,
3476
- targetContractAddress,
3477
- selectorHex,
3478
- String(input.nonce),
3479
- paramsHash,
3480
- String(input.proposedAtUnixSeconds),
3481
- String(cooldownSeconds),
3482
- String(ttlSeconds),
3483
- clearSigningPreviewHash
3484
- ].join("::"));
3485
- }
3486
- /**
3487
- * Computes the canonical, tamper-evident hash over all fields of an `OcapPublishedMultiSigCertificate` (RT-1262-3, RT-1262-15).
3488
- */
3489
- function computePublishedMultiSigCertificateHash(cert) {
3490
- const selectorHex = MULTISIG_SELECTOR_HEX_MAP[cert.operation];
3491
- if (!selectorHex || cert.selectorHex !== selectorHex) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: certificate selectorHex mismatch");
3492
- if (!Array.isArray(cert.votes) || cert.votes.length === 0 || cert.votes.length > MAX_MULTISIG_VOTES_PER_CERT) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: certificate votes must contain 1..${MAX_MULTISIG_VOTES_PER_CERT} entries`);
3493
- const serializedVotes = cert.votes.map((v) => [
3494
- utf8Keccak256Hex(assertCleanString(v.voterDid, "vote.voterDid")),
3495
- assertEvmAddress(v.voterEvmAddress, "vote.voterEvmAddress"),
3496
- utf8Keccak256Hex(assertHumanText(v.comment, "vote.comment", 500)),
3497
- String(v.votedAtUnixSeconds),
3498
- String(v.v),
3499
- assertBytes32Hex(v.r, "vote.r"),
3500
- assertBytes32Hex(v.s, "vote.s"),
3501
- assertBytes32Hex(v.eip712Digest, "vote.eip712Digest")
3502
- ].join(":")).join("|");
3503
- const clearSigningPreviewHash = cert.clearSigningPreview ? utf8Keccak256Hex(JSON.stringify(cert.clearSigningPreview)) : ZERO_BYTES32_HASH;
3504
- return utf8Keccak256Hex([
3505
- "ocap:published-multisig-cert:v1",
3506
- cert.kind,
3507
- String(cert.schemaVersion),
3508
- assertCleanString(cert.proposalId, "cert.proposalId"),
3509
- cert.ledgerMode,
3510
- assertBytes32Hex(cert.vledgerProposalHash, "cert.vledgerProposalHash"),
3511
- assertBytes32Hex(cert.vledgerStateRoot, "cert.vledgerStateRoot"),
3512
- assertCleanString(cert.proposerDid, "cert.proposerDid"),
3513
- assertEvmAddress(cert.proposerEvmAddress, "cert.proposerEvmAddress"),
3514
- assertHumanText(cert.title, "cert.title", 200),
3515
- assertHumanText(cert.rationale, "cert.rationale", 1e3),
3516
- cert.category,
3517
- assertCleanString(cert.evmChainId, "cert.evmChainId"),
3518
- assertEvmAddress(cert.signerManagerAddress, "cert.signerManagerAddress"),
3519
- assertEvmAddress(cert.targetContractAddress, "cert.targetContractAddress"),
3520
- cert.operation,
3521
- selectorHex,
3522
- String(cert.nonce),
3523
- assertBytes32Hex(cert.paramsHash, "cert.paramsHash"),
3524
- String(cert.proposedAtUnixSeconds),
3525
- String(cert.executableAfterUnixSeconds),
3526
- String(cert.expiresAtUnixSeconds),
3527
- String(cert.issuedAtUnixSeconds),
3528
- clearSigningPreviewHash,
3529
- serializedVotes
3530
- ].join("::"));
3531
- }
3532
- function freezePublishedCertificate(cert) {
3533
- const clonedVotes = cert.votes.map((v) => Object.freeze({ ...v }));
3534
- return Object.freeze({
3535
- ...cert,
3536
- ...cert.clearSigningPreview ? { clearSigningPreview: Object.freeze({ ...cert.clearSigningPreview }) } : {},
3537
- votes: Object.freeze(clonedVotes)
3538
- });
3539
- }
3540
- /**
3541
- * Computes the EIP-712 digest for a Published Indirect Multi-Sig Vote (`seq: 508..511`, Issue #1262):
3542
- * Binds `vledgerProposalHash`, `executableAfterUnixSeconds`, and `expiresAtUnixSeconds` directly into
3543
- * the foreign chain `MultiSigVaultV2` / `SignerManagerV2` EIP-712 struct hash (`RT-1262-8`, `RT-1262-13`).
3544
- */
3545
- function computePublishedMultiSigVoteDigest(params) {
3546
- const vledgerProposalHash = assertBytes32Hex(params.vledgerProposalHash, "vledgerProposalHash");
3547
- if (!Number.isSafeInteger(params.executableAfterUnixSeconds) || params.executableAfterUnixSeconds <= 0 || !Number.isSafeInteger(params.expiresAtUnixSeconds) || params.expiresAtUnixSeconds <= params.executableAfterUnixSeconds) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: invalid executableAfterUnixSeconds or expiresAtUnixSeconds");
3548
- const base = computeHardenedMultiSigOpDigest({
3549
- evmChainId: params.evmChainId,
3550
- signerManagerAddress: params.signerManagerAddress,
3551
- targetContractAddress: params.targetContractAddress,
3552
- operation: params.operation,
3553
- nonce: params.nonce,
3554
- paramsHash: params.paramsHash
3555
- });
3556
- const targetWord64 = assertEvmAddress(params.targetContractAddress, "targetContractAddress").slice(2).padStart(64, "0");
3557
- const selectorWord = base.selectorHex.slice(2).toLowerCase().padEnd(64, "0");
3558
- const paramsHash = assertBytes32Hex(params.paramsHash, "paramsHash");
3559
- const structHash = keccak256(`0x${PUBLISHED_MULTISIG_CERT_OP_TYPEHASH.slice(2)}${vledgerProposalHash.slice(2)}${targetWord64}${selectorWord}${uint256ToHex64(params.nonce)}${paramsHash.slice(2)}${uint256ToHex64(params.executableAfterUnixSeconds)}${uint256ToHex64(params.expiresAtUnixSeconds)}`).toLowerCase();
3560
- const digest = keccak256(`0x1901${base.domainSeparator.slice(2)}${structHash.slice(2)}`).toLowerCase();
3561
- return {
3562
- domainSeparator: base.domainSeparator,
3563
- structHash,
3564
- digest,
3565
- selectorHex: base.selectorHex
3566
- };
3567
- }
3568
- /**
3569
- * Computes the EIP-712 Seed Signer Veto Attestation Digest (`RT-1262-9`):
3570
- * Allows any Seed Signer to cryptographically sign a veto that is enforced both on VLedger and on the
3571
- * foreign-chain `SignerManagerV2` contract (`recordVetoAttestation`).
3572
- */
3573
- function computeMultiSigVetoAttestationDigest(params) {
3574
- const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
3575
- const signerManagerAddress = assertEvmAddress(params.signerManagerAddress, "signerManagerAddress");
3576
- const vledgerProposalHash = assertBytes32Hex(params.vledgerProposalHash, "vledgerProposalHash");
3577
- const targetContractAddress = assertEvmAddress(params.targetContractAddress, "targetContractAddress");
3578
- const seedEvmAddress = assertEvmAddress(params.seedEvmAddress, "seedEvmAddress");
3579
- if (!Number.isSafeInteger(params.nonce) || params.nonce < 0) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: nonce must be a non-negative integer");
3580
- const nameHash = utf8Keccak256Hex("ArcMultiSigSignerManagerV2").slice(2);
3581
- const versionHash = utf8Keccak256Hex("2").slice(2);
3582
- const chainIdHex64 = CANONICAL_UINT256_DECIMAL_REGEX.test(evmChainId) ? uint256ToHex64(BigInt(evmChainId)) : utf8Keccak256Hex(evmChainId).slice(2);
3583
- const domainSeparator = keccak256(`0x${EIP712_DOMAIN_TYPEHASH.slice(2)}${nameHash}${versionHash}${chainIdHex64}${signerManagerAddress.slice(2).padStart(64, "0")}`).toLowerCase();
3584
- const structHash = keccak256(`0x${MULTISIG_VETO_ATTESTATION_TYPEHASH.slice(2)}${vledgerProposalHash.slice(2)}${targetContractAddress.slice(2).padStart(64, "0")}${uint256ToHex64(params.nonce)}${seedEvmAddress.slice(2).padStart(64, "0")}`).toLowerCase();
3585
- return {
3586
- domainSeparator,
3587
- structHash,
3588
- digest: keccak256(`0x1901${domainSeparator.slice(2)}${structHash.slice(2)}`).toLowerCase()
3589
- };
3590
- }
3591
- /**
3592
- * Computes the Holder Hardware Final Release Intent Digest (`seq: 508..511`, Issue #1262):
3593
- * Because OCAP software nodes never hold custody keys or auto-sign foreign chain transactions,
3594
- * an authorized human executor must sign this Final Release Intent with their hardware key
3595
- * when submitting the `OcapPublishedMultiSigCertificate` to the foreign chain contract.
3596
- */
3597
- function computeHolderFinalReleaseDigest(params) {
3598
- const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
3599
- const signerManagerAddress = assertEvmAddress(params.signerManagerAddress, "signerManagerAddress");
3600
- const certificateHash = assertBytes32Hex(params.certificateHash, "certificateHash");
3601
- const vledgerProposalHash = assertBytes32Hex(params.vledgerProposalHash, "vledgerProposalHash");
3602
- const targetContractAddress = assertEvmAddress(params.targetContractAddress, "targetContractAddress");
3603
- const executorEvmAddress = assertEvmAddress(params.executorEvmAddress, "executorEvmAddress");
3604
- if (!Number.isSafeInteger(params.nonce) || params.nonce < 0) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: nonce must be a non-negative integer");
3605
- if (!Number.isSafeInteger(params.executableAfterUnixSeconds) || params.executableAfterUnixSeconds <= 0 || !Number.isSafeInteger(params.expiresAtUnixSeconds) || params.expiresAtUnixSeconds <= params.executableAfterUnixSeconds) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: invalid executableAfterUnixSeconds or expiresAtUnixSeconds");
3606
- const nameHash = utf8Keccak256Hex("ArcMultiSigSignerManagerV2").slice(2);
3607
- const versionHash = utf8Keccak256Hex("2").slice(2);
3608
- const chainIdHex64 = CANONICAL_UINT256_DECIMAL_REGEX.test(evmChainId) ? uint256ToHex64(BigInt(evmChainId)) : utf8Keccak256Hex(evmChainId).slice(2);
3609
- const domainSeparator = keccak256(`0x${EIP712_DOMAIN_TYPEHASH.slice(2)}${nameHash}${versionHash}${chainIdHex64}${signerManagerAddress.slice(2).padStart(64, "0")}`).toLowerCase();
3610
- const structHash = keccak256(`0x${HOLDER_RELEASE_INTENT_TYPEHASH.slice(2)}${certificateHash.slice(2)}${vledgerProposalHash.slice(2)}${targetContractAddress.slice(2).padStart(64, "0")}${uint256ToHex64(params.nonce)}${uint256ToHex64(params.executableAfterUnixSeconds)}${uint256ToHex64(params.expiresAtUnixSeconds)}${executorEvmAddress.slice(2).padStart(64, "0")}`).toLowerCase();
3611
- return keccak256(`0x1901${domainSeparator.slice(2)}${structHash.slice(2)}`).toLowerCase();
3612
- }
3613
- /**
3614
- * Standardized Published Indirect Multi-Sig Engine (`OcapPublishedMultiSigEngine`, Issue #1262):
3615
- * Implements the 3-stage VLedger / OCAP Certificate-Driven Cross-Chain Control Plane:
3616
- * 1. Public Proposal & Vote History on VLedger / OCAP (with pre-execution notifications, cooldowns, and cryptographic Veto).
3617
- * 2. Deterministic `OcapPublishedMultiSigCertificate` generation once M-of-N (`threshold` + `seedThreshold`) is met.
3618
- * 3. Foreign-chain `MultiSigVaultV2` execution gated by BOTH the published certificate AND an individual holder's
3619
- * hardware Final Release Signature (zero software custody on OCAP nodes).
3620
- */
3621
- var OcapPublishedMultiSigEngine = class {
3622
- constructor(signerManager, options) {
3623
- this.proposals = /* @__PURE__ */ new Map();
3624
- this.vledgerSequence = 0;
3625
- this.vledgerStateRoot = ZERO_BYTES32_HASH;
3626
- this.signerManager = signerManager;
3627
- const minCooldown = options?.minCooldownSeconds ?? DEFAULT_MIN_MULTISIG_COOLDOWN_SECONDS;
3628
- if (!Number.isSafeInteger(minCooldown) || minCooldown < HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: minCooldownSeconds must be an integer >= ${HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS}`);
3629
- this.minCooldownSeconds = minCooldown;
3630
- }
3631
- getVLedgerStateRoot() {
3632
- return this.vledgerStateRoot;
3633
- }
3634
- getProposalStatus(proposalId, nowUnixSeconds) {
3635
- const prop = this.proposals.get(proposalId);
3636
- if (!prop) return void 0;
3637
- if (prop.vetoed) return "VETOED";
3638
- if (prop.executed) return "EXECUTED";
3639
- if (nowUnixSeconds !== void 0 && nowUnixSeconds > prop.expiresAtUnixSeconds) return "EXPIRED";
3640
- if (prop.issuedCert) return "CERT_ISSUED";
3641
- return "VOTING";
3642
- }
3643
- createProposal(input) {
3644
- if (!input || typeof input !== "object") throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: proposal input must be an object");
3645
- if (this.proposals.size >= MAX_PUBLISHED_MULTISIG_PROPOSALS) for (const [id, existing] of this.proposals.entries()) {
3646
- const targetNonce = this.signerManager.getTargetNonce(existing.input.targetContractAddress);
3647
- if (existing.vetoed || existing.executed || existing.input.nonce < targetNonce || Number.isSafeInteger(input.proposedAtUnixSeconds) && input.proposedAtUnixSeconds > existing.expiresAtUnixSeconds) this.proposals.delete(id);
3648
- }
3649
- if (this.proposals.size >= MAX_PUBLISHED_MULTISIG_PROPOSALS) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: active proposal pool reached cap (${MAX_PUBLISHED_MULTISIG_PROPOSALS})`);
3650
- const proposalId = assertCleanString(input.proposalId, "proposalId");
3651
- if (this.proposals.has(proposalId)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: duplicate proposalId ${proposalId}`);
3652
- const proposerEvmAddress = assertEvmAddress(input.proposerEvmAddress, "proposerEvmAddress");
3653
- const managerState = this.signerManager.getState();
3654
- if (!managerState.signers.includes(proposerEvmAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposer ${proposerEvmAddress} is not an authorized vault signer`);
3655
- if (input.evmChainId !== managerState.evmChainId || assertEvmAddress(input.signerManagerAddress, "signerManagerAddress") !== managerState.signerManagerAddress) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: proposal chainId or signerManagerAddress mismatch");
3656
- const targetContractAddress = assertEvmAddress(input.targetContractAddress, "targetContractAddress");
3657
- const expectedNonce = this.signerManager.getTargetNonce(targetContractAddress);
3658
- if (input.nonce !== expectedNonce) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal nonce (${input.nonce}) does not match target contract nonce (${expectedNonce})`);
3659
- for (const existing of this.proposals.values()) if (!existing.vetoed && !existing.executed && existing.input.targetContractAddress === targetContractAddress && existing.input.nonce === expectedNonce && existing.input.proposerEvmAddress === proposerEvmAddress && input.proposedAtUnixSeconds <= existing.expiresAtUnixSeconds) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposer ${proposerEvmAddress} already has an active proposal (${existing.input.proposalId}) for ${targetContractAddress} at nonce ${expectedNonce}`);
3660
- const cooldownSeconds = input.cooldownSeconds ?? this.minCooldownSeconds;
3661
- const ttlSeconds = input.ttlSeconds ?? DEFAULT_MULTISIG_CERT_TTL_SECONDS;
3662
- const normalizedInput = {
3663
- ...input,
3664
- proposerEvmAddress,
3665
- signerManagerAddress: managerState.signerManagerAddress,
3666
- targetContractAddress,
3667
- paramsHash: assertBytes32Hex(input.paramsHash, "paramsHash"),
3668
- cooldownSeconds,
3669
- ttlSeconds
3670
- };
3671
- const vledgerProposalHash = computeVLedgerMultiSigProposalHash(normalizedInput, { minCooldownSeconds: this.minCooldownSeconds });
3672
- const executableAfterUnixSeconds = normalizedInput.proposedAtUnixSeconds + cooldownSeconds;
3673
- const expiresAtUnixSeconds = executableAfterUnixSeconds + ttlSeconds;
3674
- const clearSigningPreview = normalizedInput.decodedParams ? buildPublishedMultiSigClearSigningPreview({
3675
- targetContractAddress,
3676
- nonce: normalizedInput.nonce,
3677
- decodedParams: normalizedInput.decodedParams
3678
- }) : void 0;
3679
- this.vledgerSequence += 1;
3680
- this.vledgerStateRoot = utf8Keccak256Hex(`vledger:propose:${this.vledgerSequence}:${this.vledgerStateRoot}:${vledgerProposalHash}`);
3681
- this.proposals.set(proposalId, {
3682
- input: normalizedInput,
3683
- vledgerProposalHash,
3684
- executableAfterUnixSeconds,
3685
- expiresAtUnixSeconds,
3686
- clearSigningPreview,
3687
- vetoed: false,
3688
- executed: false,
3689
- votesBySigner: /* @__PURE__ */ new Map(),
3690
- voterDids: /* @__PURE__ */ new Set()
3691
- });
3692
- return {
3693
- proposalId,
3694
- vledgerProposalHash,
3695
- executableAfterUnixSeconds,
3696
- expiresAtUnixSeconds,
3697
- ...clearSigningPreview ? { clearSigningPreview } : {},
3698
- vledgerStateRoot: this.vledgerStateRoot
3699
- };
3700
- }
3701
- recordVote(params) {
3702
- const prop = this.proposals.get(params.proposalId);
3703
- if (!prop) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} not found`);
3704
- if (prop.vetoed || this.signerManager.isProposalVetoed(prop.vledgerProposalHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} has been vetoed (${prop.vetoReason ?? "on-chain veto"})`);
3705
- if (prop.executed) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} has already been executed`);
3706
- if (prop.issuedCert) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate already issued for proposal ${params.proposalId}`);
3707
- const currentNonce = this.signerManager.getTargetNonce(prop.input.targetContractAddress);
3708
- if (prop.input.nonce !== currentNonce) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: cannot vote on stale proposal nonce (${prop.input.nonce} !== ${currentNonce})`);
3709
- if (!Number.isSafeInteger(params.votedAtUnixSeconds) || params.votedAtUnixSeconds < prop.input.proposedAtUnixSeconds || params.votedAtUnixSeconds > prop.expiresAtUnixSeconds) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: votedAtUnixSeconds must be within [${prop.input.proposedAtUnixSeconds}, ${prop.expiresAtUnixSeconds}]`);
3710
- const voterDid = assertCleanString(params.voterDid, "voterDid");
3711
- const voterEvmAddress = assertEvmAddress(params.voterEvmAddress, "voterEvmAddress");
3712
- const comment = assertHumanText(params.comment, "comment", 500);
3713
- if (!this.signerManager.getState().signers.includes(voterEvmAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: voter ${voterEvmAddress} is not an authorized vault signer`);
3714
- if (prop.votesBySigner.has(voterEvmAddress) || prop.voterDids.has(voterDid)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: duplicate vote from signer ${voterEvmAddress} (${voterDid})`);
3715
- const { digest } = computePublishedMultiSigVoteDigest({
3716
- evmChainId: prop.input.evmChainId,
3717
- signerManagerAddress: prop.input.signerManagerAddress,
3718
- vledgerProposalHash: prop.vledgerProposalHash,
3719
- targetContractAddress: prop.input.targetContractAddress,
3720
- operation: prop.input.operation,
3721
- nonce: prop.input.nonce,
3722
- paramsHash: prop.input.paramsHash,
3723
- executableAfterUnixSeconds: prop.executableAfterUnixSeconds,
3724
- expiresAtUnixSeconds: prop.expiresAtUnixSeconds
3725
- });
3726
- const recovered = ecrecoverEvmAddress(digest, params.v, params.r, params.s);
3727
- if (recovered !== voterEvmAddress) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: vote signature recovery mismatch (${recovered} !== ${voterEvmAddress})`);
3728
- const voteRecord = Object.freeze({
3729
- voterDid,
3730
- voterEvmAddress,
3731
- comment,
3732
- votedAtUnixSeconds: params.votedAtUnixSeconds,
3733
- v: params.v,
3734
- r: assertBytes32Hex(params.r, "r"),
3735
- s: assertBytes32Hex(params.s, "s"),
3736
- eip712Digest: digest
3737
- });
3738
- prop.votesBySigner.set(voterEvmAddress, voteRecord);
3739
- prop.voterDids.add(voterDid);
3740
- this.vledgerSequence += 1;
3741
- this.vledgerStateRoot = utf8Keccak256Hex(`vledger:vote:${this.vledgerSequence}:${this.vledgerStateRoot}:${prop.vledgerProposalHash}:${voterEvmAddress}:${digest}`);
3742
- return {
3743
- proposalId: params.proposalId,
3744
- totalVotes: prop.votesBySigner.size,
3745
- vledgerStateRoot: this.vledgerStateRoot
3746
- };
3747
- }
3748
- /**
3749
- * Cryptographically Authenticated Seed Signer Veto (`RT-1262-8` & `RT-1262-9`):
3750
- * Verifies the Seed Signer's EIP-712 `MultiSigVetoAttestation` signature via `ecrecover` and records the
3751
- * veto on BOTH VLedger (`prop.vetoed = true`) AND the foreign-chain `SignerManagerV2` contract
3752
- * (`this.signerManager.recordVetoAttestation`), blocking off-chain signature scraping bypasses.
3753
- */
3754
- vetoProposal(params) {
3755
- const prop = this.proposals.get(params.proposalId);
3756
- if (!prop) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} not found`);
3757
- if (prop.executed) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: cannot veto proposal ${params.proposalId} after execution`);
3758
- if (prop.vetoed) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} is already vetoed`);
3759
- const seedEvmAddress = assertEvmAddress(params.seedEvmAddress, "seedEvmAddress");
3760
- const guardianOrSeedDid = assertCleanString(params.guardianOrSeedDid, "guardianOrSeedDid");
3761
- const reason = assertHumanText(params.reason, "reason", 500);
3762
- const { digest } = this.signerManager.recordVetoAttestation({
3763
- vledgerProposalHash: prop.vledgerProposalHash,
3764
- targetContractAddress: prop.input.targetContractAddress,
3765
- nonce: prop.input.nonce,
3766
- seedEvmAddress,
3767
- v: params.v,
3768
- r: params.r,
3769
- s: params.s
3770
- });
3771
- prop.vetoed = true;
3772
- prop.vetoedByDid = guardianOrSeedDid;
3773
- prop.vetoReason = reason;
3774
- prop.vetoAttestationDigest = digest;
3775
- this.vledgerSequence += 1;
3776
- this.vledgerStateRoot = utf8Keccak256Hex(`vledger:veto:${this.vledgerSequence}:${this.vledgerStateRoot}:${prop.vledgerProposalHash}:${seedEvmAddress}:${digest}`);
3777
- return {
3778
- vledgerProposalHash: prop.vledgerProposalHash,
3779
- vetoAttestationDigest: digest,
3780
- vledgerStateRoot: this.vledgerStateRoot
3781
- };
3782
- }
3783
- /**
3784
- * Stage 2: Crystallizes the verified vote records into an immutable `OcapPublishedMultiSigCertificate`
3785
- * once M-of-N (`threshold` + `seedThreshold`) is met and `executableAfterUnixSeconds <= nowUnixSeconds <= expiresAtUnixSeconds`.
3786
- */
3787
- issuePublishedCertificate(params) {
3788
- const prop = this.proposals.get(params.proposalId);
3789
- if (!prop) throw new CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} not found`);
3790
- if (prop.vetoed || this.signerManager.isProposalVetoed(prop.vledgerProposalHash)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: cannot issue certificate for vetoed proposal (${prop.vetoReason ?? "on-chain veto"})`);
3791
- if (prop.executed) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} has already been executed`);
3792
- if (prop.issuedCert) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate already issued for proposal ${params.proposalId}`);
3793
- if (!Number.isSafeInteger(params.nowUnixSeconds) || params.nowUnixSeconds <= 0) throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: nowUnixSeconds must be a positive integer");
3794
- if (params.nowUnixSeconds < prop.executableAfterUnixSeconds) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal is still in OCAP/VLedger cooldown until ${prop.executableAfterUnixSeconds}`);
3795
- if (params.nowUnixSeconds > prop.expiresAtUnixSeconds) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal expired at ${prop.expiresAtUnixSeconds}`);
3796
- const currentNonce = this.signerManager.getTargetNonce(prop.input.targetContractAddress);
3797
- if (prop.input.nonce !== currentNonce) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: stale proposal nonce (${prop.input.nonce} !== ${currentNonce})`);
3798
- const managerState = this.signerManager.getState();
3799
- if (!managerState.signers.includes(prop.input.proposerEvmAddress)) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposer ${prop.input.proposerEvmAddress} is no longer an active vault signer`);
3800
- for (const [otherId, other] of this.proposals.entries()) if (otherId !== params.proposalId && other.issuedCert && !other.vetoed && !other.executed && other.input.targetContractAddress === prop.input.targetContractAddress && other.input.nonce === currentNonce && params.nowUnixSeconds <= other.expiresAtUnixSeconds) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: another active certificate (${otherId}) is already issued for ${prop.input.targetContractAddress} at nonce ${currentNonce}`);
3801
- const activeVotes = Array.from(prop.votesBySigner.values()).filter((v) => managerState.signers.includes(v.voterEvmAddress)).sort((a, b) => BigInt(a.voterEvmAddress) < BigInt(b.voterEvmAddress) ? -1 : 1);
3802
- if (activeVotes.length < managerState.threshold) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: insufficient active votes (${activeVotes.length} < ${managerState.threshold})`);
3803
- const seedSignedCount = activeVotes.filter((v) => managerState.seedSigners.includes(v.voterEvmAddress)).length;
3804
- if (seedSignedCount < managerState.seedThreshold) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: insufficient seed signer votes (${seedSignedCount} < ${managerState.seedThreshold})`);
3805
- const selectorHex = MULTISIG_SELECTOR_HEX_MAP[prop.input.operation];
3806
- const unsignedCert = {
3807
- kind: "OcapPublishedMultiSigCert",
3808
- schemaVersion: 1,
3809
- proposalId: prop.input.proposalId,
3810
- ledgerMode: prop.input.ledgerMode,
3811
- vledgerProposalHash: prop.vledgerProposalHash,
3812
- vledgerStateRoot: this.vledgerStateRoot,
3813
- proposerDid: prop.input.proposerDid,
3814
- proposerEvmAddress: prop.input.proposerEvmAddress,
3815
- title: prop.input.title,
3816
- rationale: prop.input.rationale,
3817
- category: prop.input.category,
3818
- evmChainId: prop.input.evmChainId,
3819
- signerManagerAddress: prop.input.signerManagerAddress,
3820
- targetContractAddress: prop.input.targetContractAddress,
3821
- operation: prop.input.operation,
3822
- selectorHex,
3823
- nonce: prop.input.nonce,
3824
- paramsHash: prop.input.paramsHash,
3825
- proposedAtUnixSeconds: prop.input.proposedAtUnixSeconds,
3826
- executableAfterUnixSeconds: prop.executableAfterUnixSeconds,
3827
- expiresAtUnixSeconds: prop.expiresAtUnixSeconds,
3828
- issuedAtUnixSeconds: params.nowUnixSeconds,
3829
- ...prop.clearSigningPreview ? { clearSigningPreview: prop.clearSigningPreview } : {},
3830
- votes: activeVotes
3831
- };
3832
- const certHash = computePublishedMultiSigCertificateHash(unsignedCert);
3833
- const frozenCert = freezePublishedCertificate({
3834
- ...unsignedCert,
3835
- certificateHash: certHash
3836
- });
3837
- prop.issuedCert = frozenCert;
3838
- return frozenCert;
3839
- }
3840
- /**
3841
- * Stage 3 (Holder Hardware Final Release on Foreign Chain):
3842
- * Delegates to `this.signerManager.verifyAndConsumePublishedCertificate` (stateless foreign-chain contract verifier)
3843
- * AND verifies VLedger state consistency, then marks the proposal `EXECUTED`.
3844
- */
3845
- executeWithPublishedCertificate(params) {
3846
- if (!params || typeof params !== "object" || !params.certificate || typeof params.certificate !== "object") throw new CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: certificate object is required");
3847
- const cert = params.certificate;
3848
- const prop = this.proposals.get(cert.proposalId);
3849
- if (!prop || prop.vetoed) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: proposal does not exist or was vetoed on OCAP/VLedger");
3850
- if (prop.executed) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate for proposal ${cert.proposalId} has already been executed`);
3851
- if (!prop.issuedCert) throw new CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate has not been issued for proposal ${cert.proposalId}`);
3852
- if (cert.vledgerProposalHash !== prop.vledgerProposalHash || cert.certificateHash !== prop.issuedCert.certificateHash) throw new CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: certificate does not match VLedger issuedCert");
3853
- const effectiveNow = params.nowUnixSeconds ?? cert.issuedAtUnixSeconds;
3854
- const consumed = this.signerManager.verifyAndConsumePublishedCertificate({
3855
- certificate: cert,
3856
- executorEvmAddress: params.executorEvmAddress,
3857
- holderReleaseSignature: params.holderReleaseSignature,
3858
- nowUnixSeconds: effectiveNow,
3859
- minCooldownSeconds: this.minCooldownSeconds
3860
- });
3861
- prop.executed = true;
3862
- return {
3863
- executed: true,
3864
- proposalId: cert.proposalId,
3865
- vledgerProposalHash: consumed.vledgerProposalHash,
3866
- certificateHash: consumed.certificateHash,
3867
- executorEvmAddress: consumed.executorEvmAddress,
3868
- consumedNonce: consumed.consumedNonce,
3869
- verifiedSigners: consumed.verifiedSigners
3870
- };
3871
- }
3872
- };
3873
-
3874
- //#endregion
3875
- export { ARC_EVM_BRIDGE_GATEWAY_SOLIDITY_SPEC, BRIDGE_CHARTER_KIND, DEFAULT_MAX_ROLLUP_BLOCK_SIZE, DEFAULT_MIN_EVM_CONFIRMATIONS, DEFAULT_MIN_MULTISIG_COOLDOWN_SECONDS, DEFAULT_MULTISIG_CERT_TTL_SECONDS, DEFAULT_ROLLUP_SUNSET_ACTIVATION_HEIGHT, DEFAULT_VERIFYING_CONTRACT_ADDRESS, DEFAULT_WITHDRAW_TIMELOCK_DELAY_SECONDS, DEPRECATED_ROLLUP_PROTOCOL_TYPE_URLS, DIRECT_WITHDRAW_TYPEHASH, EIP712_BRIDGE_DOMAIN_NAME, EIP712_BRIDGE_DOMAIN_VERSION, EIP712_DOMAIN_TYPEHASH, EMPTY_ROLLUP_MERKLE_ROOT, EXPECTED_CATEGORY_BY_OPERATION, HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS, HOLDER_RELEASE_INTENT_TYPEHASH, HardenedMultiSigSignerManagerV2, MAX_DIRECT_VOUCHER_TTL_SECONDS, MAX_EDGE_WEBHOOK_BODY_BYTES, MAX_EDGE_WEBHOOK_SKEW_SECONDS, MAX_MULTISIG_CERT_TTL_SECONDS, MAX_MULTISIG_VOTES_PER_CERT, MAX_PUBLISHED_MULTISIG_PROPOSALS, MAX_TRACKED_WEBHOOK_NONCES, MIN_DIRECT_VOUCHER_TTL_SECONDS, MIN_MULTISIG_CERT_TTL_SECONDS, MULTISIG_OP_TYPEHASH, MULTISIG_VETO_ATTESTATION_TYPEHASH, OcapLocalEvmBridgeTestnetHarness, OcapOnChainBridgeGovernanceRegistry, OcapPublishedMultiSigEngine, OcapSimplifiedEvmBridgeNode, PUBLISHED_MULTISIG_CERT_OP_TYPEHASH, TWO_PHASE_CHALLENGE_TYPEHASH, ZERO_BYTES32_HASH, ZERO_EVM_ADDRESS, assertRollupProtocolNotSunset, buildEvmBridgeMerkleTree, buildPublishedMultiSigClearSigningPreview, computeBridgeGovernanceCharterHash, computeDirectWithdrawVoucherDigest, computeEdgeWebhookHmac, computeEip712BridgeDomainSeparator, computeEip712WithdrawStructHash, computeEvmBridgeBlockHash, computeEvmBridgeTxsHash, computeEvmBridgeWithdrawLeafHash, computeEvmTwoPhaseChallengeHash, computeHardenedMultiSigOpDigest, computeHolderFinalReleaseDigest, computeMultiSigOperationParamsHash, computeMultiSigVetoAttestationDigest, computePublishedMultiSigCertificateHash, computePublishedMultiSigVoteDigest, computeVLedgerMultiSigProposalHash, computeValidatorBlockSignatureDigest, computeValidatorVoucherSignatureDigest, deriveEvmAddressFromPrivateKeyHex, ecrecoverEvmAddress, encodeEvmBridgeWithdrawPackedPreimage, isDeprecatedRollupWriteProtocol, parseLegacyRollupReadOnlyRecord, signDigestWithSecp256k1PrivateKey, verifyDirectWithdrawVoucher, verifyEvmBridgeMerkleProof };