@ocap/tx-pipeline 1.30.25 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/esm/appchain-sovereign-hub.d.mts +160 -0
  2. package/esm/appchain-sovereign-hub.mjs +348 -0
  3. package/esm/arcvault-external-adapter.d.mts +166 -0
  4. package/esm/arcvault-external-adapter.mjs +376 -0
  5. package/esm/encrypted-nft-envelope.d.mts +172 -0
  6. package/esm/encrypted-nft-envelope.mjs +458 -0
  7. package/esm/evm-simplified-bridge.d.mts +1370 -0
  8. package/esm/evm-simplified-bridge.mjs +3875 -0
  9. package/esm/give-to-mint-karma.d.mts +472 -0
  10. package/esm/give-to-mint-karma.mjs +1057 -0
  11. package/esm/helpers/replay-guard.d.mts +15 -0
  12. package/esm/helpers/replay-guard.mjs +23 -0
  13. package/esm/index.d.mts +10 -5
  14. package/esm/index.mjs +14 -10
  15. package/esm/legacy-protocol-sunset.d.mts +251 -0
  16. package/esm/legacy-protocol-sunset.mjs +1519 -0
  17. package/esm/library.d.mts +16 -0
  18. package/esm/library.mjs +17 -0
  19. package/esm/native-abt-exchange.d.mts +2055 -0
  20. package/esm/native-abt-exchange.mjs +7250 -0
  21. package/esm/ofac-screening.d.mts +17 -0
  22. package/esm/ofac-screening.mjs +39 -0
  23. package/esm/pipes/anti-land-attack.mjs +1 -1
  24. package/esm/pipes/decode-itx.mjs +43 -4
  25. package/esm/pipes/decode-tx.d.mts +2 -3
  26. package/esm/pipes/decode-tx.mjs +53 -115
  27. package/esm/pipes/extract-signer.mjs +2 -2
  28. package/esm/pipes/extract-state.mjs +14 -3
  29. package/esm/pipes/post-execution-invariant-gate.d.mts +61 -0
  30. package/esm/pipes/post-execution-invariant-gate.mjs +789 -0
  31. package/esm/pipes/pre-flight-waf.d.mts +34 -0
  32. package/esm/pipes/pre-flight-waf.mjs +603 -0
  33. package/esm/pipes/take-state-snapshot.mjs +3 -2
  34. package/esm/pipes/update-owner.mjs +39 -4
  35. package/esm/pipes/verify-account-migration.mjs +14 -4
  36. package/esm/pipes/verify-blocked.mjs +1 -1
  37. package/esm/pipes/verify-delegation.d.mts +22 -3
  38. package/esm/pipes/verify-delegation.mjs +259 -36
  39. package/esm/pipes/verify-list-size.mjs +1 -1
  40. package/esm/pipes/verify-multisig-v2.mjs +15 -7
  41. package/esm/pipes/verify-multisig.mjs +15 -7
  42. package/esm/pipes/verify-sender.mjs +1 -1
  43. package/esm/pipes/verify-signature.mjs +35 -6
  44. package/esm/pipes/verify-signer.mjs +2 -2
  45. package/esm/pipes/verify-state-diff.mjs +3 -3
  46. package/esm/pipes/verify-token-access.mjs +1 -1
  47. package/esm/pipes/verify-token-balance.mjs +13 -5
  48. package/esm/pipes/verify-transferrable.d.mts +8 -1
  49. package/esm/pipes/verify-transferrable.mjs +3 -3
  50. package/esm/pipes/verify-tx-input.mjs +2 -2
  51. package/esm/pipes/verify-tx-size.mjs +46 -2
  52. package/esm/pipes/verify-tx.mjs +5 -7
  53. package/esm/pipes/verify-updater.mjs +1 -1
  54. package/esm/social-economy-factories.d.mts +346 -0
  55. package/esm/social-economy-factories.mjs +845 -0
  56. package/esm/super-suites-foundation.d.mts +513 -0
  57. package/esm/super-suites-foundation.mjs +1241 -0
  58. package/esm/transaction-block.d.mts +471 -0
  59. package/esm/transaction-block.mjs +1906 -0
  60. package/esm/uniswap-erc7683-solver.d.mts +201 -0
  61. package/esm/uniswap-erc7683-solver.mjs +321 -0
  62. package/esm/uniswap-lp-copilot.d.mts +113 -0
  63. package/esm/uniswap-lp-copilot.mjs +320 -0
  64. package/esm/uniswap-router.d.mts +335 -0
  65. package/esm/uniswap-router.mjs +578 -0
  66. package/esm/uniswap-token-factory-graduation.d.mts +187 -0
  67. package/esm/uniswap-token-factory-graduation.mjs +426 -0
  68. package/esm/uniswap-v4-hook.d.mts +173 -0
  69. package/esm/uniswap-v4-hook.mjs +517 -0
  70. package/lib/appchain-sovereign-hub.cjs +352 -0
  71. package/lib/appchain-sovereign-hub.d.cts +160 -0
  72. package/lib/arcvault-external-adapter.cjs +383 -0
  73. package/lib/arcvault-external-adapter.d.cts +166 -0
  74. package/lib/encrypted-nft-envelope.cjs +477 -0
  75. package/lib/encrypted-nft-envelope.d.cts +172 -0
  76. package/lib/evm-simplified-bridge.cjs +3943 -0
  77. package/lib/evm-simplified-bridge.d.cts +1370 -0
  78. package/lib/give-to-mint-karma.cjs +1084 -0
  79. package/lib/give-to-mint-karma.d.cts +472 -0
  80. package/lib/helpers/replay-guard.cjs +27 -0
  81. package/lib/helpers/replay-guard.d.cts +15 -0
  82. package/lib/index.cjs +49 -16
  83. package/lib/index.d.cts +10 -5
  84. package/lib/legacy-protocol-sunset.cjs +1543 -0
  85. package/lib/legacy-protocol-sunset.d.cts +251 -0
  86. package/lib/library.cjs +303 -0
  87. package/lib/library.d.cts +16 -0
  88. package/lib/native-abt-exchange.cjs +7322 -0
  89. package/lib/native-abt-exchange.d.cts +2055 -0
  90. package/lib/ofac-screening.cjs +42 -0
  91. package/lib/ofac-screening.d.cts +17 -0
  92. package/lib/pipes/anti-land-attack.cjs +2 -2
  93. package/lib/pipes/decode-itx.cjs +43 -4
  94. package/lib/pipes/decode-itx.d.cts +1 -1
  95. package/lib/pipes/decode-tx.cjs +52 -116
  96. package/lib/pipes/decode-tx.d.cts +3 -4
  97. package/lib/pipes/extract-signer.cjs +2 -2
  98. package/lib/pipes/extract-state.cjs +14 -3
  99. package/lib/pipes/post-execution-invariant-gate.cjs +800 -0
  100. package/lib/pipes/post-execution-invariant-gate.d.cts +61 -0
  101. package/lib/pipes/pre-flight-waf.cjs +616 -0
  102. package/lib/pipes/pre-flight-waf.d.cts +34 -0
  103. package/lib/pipes/take-state-snapshot.cjs +3 -2
  104. package/lib/pipes/update-owner.cjs +40 -5
  105. package/lib/pipes/update-owner.d.cts +1 -1
  106. package/lib/pipes/verify-account-migration.cjs +14 -4
  107. package/lib/pipes/verify-blocked.cjs +1 -1
  108. package/lib/pipes/verify-delegation.cjs +259 -36
  109. package/lib/pipes/verify-delegation.d.cts +22 -3
  110. package/lib/pipes/verify-list-size.cjs +1 -1
  111. package/lib/pipes/verify-multisig-v2.cjs +15 -7
  112. package/lib/pipes/verify-multisig.cjs +15 -7
  113. package/lib/pipes/verify-sender.cjs +1 -1
  114. package/lib/pipes/verify-service-fee.d.cts +1 -1
  115. package/lib/pipes/verify-signature.cjs +35 -6
  116. package/lib/pipes/verify-signature.d.cts +1 -1
  117. package/lib/pipes/verify-signer.cjs +2 -2
  118. package/lib/pipes/verify-state-diff.cjs +4 -4
  119. package/lib/pipes/verify-token-access.cjs +2 -2
  120. package/lib/pipes/verify-token-balance.cjs +13 -5
  121. package/lib/pipes/verify-transferrable.cjs +3 -3
  122. package/lib/pipes/verify-transferrable.d.cts +8 -1
  123. package/lib/pipes/verify-tx-input.cjs +3 -3
  124. package/lib/pipes/verify-tx-size.cjs +46 -2
  125. package/lib/pipes/verify-tx-size.d.cts +1 -1
  126. package/lib/pipes/verify-tx.cjs +6 -8
  127. package/lib/pipes/verify-tx.d.cts +1 -1
  128. package/lib/pipes/verify-updater.cjs +1 -1
  129. package/lib/social-economy-factories.cjs +852 -0
  130. package/lib/social-economy-factories.d.cts +346 -0
  131. package/lib/super-suites-foundation.cjs +1257 -0
  132. package/lib/super-suites-foundation.d.cts +513 -0
  133. package/lib/transaction-block.cjs +1941 -0
  134. package/lib/transaction-block.d.cts +471 -0
  135. package/lib/uniswap-erc7683-solver.cjs +327 -0
  136. package/lib/uniswap-erc7683-solver.d.cts +201 -0
  137. package/lib/uniswap-lp-copilot.cjs +328 -0
  138. package/lib/uniswap-lp-copilot.d.cts +113 -0
  139. package/lib/uniswap-router.cjs +593 -0
  140. package/lib/uniswap-router.d.cts +335 -0
  141. package/lib/uniswap-token-factory-graduation.cjs +431 -0
  142. package/lib/uniswap-token-factory-graduation.d.cts +187 -0
  143. package/lib/uniswap-v4-hook.cjs +527 -0
  144. package/lib/uniswap-v4-hook.d.cts +173 -0
  145. package/package.json +11 -10
  146. package/esm/helpers/dedup-height.d.mts +0 -16
  147. package/esm/helpers/dedup-height.mjs +0 -61
  148. package/lib/helpers/dedup-height.cjs +0 -72
  149. package/lib/helpers/dedup-height.d.cts +0 -16
@@ -0,0 +1,1543 @@
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const require_evm_simplified_bridge = require('./evm-simplified-bridge.cjs');
3
+ const require_transaction_block = require('./transaction-block.cjs');
4
+ let _ocap_util_lib_error = require("@ocap/util/lib/error");
5
+
6
+ //#region src/legacy-protocol-sunset.ts
7
+ const ErrorCode = {
8
+ InvalidSunset: "INVALID_LEGACY_PROTOCOL_SUNSET",
9
+ ForbiddenSunset: "FORBIDDEN_LEGACY_PROTOCOL_SUNSET"
10
+ };
11
+ const DEFAULT_LEGACY_PROTOCOL_SUNSET_HEIGHT = require_evm_simplified_bridge.DEFAULT_ROLLUP_SUNSET_ACTIVATION_HEIGHT;
12
+ const MAX_LEGACY_MIOTX_PARTICIPANTS = 64;
13
+ const MAX_LEGACY_MIOTX_TOKENS_PER_ENTRY = 32;
14
+ const MAX_LEGACY_MIOTX_ASSETS_PER_ENTRY = 64;
15
+ const CANONICAL_UINT256_DECIMAL_REGEX = /^(0|[1-9]\d{0,77})$/;
16
+ const FORBIDDEN_OBJECT_KEYS = new Set([
17
+ "__proto__",
18
+ "constructor",
19
+ "prototype"
20
+ ]);
21
+ /**
22
+ * Category 1: Deprecated `miotx` (Multi-Input-Output UTXO-style `inputs[]`/`outputs[]`) & versioned trade/swap protocols.
23
+ * Replaced by composable `TransactionBlock` + versionless `fg:t:transfer`.
24
+ */
25
+ const DEPRECATED_MIOTX_AND_TRADE_TYPE_URLS = Object.freeze([
26
+ "fg:t:transfer_v2",
27
+ "fg:t:transfer_v3",
28
+ "fg:t:exchange",
29
+ "fg:t:exchange_v2",
30
+ "fg:t:setup_swap",
31
+ "fg:t:retrieve_swap",
32
+ "fg:t:revoke_swap"
33
+ ]);
34
+ /**
35
+ * Category 2: Deprecated versioned asset & factory protocols (`_v2`, `_v3`).
36
+ * Replaced by versionless `fg:t:acquire_asset`, `fg:t:mint_asset`, `fg:t:update_asset`, `fg:t:create_factory`, `fg:t:contract_nft`.
37
+ */
38
+ const DEPRECATED_VERSIONED_ASSET_TYPE_URLS = Object.freeze([
39
+ "fg:t:acquire_asset_v2",
40
+ "fg:t:acquire_asset_v3",
41
+ "fg:t:mint_asset_v2",
42
+ "fg:t:update_asset_v2",
43
+ "fg:t:create_factory_v2"
44
+ ]);
45
+ /**
46
+ * Category 3: Deprecated Rollup & legacy versioned token bridge write protocols.
47
+ * Replaced by Zero-Rollup-Block EIP-712 `fg:t:evm_bridge_settlement` (`OcapSimplifiedEvmBridgeNode`).
48
+ */
49
+ const DEPRECATED_ROLLUP_AND_BRIDGE_TYPE_URLS = Object.freeze([
50
+ "fg:t:create_rollup",
51
+ "fg:t:update_rollup",
52
+ "fg:t:join_rollup",
53
+ "fg:t:leave_rollup",
54
+ "fg:t:create_rollup_block",
55
+ "fg:t:claim_block_reward",
56
+ "fg:t:pause_rollup",
57
+ "fg:t:resume_rollup",
58
+ "fg:t:close_rollup",
59
+ "fg:t:migrate_rollup",
60
+ "fg:t:deposit_token",
61
+ "fg:t:deposit_token_v2",
62
+ "fg:t:withdraw_token",
63
+ "fg:t:withdraw_token_v2",
64
+ "fg:t:revoke_withdraw"
65
+ ]);
66
+ /**
67
+ * Complete list of all 27 deprecated legacy `V1/V2/V3`, `miotx`, and Rollup write protocols
68
+ * frozen into `READ_ONLY_LEGACY_ARCHIVE` mode after `sunsetActivationHeight`.
69
+ */
70
+ const DEPRECATED_LEGACY_PROTOCOL_TYPE_URLS = Object.freeze([
71
+ ...DEPRECATED_MIOTX_AND_TRADE_TYPE_URLS,
72
+ ...DEPRECATED_VERSIONED_ASSET_TYPE_URLS,
73
+ ...DEPRECATED_ROLLUP_AND_BRIDGE_TYPE_URLS
74
+ ]);
75
+ /**
76
+ * Subset of deprecated protocols that used the legacy `miotx` (Multi-Input-Output) UTXO-style array structure.
77
+ */
78
+ const DEPRECATED_MIOTX_PROTOCOL_TYPE_URLS = Object.freeze([
79
+ "fg:t:transfer_v3",
80
+ "fg:t:exchange_v2",
81
+ "fg:t:acquire_asset_v3"
82
+ ]);
83
+ /**
84
+ * Canonical Clean VNext Active Write Protocol Set (Domain-Agnostic, Versionless Composable Primitives).
85
+ * Issue #1251: L1 protocol identifiers strictly express orthogonal state-machine primitives
86
+ * without application-specific vocabulary (zero `nft`, `karma`, or `evm` in L1 protocol names).
87
+ */
88
+ const VNEXT_CANONICAL_WRITE_PROTOCOL_TYPE_URLS = Object.freeze([
89
+ "fg:t:transaction_block",
90
+ "fg:t:transfer",
91
+ "fg:t:create_asset",
92
+ "fg:t:mint_asset",
93
+ "fg:t:acquire_asset",
94
+ "fg:t:update_asset",
95
+ "fg:t:consume_asset",
96
+ "fg:t:execute_asset",
97
+ "fg:t:create_factory",
98
+ "fg:t:create_token",
99
+ "fg:t:create_token_factory",
100
+ "fg:t:update_token_factory",
101
+ "fg:t:mint_token",
102
+ "fg:t:burn_token",
103
+ "fg:t:settle_attestation",
104
+ "fg:t:declare",
105
+ "fg:t:account_migrate",
106
+ "fg:t:delegate",
107
+ "fg:t:revoke_delegate",
108
+ "fg:t:stake",
109
+ "fg:t:revoke_stake",
110
+ "fg:t:claim_stake",
111
+ "fg:t:slash_stake",
112
+ "fg:t:return_stake"
113
+ ]);
114
+ /**
115
+ * Issue #1251: Mapping of application-coupled protocol aliases to their domain-agnostic
116
+ * VNext L1 state-machine primitives.
117
+ */
118
+ const DOMAIN_COUPLED_PROTOCOL_ALIAS_MAP = Object.freeze({
119
+ "fg:t:contract_nft": "fg:t:execute_asset",
120
+ "fg:t:give_karma": "fg:t:mint_token",
121
+ "fg:t:claim_karma": "fg:t:settle_attestation",
122
+ "fg:t:evm_bridge_settlement": "fg:t:settle_attestation"
123
+ });
124
+ const LEGACY_REPLACEMENT_MAP = Object.freeze({
125
+ "fg:t:transfer_v2": {
126
+ legacyTypeUrl: "fg:t:transfer_v2",
127
+ category: "MIOTX_AND_VERSIONED_TRADE",
128
+ isMiotx: false,
129
+ vnextReplacementTypeUrl: "fg:t:transfer",
130
+ migrationGuidance: "Use versionless fg:t:transfer statement inside fg:t:transaction_block"
131
+ },
132
+ "fg:t:transfer_v3": {
133
+ legacyTypeUrl: "fg:t:transfer_v3",
134
+ category: "MIOTX_AND_VERSIONED_TRADE",
135
+ isMiotx: true,
136
+ vnextReplacementTypeUrl: "fg:t:transaction_block",
137
+ migrationGuidance: "miotx (inputs[]/outputs[]) is retired; compose multiple atomic fg:t:transfer statements inside fg:t:transaction_block"
138
+ },
139
+ "fg:t:exchange": {
140
+ legacyTypeUrl: "fg:t:exchange",
141
+ category: "MIOTX_AND_VERSIONED_TRADE",
142
+ isMiotx: false,
143
+ vnextReplacementTypeUrl: "fg:t:transaction_block",
144
+ migrationGuidance: "Legacy exchange is retired; compose atomic multi-party fg:t:transfer statements inside fg:t:transaction_block"
145
+ },
146
+ "fg:t:exchange_v2": {
147
+ legacyTypeUrl: "fg:t:exchange_v2",
148
+ category: "MIOTX_AND_VERSIONED_TRADE",
149
+ isMiotx: true,
150
+ vnextReplacementTypeUrl: "fg:t:transaction_block",
151
+ migrationGuidance: "miotx exchange_v2 is retired; compose atomic multi-party fg:t:transfer statements inside fg:t:transaction_block"
152
+ },
153
+ "fg:t:setup_swap": {
154
+ legacyTypeUrl: "fg:t:setup_swap",
155
+ category: "MIOTX_AND_VERSIONED_TRADE",
156
+ isMiotx: false,
157
+ vnextReplacementTypeUrl: "fg:t:transaction_block",
158
+ migrationGuidance: "Legacy HTLC swap is retired; use fg:t:transaction_block with TwoPhaseCommitCoordinator or fg:t:settle_attestation"
159
+ },
160
+ "fg:t:retrieve_swap": {
161
+ legacyTypeUrl: "fg:t:retrieve_swap",
162
+ category: "MIOTX_AND_VERSIONED_TRADE",
163
+ isMiotx: false,
164
+ vnextReplacementTypeUrl: "fg:t:transaction_block",
165
+ migrationGuidance: "Legacy HTLC swap is retired; use fg:t:transaction_block with TwoPhaseCommitCoordinator or fg:t:settle_attestation"
166
+ },
167
+ "fg:t:revoke_swap": {
168
+ legacyTypeUrl: "fg:t:revoke_swap",
169
+ category: "MIOTX_AND_VERSIONED_TRADE",
170
+ isMiotx: false,
171
+ vnextReplacementTypeUrl: "fg:t:transaction_block",
172
+ migrationGuidance: "Legacy HTLC swap is retired; use fg:t:transaction_block with TwoPhaseCommitCoordinator or fg:t:settle_attestation"
173
+ },
174
+ "fg:t:acquire_asset_v2": {
175
+ legacyTypeUrl: "fg:t:acquire_asset_v2",
176
+ category: "VERSIONED_ASSET_AND_FACTORY",
177
+ isMiotx: false,
178
+ vnextReplacementTypeUrl: "fg:t:acquire_asset",
179
+ migrationGuidance: "Use versionless fg:t:acquire_asset statement inside fg:t:transaction_block"
180
+ },
181
+ "fg:t:acquire_asset_v3": {
182
+ legacyTypeUrl: "fg:t:acquire_asset_v3",
183
+ category: "VERSIONED_ASSET_AND_FACTORY",
184
+ isMiotx: true,
185
+ vnextReplacementTypeUrl: "fg:t:acquire_asset",
186
+ migrationGuidance: "miotx acquire_asset_v3 is retired; use versionless fg:t:acquire_asset (chained with fg:t:transfer via $steps[i] inside fg:t:transaction_block)"
187
+ },
188
+ "fg:t:mint_asset_v2": {
189
+ legacyTypeUrl: "fg:t:mint_asset_v2",
190
+ category: "VERSIONED_ASSET_AND_FACTORY",
191
+ isMiotx: false,
192
+ vnextReplacementTypeUrl: "fg:t:mint_asset",
193
+ migrationGuidance: "Use versionless fg:t:mint_asset statement"
194
+ },
195
+ "fg:t:update_asset_v2": {
196
+ legacyTypeUrl: "fg:t:update_asset_v2",
197
+ category: "VERSIONED_ASSET_AND_FACTORY",
198
+ isMiotx: false,
199
+ vnextReplacementTypeUrl: "fg:t:update_asset",
200
+ migrationGuidance: "Use versionless fg:t:update_asset statement"
201
+ },
202
+ "fg:t:create_factory_v2": {
203
+ legacyTypeUrl: "fg:t:create_factory_v2",
204
+ category: "VERSIONED_ASSET_AND_FACTORY",
205
+ isMiotx: false,
206
+ vnextReplacementTypeUrl: "fg:t:create_factory",
207
+ migrationGuidance: "Use versionless fg:t:create_factory statement"
208
+ },
209
+ "fg:t:create_rollup": {
210
+ legacyTypeUrl: "fg:t:create_rollup",
211
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
212
+ isMiotx: false,
213
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
214
+ migrationGuidance: "Legacy Rollup is retired; use domain-agnostic attestation primitive fg:t:settle_attestation"
215
+ },
216
+ "fg:t:update_rollup": {
217
+ legacyTypeUrl: "fg:t:update_rollup",
218
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
219
+ isMiotx: false,
220
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
221
+ migrationGuidance: "Legacy Rollup is retired; use domain-agnostic attestation primitive fg:t:settle_attestation"
222
+ },
223
+ "fg:t:join_rollup": {
224
+ legacyTypeUrl: "fg:t:join_rollup",
225
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
226
+ isMiotx: false,
227
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
228
+ migrationGuidance: "Legacy Rollup is retired; use domain-agnostic attestation primitive fg:t:settle_attestation"
229
+ },
230
+ "fg:t:leave_rollup": {
231
+ legacyTypeUrl: "fg:t:leave_rollup",
232
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
233
+ isMiotx: false,
234
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
235
+ migrationGuidance: "Legacy Rollup is retired; use domain-agnostic attestation primitive fg:t:settle_attestation"
236
+ },
237
+ "fg:t:create_rollup_block": {
238
+ legacyTypeUrl: "fg:t:create_rollup_block",
239
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
240
+ isMiotx: false,
241
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
242
+ migrationGuidance: "RollupBlock is retired; use Zero-Rollup-Block EIP-712 DirectWithdrawVoucher via fg:t:settle_attestation"
243
+ },
244
+ "fg:t:claim_block_reward": {
245
+ legacyTypeUrl: "fg:t:claim_block_reward",
246
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
247
+ isMiotx: false,
248
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
249
+ migrationGuidance: "Rollup block rewards are retired; bridge operates with 0 bridge fee and validator quorum"
250
+ },
251
+ "fg:t:pause_rollup": {
252
+ legacyTypeUrl: "fg:t:pause_rollup",
253
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
254
+ isMiotx: false,
255
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
256
+ migrationGuidance: "Legacy Rollup is retired; use Guardian circuit breaker on OcapSimplifiedEvmBridgeNode"
257
+ },
258
+ "fg:t:resume_rollup": {
259
+ legacyTypeUrl: "fg:t:resume_rollup",
260
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
261
+ isMiotx: false,
262
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
263
+ migrationGuidance: "Legacy Rollup is retired; use Guardian circuit breaker on OcapSimplifiedEvmBridgeNode"
264
+ },
265
+ "fg:t:close_rollup": {
266
+ legacyTypeUrl: "fg:t:close_rollup",
267
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
268
+ isMiotx: false,
269
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
270
+ migrationGuidance: "Legacy Rollup is retired; use domain-agnostic attestation primitive fg:t:settle_attestation"
271
+ },
272
+ "fg:t:migrate_rollup": {
273
+ legacyTypeUrl: "fg:t:migrate_rollup",
274
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
275
+ isMiotx: false,
276
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
277
+ migrationGuidance: "Legacy Rollup is retired; use domain-agnostic attestation primitive fg:t:settle_attestation"
278
+ },
279
+ "fg:t:deposit_token": {
280
+ legacyTypeUrl: "fg:t:deposit_token",
281
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
282
+ isMiotx: false,
283
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
284
+ migrationGuidance: "Legacy deposit_token is retired; use fg:t:settle_attestation"
285
+ },
286
+ "fg:t:deposit_token_v2": {
287
+ legacyTypeUrl: "fg:t:deposit_token_v2",
288
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
289
+ isMiotx: false,
290
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
291
+ migrationGuidance: "Legacy deposit_token_v2 is retired; use fg:t:settle_attestation"
292
+ },
293
+ "fg:t:withdraw_token": {
294
+ legacyTypeUrl: "fg:t:withdraw_token",
295
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
296
+ isMiotx: false,
297
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
298
+ migrationGuidance: "Legacy withdraw_token is retired; use EIP-712 DirectWithdrawVoucher via fg:t:settle_attestation"
299
+ },
300
+ "fg:t:withdraw_token_v2": {
301
+ legacyTypeUrl: "fg:t:withdraw_token_v2",
302
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
303
+ isMiotx: false,
304
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
305
+ migrationGuidance: "Legacy withdraw_token_v2 is retired; use EIP-712 DirectWithdrawVoucher via fg:t:settle_attestation"
306
+ },
307
+ "fg:t:revoke_withdraw": {
308
+ legacyTypeUrl: "fg:t:revoke_withdraw",
309
+ category: "LEGACY_ROLLUP_AND_BRIDGE",
310
+ isMiotx: false,
311
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
312
+ migrationGuidance: "Legacy revoke_withdraw is retired; use Guardian timelock cancellation on fg:t:settle_attestation"
313
+ }
314
+ });
315
+ const DEPRECATED_LEGACY_SET = new Set(DEPRECATED_LEGACY_PROTOCOL_TYPE_URLS);
316
+ const DEPRECATED_MIOTX_SET = new Set(DEPRECATED_MIOTX_PROTOCOL_TYPE_URLS);
317
+ const VNEXT_CANONICAL_SET = new Set(VNEXT_CANONICAL_WRITE_PROTOCOL_TYPE_URLS);
318
+ function assertCleanString(value, fieldName, maxLen = 256) {
319
+ if (typeof value !== "string") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} must be a string`);
320
+ const trimmed = value.trim();
321
+ if (!trimmed || trimmed.length > maxLen) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} must be 1..${maxLen} non-empty chars`);
322
+ if (/[\u0000-\u001f\u007f]/.test(trimmed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: control characters forbidden in ${fieldName}`);
323
+ if (FORBIDDEN_OBJECT_KEYS.has(trimmed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: reserved identifier forbidden in ${fieldName}`);
324
+ return trimmed;
325
+ }
326
+ function assertNoProtoPollutionKeys(obj, label) {
327
+ if (Object.prototype.hasOwnProperty.call(obj, "__proto__") || Object.prototype.hasOwnProperty.call(obj, "constructor") || Object.prototype.hasOwnProperty.call(obj, "prototype")) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: prototype pollution keys rejected in ${label}`);
328
+ }
329
+ function parseStrictPositiveBigInt(value, fieldName) {
330
+ if (typeof value === "bigint") {
331
+ if (value <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} must be > 0`);
332
+ return value;
333
+ }
334
+ if (typeof value === "number") {
335
+ if (!Number.isSafeInteger(value) || value <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} must be a positive safe integer`);
336
+ return BigInt(value);
337
+ }
338
+ if (typeof value === "string") {
339
+ const trimmed = value.trim();
340
+ if (!CANONICAL_UINT256_DECIMAL_REGEX.test(trimmed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} must be a canonical non-negative decimal integer string`);
341
+ const parsed = BigInt(trimmed);
342
+ if (parsed <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} must be > 0`);
343
+ return parsed;
344
+ }
345
+ throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} must be a positive integer`);
346
+ }
347
+ function parseStrictNonNegativeBigInt(value, fieldName) {
348
+ if (value === void 0 || value === null || value === "") return 0n;
349
+ if (typeof value === "bigint") {
350
+ if (value < 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} cannot be negative`);
351
+ return value;
352
+ }
353
+ if (typeof value === "number") {
354
+ if (!Number.isSafeInteger(value) || value < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} must be a non-negative safe integer`);
355
+ return BigInt(value);
356
+ }
357
+ if (typeof value === "string") {
358
+ const trimmed = value.trim();
359
+ if (!CANONICAL_UINT256_DECIMAL_REGEX.test(trimmed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} must be a canonical non-negative decimal integer string`);
360
+ return BigInt(trimmed);
361
+ }
362
+ throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${fieldName} must be a non-negative integer`);
363
+ }
364
+ /**
365
+ * Normalizes any transaction or statement `typeUrl` / `type` (e.g. `fg:t:transfer_v3`,
366
+ * `transferV3`, `TransferV3Tx`, `type.googleapis.com/forge_abi.ExchangeV2Tx`, `acquire-asset-v3`)
367
+ * into its canonical `fg:t:<snake_case>` identifier so no alias can bypass sunset enforcement.
368
+ */
369
+ function normalizeProtocolTypeUrl(rawTypeUrl) {
370
+ if (typeof rawTypeUrl !== "string") return "";
371
+ const trimmed = rawTypeUrl.trim();
372
+ if (!trimmed) return "";
373
+ const segments = trimmed.split(/[:/.]/).filter(Boolean);
374
+ const lastSegment = segments[segments.length - 1] ?? "";
375
+ if (!lastSegment) return "";
376
+ const snakeCase = lastSegment.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s]+/g, "_").toLowerCase().replace(/_+/g, "_").replace(/^_+|_+$/g, "").replace(/(?:_?tx)+$/g, "").replace(/^_+|_+$/g, "").replace(/([a-z])_?v_?([0-9]+)$/g, "$1_v$2").replace(/^transfer_v([0-9]+)$/, "transfer_v$1").replace(/^exchange_v([0-9]+)$/, "exchange_v$1").replace(/^acquireasset_v([0-9]+)$/, "acquire_asset_v$1").replace(/^mintasset_v([0-9]+)$/, "mint_asset_v$1").replace(/^updateasset_v([0-9]+)$/, "update_asset_v$1").replace(/^createfactory_v([0-9]+)$/, "create_factory_v$1").replace(/_+/g, "_");
377
+ if (!snakeCase) return "";
378
+ if (snakeCase === "claim_reward" || snakeCase === "claim_block_reward_v1") return "fg:t:claim_block_reward";
379
+ const v1AliasMap = {
380
+ transfer_v1: "fg:t:transfer_v2",
381
+ exchange_v1: "fg:t:exchange",
382
+ setup_swap_v1: "fg:t:setup_swap",
383
+ retrieve_swap_v1: "fg:t:retrieve_swap",
384
+ revoke_swap_v1: "fg:t:revoke_swap",
385
+ acquire_asset_v1: "fg:t:acquire_asset_v2",
386
+ mint_asset_v1: "fg:t:mint_asset_v2",
387
+ update_asset_v1: "fg:t:update_asset_v2",
388
+ create_factory_v1: "fg:t:create_factory_v2",
389
+ deposit_token_v1: "fg:t:deposit_token",
390
+ withdraw_token_v1: "fg:t:withdraw_token",
391
+ revoke_withdraw_v1: "fg:t:revoke_withdraw",
392
+ create_rollup_v1: "fg:t:create_rollup",
393
+ update_rollup_v1: "fg:t:update_rollup",
394
+ join_rollup_v1: "fg:t:join_rollup",
395
+ leave_rollup_v1: "fg:t:leave_rollup",
396
+ create_rollup_block_v1: "fg:t:create_rollup_block",
397
+ pause_rollup_v1: "fg:t:pause_rollup",
398
+ resume_rollup_v1: "fg:t:resume_rollup",
399
+ close_rollup_v1: "fg:t:close_rollup",
400
+ migrate_rollup_v1: "fg:t:migrate_rollup"
401
+ };
402
+ if (v1AliasMap[snakeCase]) return v1AliasMap[snakeCase];
403
+ return `fg:t:${snakeCase}`;
404
+ }
405
+ /**
406
+ * Returns true if `typeUrl` is one of the 27 deprecated legacy `V1/V2/V3`, `miotx`, or Rollup write protocols.
407
+ */
408
+ function isDeprecatedLegacyWriteProtocol(typeUrl) {
409
+ const normalized = normalizeProtocolTypeUrl(typeUrl);
410
+ return DEPRECATED_LEGACY_SET.has(normalized);
411
+ }
412
+ /**
413
+ * Returns true if `typeUrl` is a deprecated `miotx` (Multi-Input-Output) protocol (`transfer_v3`, `exchange_v2`, `acquire_asset_v3`).
414
+ */
415
+ function isMiotxLegacyProtocol(typeUrl) {
416
+ const normalized = normalizeProtocolTypeUrl(typeUrl);
417
+ return DEPRECATED_MIOTX_SET.has(normalized);
418
+ }
419
+ /**
420
+ * Returns true if `typeUrl` is in the clean VNext canonical active write protocol set.
421
+ */
422
+ function isVNextCanonicalWriteProtocol(typeUrl) {
423
+ const normalized = normalizeProtocolTypeUrl(typeUrl);
424
+ return VNEXT_CANONICAL_SET.has(normalized);
425
+ }
426
+ /**
427
+ * Issue #1251: Returns true if `typeUrl` is an application-domain-coupled protocol alias
428
+ * (`contract_nft`, `give_karma`, `claim_karma`, `evm_bridge_settlement`).
429
+ */
430
+ function isDomainCoupledProtocolAlias(typeUrl) {
431
+ const normalized = normalizeProtocolTypeUrl(typeUrl);
432
+ return Object.prototype.hasOwnProperty.call(DOMAIN_COUPLED_PROTOCOL_ALIAS_MAP, normalized);
433
+ }
434
+ /**
435
+ * Issue #1251: Resolves an application-coupled protocol alias (`contract_nft`, `give_karma`,
436
+ * `claim_karma`, `evm_bridge_settlement`) or canonical VNext protocol to its domain-agnostic
437
+ * VNext L1 primitive (`fg:t:execute_asset`, `fg:t:mint_token`, `fg:t:settle_attestation`, etc.).
438
+ */
439
+ function resolveDomainAgnosticVNextProtocol(typeUrl) {
440
+ const normalized = normalizeProtocolTypeUrl(typeUrl);
441
+ if (Object.prototype.hasOwnProperty.call(DOMAIN_COUPLED_PROTOCOL_ALIAS_MAP, normalized)) return DOMAIN_COUPLED_PROTOCOL_ALIAS_MAP[normalized];
442
+ if (VNEXT_CANONICAL_SET.has(normalized)) return normalized;
443
+ return null;
444
+ }
445
+ /**
446
+ * Returns the structured replacement specification and migration guidance for a deprecated legacy protocol,
447
+ * or `null` if the protocol is not in the deprecated legacy list.
448
+ */
449
+ function getLegacyProtocolReplacementSpec(typeUrl) {
450
+ return LEGACY_REPLACEMENT_MAP[normalizeProtocolTypeUrl(typeUrl)] ?? null;
451
+ }
452
+ /**
453
+ * Active Write Pipeline Sunset Gate (`assertLegacyProtocolNotSunset`):
454
+ * - When `readOnlyArchiveMode === true` or `currentBlockHeight < sunsetActivationHeight`, allows historical read/replay.
455
+ * - When `currentBlockHeight >= sunsetActivationHeight`, fails closed (`FORBIDDEN_LEGACY_PROTOCOL_SUNSET`) on all
456
+ * 27 deprecated `V1/V2/V3`, `miotx`, and Rollup write protocols with actionable VNext migration guidance.
457
+ */
458
+ function assertLegacyProtocolNotSunset(params) {
459
+ if (!params || typeof params !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolSunset: params must be an object");
460
+ const rawTypeUrl = assertCleanString(params.typeUrl, "typeUrl");
461
+ if (!Number.isSafeInteger(params.currentBlockHeight) || params.currentBlockHeight < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolSunset: currentBlockHeight must be a non-negative safe integer");
462
+ const activationHeight = params.sunsetActivationHeight ?? DEFAULT_LEGACY_PROTOCOL_SUNSET_HEIGHT;
463
+ if (!Number.isSafeInteger(activationHeight) || activationHeight < 1) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolSunset: sunsetActivationHeight must be a positive safe integer (>= 1)");
464
+ if (params.readOnlyArchiveMode === true) return;
465
+ const spec = getLegacyProtocolReplacementSpec(rawTypeUrl);
466
+ if (spec && params.currentBlockHeight >= activationHeight) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: legacy write protocol ${spec.legacyTypeUrl} (${spec.category}${spec.isMiotx ? ", miotx" : ""}) is sunset and read-only at block height ${params.currentBlockHeight} (>= activation height ${activationHeight}). Replacement: ${spec.vnextReplacementTypeUrl} (${spec.migrationGuidance})`);
467
+ }
468
+ function validateVNextStatementOrTemplate(stmt, label, currentBlockHeight, sunsetActivationHeight, requireStrictWhitelist, depth = 0) {
469
+ if (depth > 8) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: ${label} exceeds maximum nested statementTemplates depth`);
470
+ if (!stmt || typeof stmt !== "object" || Array.isArray(stmt)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${label} must be an object`);
471
+ const hasTypeUrl = stmt.typeUrl !== void 0 && stmt.typeUrl !== null && String(stmt.typeUrl).trim() !== "";
472
+ const hasType = stmt.type !== void 0 && stmt.type !== null && String(stmt.type).trim() !== "";
473
+ if (!hasTypeUrl && !hasType) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${label} is missing type or typeUrl`);
474
+ if (hasTypeUrl) assertLegacyProtocolNotSunset({
475
+ typeUrl: String(stmt.typeUrl),
476
+ currentBlockHeight,
477
+ sunsetActivationHeight
478
+ });
479
+ if (hasType) assertLegacyProtocolNotSunset({
480
+ typeUrl: String(stmt.type),
481
+ currentBlockHeight,
482
+ sunsetActivationHeight
483
+ });
484
+ const canonicalFromTypeUrl = hasTypeUrl ? normalizeProtocolTypeUrl(String(stmt.typeUrl)) : "";
485
+ const canonicalFromType = hasType ? normalizeProtocolTypeUrl(String(stmt.type)) : "";
486
+ if (hasTypeUrl && hasType && canonicalFromTypeUrl !== canonicalFromType) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: ${label} has conflicting typeUrl (${canonicalFromTypeUrl}) and type (${canonicalFromType})`);
487
+ const canonicalTypeUrl = canonicalFromTypeUrl || canonicalFromType;
488
+ if (!canonicalTypeUrl || canonicalTypeUrl === "fg:t:") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${label} resolved to empty protocol typeUrl`);
489
+ if (canonicalTypeUrl === "fg:t:transaction_block") throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: ${label} cannot recursively nest fg:t:transaction_block`);
490
+ if (depth >= 1 && canonicalTypeUrl === "fg:t:execute_asset") throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: ${label} cannot recursively nest fg:t:execute_asset inside statementTemplates (MAX_EXECUTE_ASSET_DEPTH = 1)`);
491
+ if (requireStrictWhitelist && !isVNextCanonicalWriteProtocol(canonicalTypeUrl)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: ${label} protocol ${canonicalTypeUrl} is not in VNEXT_CANONICAL_WRITE_PROTOCOL_TYPE_URLS`);
492
+ const itx = stmt.itx && typeof stmt.itx === "object" ? stmt.itx : null;
493
+ if (itx) {
494
+ const candidateTemplateArrays = [
495
+ {
496
+ path: `${label}.itx.statementTemplates`,
497
+ templates: itx.statementTemplates
498
+ },
499
+ {
500
+ path: `${label}.itx.data.value.statementTemplates`,
501
+ templates: itx.data?.value?.statementTemplates
502
+ },
503
+ {
504
+ path: `${label}.itx.contractAsset.data.value.statementTemplates`,
505
+ templates: itx.contractAsset?.data?.value?.statementTemplates
506
+ }
507
+ ];
508
+ for (const candidate of candidateTemplateArrays) if (candidate.templates !== void 0 && candidate.templates !== null) {
509
+ if (!Array.isArray(candidate.templates)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${candidate.path} must be an array when present`);
510
+ for (let tIdx = 0; tIdx < candidate.templates.length; tIdx++) validateVNextStatementOrTemplate(candidate.templates[tIdx], `${candidate.path}[${tIdx}]`, currentBlockHeight, sunsetActivationHeight, requireStrictWhitelist, depth + 1);
511
+ }
512
+ }
513
+ }
514
+ /**
515
+ * Deeply validates that a `TransactionBlockInput` contains ONLY clean VNext canonical write statements
516
+ * and does NOT smuggle any deprecated `V1/V2/V3`, `miotx`, or Rollup protocol inside `statements[]`
517
+ * or nested `ContractNFT` `statementTemplates`.
518
+ */
519
+ function assertTransactionBlockVNextPure(block, options) {
520
+ if (!block || typeof block !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolSunset: block must be an object");
521
+ if (!Array.isArray(block.statements) || block.statements.length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolSunset: TransactionBlock must contain at least one statement");
522
+ const currentBlockHeight = options?.currentBlockHeight ?? DEFAULT_LEGACY_PROTOCOL_SUNSET_HEIGHT;
523
+ const sunsetActivationHeight = options?.sunsetActivationHeight ?? DEFAULT_LEGACY_PROTOCOL_SUNSET_HEIGHT;
524
+ const requireStrictWhitelist = options?.requireStrictCanonicalWhitelist ?? true;
525
+ for (let i = 0; i < block.statements.length; i++) validateVNextStatementOrTemplate(block.statements[i], `statement[${i}]`, currentBlockHeight, sunsetActivationHeight, requireStrictWhitelist, 0);
526
+ }
527
+ function parseTokenList(rawTokens, primaryTokenAddress, primaryValue, label = "tokens") {
528
+ const entries = /* @__PURE__ */ new Map();
529
+ if (primaryValue !== void 0 && primaryValue !== null && primaryValue !== "" && primaryValue !== "0") {
530
+ const amount = parseStrictNonNegativeBigInt(primaryValue, `${label}.primaryValue`);
531
+ if (amount > 0n) {
532
+ const tokenAddr = assertCleanString(primaryTokenAddress || "z35n6UoHSi9s4236123nativeAbt", "primaryTokenAddress");
533
+ entries.set(tokenAddr, (entries.get(tokenAddr) ?? 0n) + amount);
534
+ }
535
+ }
536
+ if (rawTokens !== void 0 && rawTokens !== null) {
537
+ if (!Array.isArray(rawTokens) || rawTokens.length > MAX_LEGACY_MIOTX_TOKENS_PER_ENTRY) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${label} must be an array of at most ${MAX_LEGACY_MIOTX_TOKENS_PER_ENTRY} items`);
538
+ for (let i = 0; i < rawTokens.length; i++) {
539
+ const item = rawTokens[i];
540
+ if (!item || typeof item !== "object" || Array.isArray(item)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${label}[${i}] must be an object`);
541
+ assertNoProtoPollutionKeys(item, `${label}[${i}]`);
542
+ const address = assertCleanString(item.address, `${label}[${i}].address`);
543
+ const value = parseStrictPositiveBigInt(item.value, `${label}[${i}].value`);
544
+ entries.set(address, (entries.get(address) ?? 0n) + value);
545
+ }
546
+ }
547
+ return Object.freeze(Array.from(entries.entries()).map(([address, value]) => Object.freeze({
548
+ address,
549
+ value
550
+ })));
551
+ }
552
+ function parseAssetList(rawAssets, label = "assets") {
553
+ if (rawAssets === void 0 || rawAssets === null) return Object.freeze([]);
554
+ if (!Array.isArray(rawAssets) || rawAssets.length > MAX_LEGACY_MIOTX_ASSETS_PER_ENTRY) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${label} must be an array of at most ${MAX_LEGACY_MIOTX_ASSETS_PER_ENTRY} items`);
555
+ const seen = /* @__PURE__ */ new Set();
556
+ const result = [];
557
+ for (let i = 0; i < rawAssets.length; i++) {
558
+ const assetDid = assertCleanString(rawAssets[i], `${label}[${i}]`);
559
+ if (seen.has(assetDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: duplicate asset ${assetDid} in ${label}`);
560
+ seen.add(assetDid);
561
+ result.push(assetDid);
562
+ }
563
+ return Object.freeze(result);
564
+ }
565
+ function parseMiotxParticipantList(rawList, label) {
566
+ if (!Array.isArray(rawList) || rawList.length === 0 || rawList.length > MAX_LEGACY_MIOTX_PARTICIPANTS) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${label} must be a non-empty array of 1..${MAX_LEGACY_MIOTX_PARTICIPANTS} entries`);
567
+ const list = [];
568
+ for (let i = 0; i < rawList.length; i++) {
569
+ const entry = rawList[i];
570
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${label}[${i}] must be an object`);
571
+ assertNoProtoPollutionKeys(entry, `${label}[${i}]`);
572
+ const owner = assertCleanString(entry.owner, `${label}[${i}].owner`);
573
+ const tokens = parseTokenList(entry.tokens ?? entry.tokensList, void 0, void 0, `${label}[${i}].tokens`);
574
+ const assets = parseAssetList(entry.assets ?? entry.assetsList, `${label}[${i}].assets`);
575
+ if (tokens.length === 0 && assets.length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: ${label}[${i}] (${owner}) must contain at least one token or asset`);
576
+ list.push(Object.freeze({
577
+ owner,
578
+ tokens,
579
+ assets
580
+ }));
581
+ }
582
+ return Object.freeze(list);
583
+ }
584
+ /**
585
+ * Strictly parses historical `V1/V2/V3`, `miotx` (`transfer_v3`, `exchange_v2`, `acquire_asset_v3`),
586
+ * and Rollup records into a deeply frozen (`Object.freeze`) read-only archive summary (`mode: 'READ_ONLY_LEGACY_ARCHIVE'`).
587
+ * Enforces strict zero-sum token and asset conservation for historical `transfer_v3` `miotx` records.
588
+ */
589
+ function parseLegacyTxReadOnlyArchiveRecord(rawRecord) {
590
+ if (!rawRecord || typeof rawRecord !== "object" || Array.isArray(rawRecord)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolSunset: rawRecord must be a plain object");
591
+ assertNoProtoPollutionKeys(rawRecord, "rawRecord");
592
+ const rawKind = String(rawRecord.recordKind ?? rawRecord.typeUrl ?? rawRecord.type ?? "").trim();
593
+ if (!rawKind) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolSunset: recordKind or typeUrl is required");
594
+ const canonicalTypeUrl = normalizeProtocolTypeUrl(rawKind);
595
+ const resolvedRollupKind = rawKind === "RollupState" || rawKind === "RollupBlock" ? rawKind : {
596
+ "fg:t:rollup_state": "RollupState",
597
+ "fg:t:rollup_block": "RollupBlock",
598
+ "fg:t:create_rollup_block": "RollupBlock",
599
+ "fg:t:deposit_token": "deposit_token_v2",
600
+ "fg:t:deposit_token_v1": "deposit_token_v2",
601
+ "fg:t:deposit_token_v2": "deposit_token_v2",
602
+ "fg:t:withdraw_token": "withdraw_token_v2",
603
+ "fg:t:withdraw_token_v1": "withdraw_token_v2",
604
+ "fg:t:withdraw_token_v2": "withdraw_token_v2"
605
+ }[canonicalTypeUrl];
606
+ if (resolvedRollupKind) {
607
+ const nestedItx = rawRecord.itx && typeof rawRecord.itx === "object" && !Array.isArray(rawRecord.itx) ? rawRecord.itx : {};
608
+ assertNoProtoPollutionKeys(nestedItx, "itx");
609
+ const rollupSummary = require_evm_simplified_bridge.parseLegacyRollupReadOnlyRecord({
610
+ ...nestedItx,
611
+ ...rawRecord,
612
+ recordKind: resolvedRollupKind
613
+ });
614
+ const canonicalLegacyTypeUrl = rollupSummary.recordKind === "RollupState" || rollupSummary.recordKind === "RollupBlock" ? rollupSummary.recordKind : `fg:t:${rollupSummary.recordKind}`;
615
+ return Object.freeze({
616
+ recordKind: rollupSummary.recordKind,
617
+ canonicalLegacyTypeUrl,
618
+ mode: "READ_ONLY_LEGACY_ARCHIVE",
619
+ isMiotx: false,
620
+ vnextReplacementTypeUrl: "fg:t:settle_attestation",
621
+ fromDid: rollupSummary.fromDid ?? rollupSummary.proposerDid,
622
+ toDid: rollupSummary.recipientAddress,
623
+ rollupArchive: rollupSummary
624
+ });
625
+ }
626
+ const itx = rawRecord.itx && typeof rawRecord.itx === "object" && !Array.isArray(rawRecord.itx) ? rawRecord.itx : rawRecord;
627
+ assertNoProtoPollutionKeys(itx, "itx");
628
+ const txHash = rawRecord.txHash !== void 0 ? assertCleanString(rawRecord.txHash, "txHash") : void 0;
629
+ if (canonicalTypeUrl === "fg:t:transfer_v2" || canonicalTypeUrl === "fg:t:transfer_v1" || canonicalTypeUrl === "fg:t:transfer") {
630
+ const fromDid = assertCleanString(rawRecord.from ?? itx.from, "from");
631
+ const toDid = assertCleanString(itx.to, "itx.to");
632
+ if (fromDid === toDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, "LegacyProtocolSunset: transfer_v2 sender and receiver must be distinct DIDs");
633
+ const primaryTokenAddr = typeof rawRecord.primaryTokenAddress === "string" ? rawRecord.primaryTokenAddress : "z35n6UoHSi9s4236123nativeAbt";
634
+ const tokens = parseTokenList(itx.tokens ?? itx.tokensList, primaryTokenAddr, itx.value, "itx.tokens");
635
+ const assets = parseAssetList(itx.assets ?? itx.assetsList, "itx.assets");
636
+ if (tokens.length === 0 && assets.length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolSunset: legacy transfer_v2 record must transfer at least one token or asset");
637
+ const participantInput = Object.freeze({
638
+ owner: fromDid,
639
+ tokens,
640
+ assets
641
+ });
642
+ const participantOutput = Object.freeze({
643
+ owner: toDid,
644
+ tokens,
645
+ assets
646
+ });
647
+ const volumeMap = {};
648
+ for (const t of tokens) volumeMap[t.address] = t.value.toString();
649
+ return Object.freeze({
650
+ recordKind: "transfer_v2",
651
+ canonicalLegacyTypeUrl: "fg:t:transfer_v2",
652
+ mode: "READ_ONLY_LEGACY_ARCHIVE",
653
+ isMiotx: false,
654
+ vnextReplacementTypeUrl: "fg:t:transfer",
655
+ txHash,
656
+ fromDid,
657
+ toDid,
658
+ inputs: Object.freeze([participantInput]),
659
+ outputs: Object.freeze([participantOutput]),
660
+ totalTokenVolumeByAddress: Object.freeze(volumeMap),
661
+ transferredAssets: assets
662
+ });
663
+ }
664
+ if (canonicalTypeUrl === "fg:t:transfer_v3") {
665
+ const inputs = parseMiotxParticipantList(itx.inputs ?? itx.inputsList, "itx.inputs");
666
+ const outputs = parseMiotxParticipantList(itx.outputs ?? itx.outputsList, "itx.outputs");
667
+ const inputTokenSums = /* @__PURE__ */ new Map();
668
+ const outputTokenSums = /* @__PURE__ */ new Map();
669
+ const inputAssets = /* @__PURE__ */ new Map();
670
+ const outputAssets = /* @__PURE__ */ new Map();
671
+ for (const inp of inputs) {
672
+ for (const t of inp.tokens) inputTokenSums.set(t.address, (inputTokenSums.get(t.address) ?? 0n) + t.value);
673
+ for (const a of inp.assets) {
674
+ if (inputAssets.has(a)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: duplicate asset ${a} across transfer_v3 inputs`);
675
+ inputAssets.set(a, inp.owner);
676
+ }
677
+ }
678
+ for (const out of outputs) {
679
+ for (const t of out.tokens) outputTokenSums.set(t.address, (outputTokenSums.get(t.address) ?? 0n) + t.value);
680
+ for (const a of out.assets) {
681
+ if (outputAssets.has(a)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: duplicate asset ${a} across transfer_v3 outputs`);
682
+ outputAssets.set(a, out.owner);
683
+ }
684
+ }
685
+ if (inputTokenSums.size !== outputTokenSums.size) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, "LegacyProtocolSunset: transfer_v3 miotx token set mismatch between inputs and outputs");
686
+ const volumeMap = {};
687
+ for (const [tokenAddr, inSum] of inputTokenSums.entries()) {
688
+ const outSum = outputTokenSums.get(tokenAddr);
689
+ if (outSum !== inSum) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: transfer_v3 miotx zero-sum violation for token ${tokenAddr} (inputs=${inSum}, outputs=${String(outSum)})`);
690
+ volumeMap[tokenAddr] = inSum.toString();
691
+ }
692
+ if (inputAssets.size !== outputAssets.size) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, "LegacyProtocolSunset: transfer_v3 miotx asset count mismatch between inputs and outputs");
693
+ for (const [assetDid, inOwner] of inputAssets.entries()) {
694
+ const outOwner = outputAssets.get(assetDid);
695
+ if (!outOwner) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: transfer_v3 miotx asset ${assetDid} missing in outputs`);
696
+ if (inOwner === outOwner) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: transfer_v3 miotx asset ${assetDid} cannot be self-transferred (${inOwner} -> ${outOwner})`);
697
+ }
698
+ const ownerTokenIn = /* @__PURE__ */ new Map();
699
+ const ownerTokenOut = /* @__PURE__ */ new Map();
700
+ for (const inp of inputs) for (const t of inp.tokens) {
701
+ const key = `${inp.owner}::${t.address}`;
702
+ ownerTokenIn.set(key, (ownerTokenIn.get(key) ?? 0n) + t.value);
703
+ }
704
+ for (const out of outputs) for (const t of out.tokens) {
705
+ const key = `${out.owner}::${t.address}`;
706
+ ownerTokenOut.set(key, (ownerTokenOut.get(key) ?? 0n) + t.value);
707
+ }
708
+ let hasNetCrossOwnerTransfer = inputAssets.size > 0;
709
+ for (const [key, inAmt] of ownerTokenIn.entries()) if (inAmt !== (ownerTokenOut.get(key) ?? 0n)) {
710
+ hasNetCrossOwnerTransfer = true;
711
+ break;
712
+ }
713
+ if (!hasNetCrossOwnerTransfer) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, "LegacyProtocolSunset: transfer_v3 miotx has zero net transfer across distinct owners (pure self-transfer)");
714
+ return Object.freeze({
715
+ recordKind: "transfer_v3",
716
+ canonicalLegacyTypeUrl: "fg:t:transfer_v3",
717
+ mode: "READ_ONLY_LEGACY_ARCHIVE",
718
+ isMiotx: true,
719
+ vnextReplacementTypeUrl: "fg:t:transaction_block",
720
+ txHash,
721
+ fromDid: inputs[0].owner,
722
+ toDid: outputs[0].owner,
723
+ inputs,
724
+ outputs,
725
+ totalTokenVolumeByAddress: Object.freeze(volumeMap),
726
+ transferredAssets: Object.freeze(Array.from(inputAssets.keys()))
727
+ });
728
+ }
729
+ if (canonicalTypeUrl === "fg:t:exchange_v2" || canonicalTypeUrl === "fg:t:exchange_v1" || canonicalTypeUrl === "fg:t:exchange") {
730
+ const senderDid = assertCleanString(rawRecord.from ?? itx.from, "from");
731
+ const receiverDid = assertCleanString(itx.to, "itx.to");
732
+ if (senderDid === receiverDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, "LegacyProtocolSunset: exchange_v2 sender and receiver must be distinct DIDs");
733
+ const senderBundle = itx.sender && typeof itx.sender === "object" && !Array.isArray(itx.sender) ? itx.sender : {};
734
+ const receiverBundle = itx.receiver && typeof itx.receiver === "object" && !Array.isArray(itx.receiver) ? itx.receiver : {};
735
+ assertNoProtoPollutionKeys(senderBundle, "itx.sender");
736
+ assertNoProtoPollutionKeys(receiverBundle, "itx.receiver");
737
+ const primaryTokenAddr = typeof rawRecord.primaryTokenAddress === "string" ? rawRecord.primaryTokenAddress : "z35n6UoHSi9s4236123nativeAbt";
738
+ const senderTokens = parseTokenList(senderBundle.tokens ?? senderBundle.tokensList, primaryTokenAddr, senderBundle.value, "itx.sender.tokens");
739
+ const senderAssets = parseAssetList(senderBundle.assets ?? senderBundle.assetsList, "itx.sender.assets");
740
+ const receiverTokens = parseTokenList(receiverBundle.tokens ?? receiverBundle.tokensList, primaryTokenAddr, receiverBundle.value, "itx.receiver.tokens");
741
+ const receiverAssets = parseAssetList(receiverBundle.assets ?? receiverBundle.assetsList, "itx.receiver.assets");
742
+ const senderAssetSet = new Set(senderAssets);
743
+ for (const rAsset of receiverAssets) if (senderAssetSet.has(rAsset)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: overlapping asset ${rAsset} between exchange_v2 sender and receiver`);
744
+ if (senderTokens.length === 0 && senderAssets.length === 0 || receiverTokens.length === 0 && receiverAssets.length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolSunset: exchange_v2 requires both sender and receiver to provide at least one token or asset");
745
+ const inputs = Object.freeze([Object.freeze({
746
+ owner: senderDid,
747
+ tokens: senderTokens,
748
+ assets: senderAssets
749
+ }), Object.freeze({
750
+ owner: receiverDid,
751
+ tokens: receiverTokens,
752
+ assets: receiverAssets
753
+ })]);
754
+ const outputs = Object.freeze([Object.freeze({
755
+ owner: receiverDid,
756
+ tokens: senderTokens,
757
+ assets: senderAssets
758
+ }), Object.freeze({
759
+ owner: senderDid,
760
+ tokens: receiverTokens,
761
+ assets: receiverAssets
762
+ })]);
763
+ const volumeTotals = /* @__PURE__ */ new Map();
764
+ for (const t of [...senderTokens, ...receiverTokens]) volumeTotals.set(t.address, (volumeTotals.get(t.address) ?? 0n) + t.value);
765
+ const volumeMap = {};
766
+ for (const [addr, total] of volumeTotals.entries()) volumeMap[addr] = total.toString();
767
+ return Object.freeze({
768
+ recordKind: "exchange_v2",
769
+ canonicalLegacyTypeUrl: "fg:t:exchange_v2",
770
+ mode: "READ_ONLY_LEGACY_ARCHIVE",
771
+ isMiotx: true,
772
+ vnextReplacementTypeUrl: "fg:t:transaction_block",
773
+ txHash,
774
+ fromDid: senderDid,
775
+ toDid: receiverDid,
776
+ inputs,
777
+ outputs,
778
+ totalTokenVolumeByAddress: Object.freeze(volumeMap),
779
+ transferredAssets: Object.freeze([...senderAssets, ...receiverAssets])
780
+ });
781
+ }
782
+ if (canonicalTypeUrl === "fg:t:acquire_asset_v3" || canonicalTypeUrl === "fg:t:acquire_asset_v2" || canonicalTypeUrl === "fg:t:acquire_asset_v1" || canonicalTypeUrl === "fg:t:acquire_asset") {
783
+ const fromDid = assertCleanString(rawRecord.from ?? itx.from, "from");
784
+ const factoryAddress = assertCleanString(itx.factory, "itx.factory");
785
+ const rawInputs = itx.inputs ?? itx.inputsList;
786
+ const inputs = Array.isArray(rawInputs) && rawInputs.length > 0 ? parseMiotxParticipantList(rawInputs, "itx.inputs") : Object.freeze([]);
787
+ const rawSpecs = itx.specs ?? itx.specsList;
788
+ const specsCount = Array.isArray(rawSpecs) && rawSpecs.length > 0 ? rawSpecs.length : 1;
789
+ if (specsCount > MAX_LEGACY_MIOTX_ASSETS_PER_ENTRY) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolSunset: acquire_asset specs count exceeds limit");
790
+ const volumeTotals = /* @__PURE__ */ new Map();
791
+ const consumedAssets = [];
792
+ const seenConsumedAssets = /* @__PURE__ */ new Set();
793
+ for (const inp of inputs) {
794
+ for (const t of inp.tokens) volumeTotals.set(t.address, (volumeTotals.get(t.address) ?? 0n) + t.value);
795
+ for (const a of inp.assets) {
796
+ if (seenConsumedAssets.has(a)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: duplicate asset ${a} across acquire_asset_v3 inputs`);
797
+ seenConsumedAssets.add(a);
798
+ consumedAssets.push(a);
799
+ }
800
+ }
801
+ const volumeMap = {};
802
+ for (const [addr, total] of volumeTotals.entries()) volumeMap[addr] = total.toString();
803
+ const isV3 = canonicalTypeUrl === "fg:t:acquire_asset_v3";
804
+ return Object.freeze({
805
+ recordKind: isV3 ? "acquire_asset_v3" : "acquire_asset_v2",
806
+ canonicalLegacyTypeUrl: isV3 ? "fg:t:acquire_asset_v3" : "fg:t:acquire_asset_v2",
807
+ mode: "READ_ONLY_LEGACY_ARCHIVE",
808
+ isMiotx: isV3,
809
+ vnextReplacementTypeUrl: "fg:t:acquire_asset",
810
+ txHash,
811
+ fromDid,
812
+ toDid: typeof itx.to === "string" && itx.to.trim() ? assertCleanString(itx.to, "itx.to") : fromDid,
813
+ factoryAddress,
814
+ inputs,
815
+ totalTokenVolumeByAddress: Object.freeze(volumeMap),
816
+ transferredAssets: Object.freeze(consumedAssets),
817
+ acquiredAssetSpecsCount: specsCount
818
+ });
819
+ }
820
+ if (canonicalTypeUrl === "fg:t:mint_asset_v2" || canonicalTypeUrl === "fg:t:mint_asset_v1" || canonicalTypeUrl === "fg:t:mint_asset") {
821
+ const fromDid = assertCleanString(rawRecord.from ?? itx.from, "from");
822
+ const assetAddress = typeof itx.address === "string" && itx.address.trim() ? assertCleanString(itx.address, "itx.address") : void 0;
823
+ const toDid = typeof itx.owner === "string" && itx.owner.trim() ? assertCleanString(itx.owner, "itx.owner") : typeof itx.to === "string" && itx.to.trim() ? assertCleanString(itx.to, "itx.to") : fromDid;
824
+ const factoryAddress = typeof itx.factory === "string" && itx.factory.trim() ? assertCleanString(itx.factory, "itx.factory") : void 0;
825
+ return Object.freeze({
826
+ recordKind: "mint_asset_v2",
827
+ canonicalLegacyTypeUrl: "fg:t:mint_asset_v2",
828
+ mode: "READ_ONLY_LEGACY_ARCHIVE",
829
+ isMiotx: false,
830
+ vnextReplacementTypeUrl: "fg:t:mint_asset",
831
+ txHash,
832
+ fromDid,
833
+ toDid,
834
+ factoryAddress,
835
+ assetAddress
836
+ });
837
+ }
838
+ if (canonicalTypeUrl === "fg:t:update_asset_v2" || canonicalTypeUrl === "fg:t:update_asset_v1" || canonicalTypeUrl === "fg:t:update_asset") {
839
+ const fromDid = assertCleanString(rawRecord.from ?? itx.from, "from");
840
+ const assetAddress = assertCleanString(itx.address, "itx.address");
841
+ return Object.freeze({
842
+ recordKind: "update_asset_v2",
843
+ canonicalLegacyTypeUrl: "fg:t:update_asset_v2",
844
+ mode: "READ_ONLY_LEGACY_ARCHIVE",
845
+ isMiotx: false,
846
+ vnextReplacementTypeUrl: "fg:t:update_asset",
847
+ txHash,
848
+ fromDid,
849
+ assetAddress
850
+ });
851
+ }
852
+ if (canonicalTypeUrl === "fg:t:create_factory_v2" || canonicalTypeUrl === "fg:t:create_factory_v1" || canonicalTypeUrl === "fg:t:create_factory") {
853
+ const fromDid = assertCleanString(rawRecord.from ?? itx.from, "from");
854
+ const factoryAddress = typeof itx.address === "string" && itx.address.trim() ? assertCleanString(itx.address, "itx.address") : typeof itx.factory === "string" && itx.factory.trim() ? assertCleanString(itx.factory, "itx.factory") : void 0;
855
+ return Object.freeze({
856
+ recordKind: "create_factory_v2",
857
+ canonicalLegacyTypeUrl: "fg:t:create_factory_v2",
858
+ mode: "READ_ONLY_LEGACY_ARCHIVE",
859
+ isMiotx: false,
860
+ vnextReplacementTypeUrl: "fg:t:create_factory",
861
+ txHash,
862
+ fromDid,
863
+ factoryAddress
864
+ });
865
+ }
866
+ throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolSunset: unsupported legacy archive record kind (${rawKind})`);
867
+ }
868
+ /**
869
+ * Deterministically compiles any legacy `transfer_v2`, `transfer_v3` (`miotx`), `exchange_v2` (`miotx`),
870
+ * or `acquire_asset_v2` / `acquire_asset_v3` record into a 100% VNext-pure `TransactionBlockInput`
871
+ * containing only versionless atomic statements (`fg:t:transfer`, `fg:t:acquire_asset`) with explicit
872
+ * `readSet` / `writeSet` footprints and zero-sum conservation.
873
+ */
874
+ function compileLegacyTxToVNextTransactionBlock(rawRecord) {
875
+ const summary = parseLegacyTxReadOnlyArchiveRecord(rawRecord);
876
+ const blockId = summary.txHash ? `vnext:${summary.txHash}` : `vnext:${summary.recordKind}`;
877
+ if (summary.recordKind === "transfer_v2") {
878
+ const inp = summary.inputs[0];
879
+ const out = summary.outputs[0];
880
+ const stmt = {
881
+ id: "stmt_transfer_0",
882
+ type: "transfer",
883
+ typeUrl: "fg:t:transfer",
884
+ from: inp.owner,
885
+ itx: {
886
+ to: out.owner,
887
+ tokens: inp.tokens.map((t) => ({
888
+ address: t.address,
889
+ value: t.value.toString()
890
+ })),
891
+ assets: [...inp.assets]
892
+ }
893
+ };
894
+ const rawBlock = {
895
+ id: blockId,
896
+ from: inp.owner,
897
+ statements: [stmt],
898
+ enforceZeroSum: true
899
+ };
900
+ const footprint = require_transaction_block.extractStateFootprint(rawBlock);
901
+ const transactionBlock = {
902
+ ...rawBlock,
903
+ readSet: footprint.readSet,
904
+ writeSet: footprint.writeSet
905
+ };
906
+ assertTransactionBlockVNextPure(transactionBlock);
907
+ return {
908
+ archiveSummary: summary,
909
+ transactionBlock
910
+ };
911
+ }
912
+ if (summary.recordKind === "transfer_v3") {
913
+ const statements = [];
914
+ const remainingInputsByToken = /* @__PURE__ */ new Map();
915
+ for (const inp of summary.inputs) for (const t of inp.tokens) {
916
+ const queue = remainingInputsByToken.get(t.address) ?? [];
917
+ queue.push({
918
+ owner: inp.owner,
919
+ remaining: t.value
920
+ });
921
+ remainingInputsByToken.set(t.address, queue);
922
+ }
923
+ const remainingOutputsByToken = /* @__PURE__ */ new Map();
924
+ for (const out of summary.outputs) for (const t of out.tokens) {
925
+ const outQueue = remainingOutputsByToken.get(t.address) ?? [];
926
+ outQueue.push({
927
+ owner: out.owner,
928
+ needed: t.value
929
+ });
930
+ remainingOutputsByToken.set(t.address, outQueue);
931
+ }
932
+ for (const [tokenAddr, inQueue] of remainingInputsByToken.entries()) {
933
+ const outQueue = remainingOutputsByToken.get(tokenAddr) ?? [];
934
+ for (const inSlot of inQueue) {
935
+ if (inSlot.remaining === 0n) continue;
936
+ for (const outSlot of outQueue) {
937
+ if (outSlot.needed === 0n || outSlot.owner !== inSlot.owner) continue;
938
+ const selfChange = inSlot.remaining <= outSlot.needed ? inSlot.remaining : outSlot.needed;
939
+ inSlot.remaining -= selfChange;
940
+ outSlot.needed -= selfChange;
941
+ }
942
+ }
943
+ }
944
+ const assetOwnerMap = /* @__PURE__ */ new Map();
945
+ for (const inp of summary.inputs) for (const assetDid of inp.assets) assetOwnerMap.set(assetDid, inp.owner);
946
+ const pairTransfers = /* @__PURE__ */ new Map();
947
+ const getOrCreatePair = (from, to) => {
948
+ const key = `${from}->${to}`;
949
+ let pair = pairTransfers.get(key);
950
+ if (!pair) {
951
+ pair = {
952
+ from,
953
+ to,
954
+ tokens: /* @__PURE__ */ new Map(),
955
+ assets: []
956
+ };
957
+ pairTransfers.set(key, pair);
958
+ }
959
+ return pair;
960
+ };
961
+ for (const [tokenAddr, outQueue] of remainingOutputsByToken.entries()) {
962
+ const inQueue = remainingInputsByToken.get(tokenAddr) ?? [];
963
+ for (const outSlot of outQueue) {
964
+ if (outSlot.needed === 0n) continue;
965
+ for (const inSlot of inQueue) {
966
+ if (outSlot.needed === 0n) break;
967
+ if (inSlot.remaining === 0n) continue;
968
+ const matched = inSlot.remaining <= outSlot.needed ? inSlot.remaining : outSlot.needed;
969
+ inSlot.remaining -= matched;
970
+ outSlot.needed -= matched;
971
+ const pair = getOrCreatePair(inSlot.owner, outSlot.owner);
972
+ pair.tokens.set(tokenAddr, (pair.tokens.get(tokenAddr) ?? 0n) + matched);
973
+ }
974
+ }
975
+ }
976
+ for (const out of summary.outputs) for (const assetDid of out.assets) getOrCreatePair(assetOwnerMap.get(assetDid), out.owner).assets.push(assetDid);
977
+ let stepIdx = 0;
978
+ for (const pair of pairTransfers.values()) statements.push({
979
+ id: `stmt_transfer_${stepIdx++}`,
980
+ type: "transfer",
981
+ typeUrl: "fg:t:transfer",
982
+ from: pair.from,
983
+ itx: {
984
+ to: pair.to,
985
+ tokens: Array.from(pair.tokens.entries()).map(([address, val]) => ({
986
+ address,
987
+ value: val.toString()
988
+ })),
989
+ assets: [...pair.assets]
990
+ }
991
+ });
992
+ const rawBlock = {
993
+ id: blockId,
994
+ from: summary.fromDid,
995
+ statements,
996
+ enforceZeroSum: true
997
+ };
998
+ const footprint = require_transaction_block.extractStateFootprint(rawBlock);
999
+ const transactionBlock = {
1000
+ ...rawBlock,
1001
+ readSet: footprint.readSet,
1002
+ writeSet: footprint.writeSet
1003
+ };
1004
+ assertTransactionBlockVNextPure(transactionBlock);
1005
+ return {
1006
+ archiveSummary: summary,
1007
+ transactionBlock
1008
+ };
1009
+ }
1010
+ if (summary.recordKind === "exchange_v2") {
1011
+ const senderInput = summary.inputs[0];
1012
+ const receiverInput = summary.inputs[1];
1013
+ const statements = [{
1014
+ id: "stmt_swap_leg_0",
1015
+ type: "transfer",
1016
+ typeUrl: "fg:t:transfer",
1017
+ from: senderInput.owner,
1018
+ itx: {
1019
+ to: receiverInput.owner,
1020
+ tokens: senderInput.tokens.map((t) => ({
1021
+ address: t.address,
1022
+ value: t.value.toString()
1023
+ })),
1024
+ assets: [...senderInput.assets]
1025
+ }
1026
+ }, {
1027
+ id: "stmt_swap_leg_1",
1028
+ type: "transfer",
1029
+ typeUrl: "fg:t:transfer",
1030
+ from: receiverInput.owner,
1031
+ itx: {
1032
+ to: senderInput.owner,
1033
+ tokens: receiverInput.tokens.map((t) => ({
1034
+ address: t.address,
1035
+ value: t.value.toString()
1036
+ })),
1037
+ assets: [...receiverInput.assets]
1038
+ }
1039
+ }];
1040
+ const rawBlock = {
1041
+ id: blockId,
1042
+ from: senderInput.owner,
1043
+ statements,
1044
+ enforceZeroSum: true
1045
+ };
1046
+ const footprint = require_transaction_block.extractStateFootprint(rawBlock);
1047
+ const transactionBlock = {
1048
+ ...rawBlock,
1049
+ readSet: footprint.readSet,
1050
+ writeSet: footprint.writeSet
1051
+ };
1052
+ assertTransactionBlockVNextPure(transactionBlock);
1053
+ return {
1054
+ archiveSummary: summary,
1055
+ transactionBlock
1056
+ };
1057
+ }
1058
+ if (summary.recordKind === "acquire_asset_v2" || summary.recordKind === "acquire_asset_v3") {
1059
+ const statements = [];
1060
+ let stepIdx = 0;
1061
+ for (const inp of summary.inputs ?? []) statements.push({
1062
+ id: `stmt_factory_pay_${stepIdx++}`,
1063
+ type: "transfer",
1064
+ typeUrl: "fg:t:transfer",
1065
+ from: inp.owner,
1066
+ itx: {
1067
+ to: summary.factoryAddress,
1068
+ tokens: inp.tokens.map((t) => ({
1069
+ address: t.address,
1070
+ value: t.value.toString()
1071
+ })),
1072
+ assets: [...inp.assets]
1073
+ }
1074
+ });
1075
+ const paymentRefs = statements.map((_, idx) => `$steps[${idx}]`);
1076
+ statements.push({
1077
+ id: `stmt_acquire_asset_${stepIdx}`,
1078
+ type: "acquire_asset",
1079
+ typeUrl: "fg:t:acquire_asset",
1080
+ from: summary.fromDid,
1081
+ itx: {
1082
+ factory: summary.factoryAddress,
1083
+ to: summary.toDid,
1084
+ specsCount: summary.acquiredAssetSpecsCount ?? 1,
1085
+ ...paymentRefs.length > 0 ? {
1086
+ paymentRef: paymentRefs[0],
1087
+ paymentRefs
1088
+ } : {}
1089
+ }
1090
+ });
1091
+ const rawBlock = {
1092
+ id: blockId,
1093
+ from: summary.fromDid,
1094
+ statements,
1095
+ enforceZeroSum: true
1096
+ };
1097
+ const footprint = require_transaction_block.extractStateFootprint(rawBlock);
1098
+ const transactionBlock = {
1099
+ ...rawBlock,
1100
+ readSet: footprint.readSet,
1101
+ writeSet: footprint.writeSet
1102
+ };
1103
+ assertTransactionBlockVNextPure(transactionBlock);
1104
+ return {
1105
+ archiveSummary: summary,
1106
+ transactionBlock
1107
+ };
1108
+ }
1109
+ if (summary.recordKind === "mint_asset_v2" || summary.recordKind === "update_asset_v2" || summary.recordKind === "create_factory_v2") {
1110
+ const rawItx = rawRecord.itx && typeof rawRecord.itx === "object" && !Array.isArray(rawRecord.itx) ? { ...rawRecord.itx } : { ...rawRecord };
1111
+ const vnextTypeUrl = summary.vnextReplacementTypeUrl;
1112
+ const shortType = vnextTypeUrl.slice(5);
1113
+ const stmt = {
1114
+ id: `stmt_${shortType}_0`,
1115
+ type: shortType,
1116
+ typeUrl: vnextTypeUrl,
1117
+ from: summary.fromDid,
1118
+ itx: rawItx
1119
+ };
1120
+ const rawBlock = {
1121
+ id: blockId,
1122
+ from: summary.fromDid,
1123
+ statements: [stmt],
1124
+ enforceZeroSum: true
1125
+ };
1126
+ const footprint = require_transaction_block.extractStateFootprint(rawBlock);
1127
+ const transactionBlock = {
1128
+ ...rawBlock,
1129
+ readSet: footprint.readSet,
1130
+ writeSet: footprint.writeSet
1131
+ };
1132
+ assertTransactionBlockVNextPure(transactionBlock);
1133
+ return {
1134
+ archiveSummary: summary,
1135
+ transactionBlock
1136
+ };
1137
+ }
1138
+ if (summary.recordKind === "deposit_token_v2" || summary.recordKind === "withdraw_token_v2") {
1139
+ const rollupInfo = summary.rollupArchive;
1140
+ const actorDid = summary.fromDid ?? rollupInfo.recipientAddress;
1141
+ const rawBlock = {
1142
+ id: blockId,
1143
+ from: actorDid,
1144
+ statements: [{
1145
+ id: "stmt_settle_attestation_0",
1146
+ type: "settle_attestation",
1147
+ typeUrl: "fg:t:settle_attestation",
1148
+ from: actorDid,
1149
+ itx: {
1150
+ attestationKind: summary.recordKind,
1151
+ rollupAddress: rollupInfo.rollupAddress,
1152
+ tokenAddress: rollupInfo.tokenAddress,
1153
+ recipientAddress: rollupInfo.recipientAddress,
1154
+ amount: rollupInfo.amount?.toString(),
1155
+ evidenceHash: rollupInfo.evidenceHash
1156
+ }
1157
+ }],
1158
+ enforceZeroSum: true
1159
+ };
1160
+ const footprint = require_transaction_block.extractStateFootprint(rawBlock);
1161
+ const transactionBlock = {
1162
+ ...rawBlock,
1163
+ readSet: footprint.readSet,
1164
+ writeSet: footprint.writeSet
1165
+ };
1166
+ assertTransactionBlockVNextPure(transactionBlock);
1167
+ return {
1168
+ archiveSummary: summary,
1169
+ transactionBlock
1170
+ };
1171
+ }
1172
+ throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolSunset: legacy Rollup/Bridge record ${summary.recordKind} cannot be compiled to an L1 TransactionBlock; use Zero-Rollup-Block EIP-712 OcapSimplifiedEvmBridgeNode instead`);
1173
+ }
1174
+ /**
1175
+ * Executes a VNext `TransactionBlockInput` after enforcing `assertTransactionBlockVNextPure`
1176
+ * (guaranteeing no deprecated `V1/V2/V3`, `miotx`, or Rollup protocol can execute at or after `sunsetActivationHeight`).
1177
+ */
1178
+ async function executeVNextTransactionBlock(block, options) {
1179
+ assertTransactionBlockVNextPure(block, {
1180
+ currentBlockHeight: options.currentBlockHeight,
1181
+ sunsetActivationHeight: options.sunsetActivationHeight,
1182
+ requireStrictCanonicalWhitelist: true
1183
+ });
1184
+ return require_transaction_block.executeTransactionBlock(block, {
1185
+ statedb: options.statedb,
1186
+ executeStatement: options.executeStatement,
1187
+ dryRun: options.dryRun
1188
+ });
1189
+ }
1190
+ /**
1191
+ * Issue #1251:
1192
+ * Pluggable Compatibility Add-On Layer (`LegacyProtocolCompatibilityAddon`).
1193
+ *
1194
+ * Allows existing wallets (DID Wallet), SDKs, and legacy services that still submit deprecated
1195
+ * `V1/V2/V3` (`transfer_v2`, `acquire_asset_v2`), `miotx` (`transfer_v3`, `exchange_v2`, `acquire_asset_v3`),
1196
+ * or application-coupled protocol names (`contract_nft`, `give_karma`, `claim_karma`, `evm_bridge_settlement`)
1197
+ * to continue working seamlessly in the current release (`ADDON_TRANSLATE_AND_EXECUTE`), while
1198
+ * 100% of underlying state execution runs on the pure, domain-agnostic VNext `TransactionBlock` engine.
1199
+ *
1200
+ * In the next major release, operators simply switch `mode` to `'SUNSET_READ_ONLY_ARCHIVE'` (or remove the add-on)
1201
+ * to reject legacy write protocols fail-closed while preserving read-only archive decoding.
1202
+ */
1203
+ var LegacyProtocolCompatibilityAddon = class {
1204
+ constructor(options) {
1205
+ this.totalTranslatedTxs = 0;
1206
+ this.totalPassthroughVNextTxs = 0;
1207
+ this.rejectedAfterSunsetCount = 0;
1208
+ this.translatedCounts = /* @__PURE__ */ new Map();
1209
+ const mode = options?.mode ?? "ADDON_TRANSLATE_AND_EXECUTE";
1210
+ if (mode !== "ADDON_TRANSLATE_AND_EXECUTE" && mode !== "SUNSET_READ_ONLY_ARCHIVE") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolCompatibilityAddon: invalid mode ${String(mode)}`);
1211
+ const targetRemovalRelease = assertCleanString(options?.targetRemovalRelease ?? "v2.0-major", "targetRemovalRelease", 64);
1212
+ const sunsetActivationHeight = options?.sunsetActivationHeight ?? DEFAULT_LEGACY_PROTOCOL_SUNSET_HEIGHT;
1213
+ if (!Number.isSafeInteger(sunsetActivationHeight) || sunsetActivationHeight < 1) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolCompatibilityAddon: sunsetActivationHeight must be a positive safe integer (>= 1)");
1214
+ this.mode = mode;
1215
+ this.targetRemovalRelease = targetRemovalRelease;
1216
+ this.sunsetActivationHeight = sunsetActivationHeight;
1217
+ }
1218
+ getMode() {
1219
+ return this.mode;
1220
+ }
1221
+ setMode(mode) {
1222
+ if (mode !== "ADDON_TRANSLATE_AND_EXECUTE" && mode !== "SUNSET_READ_ONLY_ARCHIVE") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolCompatibilityAddon: invalid mode ${String(mode)}`);
1223
+ this.mode = mode;
1224
+ }
1225
+ getMetrics() {
1226
+ const countsObj = {};
1227
+ for (const [k, v] of this.translatedCounts.entries()) countsObj[k] = v;
1228
+ return Object.freeze({
1229
+ mode: this.mode,
1230
+ targetRemovalRelease: this.targetRemovalRelease,
1231
+ totalTranslatedTxs: this.totalTranslatedTxs,
1232
+ totalPassthroughVNextTxs: this.totalPassthroughVNextTxs,
1233
+ rejectedAfterSunsetCount: this.rejectedAfterSunsetCount,
1234
+ translatedByLegacyTypeUrl: Object.freeze(countsObj)
1235
+ });
1236
+ }
1237
+ recordTranslation(warnings, originalTypeUrl, translatedVNextTypeUrl, category, guidance) {
1238
+ this.translatedCounts.set(originalTypeUrl, (this.translatedCounts.get(originalTypeUrl) ?? 0) + 1);
1239
+ warnings.push(Object.freeze({
1240
+ originalTypeUrl,
1241
+ translatedVNextTypeUrl,
1242
+ category,
1243
+ targetRemovalRelease: this.targetRemovalRelease,
1244
+ message: `[CompatibilityAddon] Protocol ${originalTypeUrl} is deprecated and scheduled for removal in ${this.targetRemovalRelease}; transparently translated to ${translatedVNextTypeUrl}. ${guidance}`
1245
+ }));
1246
+ }
1247
+ remapStepReferencesInValue(value, mapIndex, depth = 0) {
1248
+ if (depth > 16 || value === null || value === void 0) return value;
1249
+ if (typeof value === "string") {
1250
+ if (!value.includes("$steps[")) return value;
1251
+ return value.replace(/\$steps\[(\d+)\]/g, (_match, rawIdx) => {
1252
+ const parsedIdx = Number(rawIdx);
1253
+ return Number.isSafeInteger(parsedIdx) ? `$steps[${mapIndex(parsedIdx)}]` : _match;
1254
+ });
1255
+ }
1256
+ if (Array.isArray(value)) return value.map((item) => this.remapStepReferencesInValue(item, mapIndex, depth + 1));
1257
+ if (typeof value === "object") {
1258
+ const out = {};
1259
+ for (const [k, v] of Object.entries(value)) out[k] = this.remapStepReferencesInValue(v, mapIndex, depth + 1);
1260
+ return out;
1261
+ }
1262
+ return value;
1263
+ }
1264
+ translateStatementTemplateRecursively(stmt, warnings, currentBlockHeight, depth = 0) {
1265
+ if (depth > 8) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, "LegacyProtocolCompatibilityAddon: maximum nested statementTemplates depth exceeded");
1266
+ if (!stmt || typeof stmt !== "object" || Array.isArray(stmt)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolCompatibilityAddon: statement must be an object");
1267
+ assertNoProtoPollutionKeys(stmt, "statement");
1268
+ const hasTypeUrl = stmt.typeUrl !== void 0 && stmt.typeUrl !== null && String(stmt.typeUrl).trim() !== "";
1269
+ const hasType = stmt.type !== void 0 && stmt.type !== null && String(stmt.type).trim() !== "";
1270
+ if (!hasTypeUrl && !hasType) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolCompatibilityAddon: statement is missing type or typeUrl");
1271
+ const normUrl = hasTypeUrl ? normalizeProtocolTypeUrl(String(stmt.typeUrl)) : "";
1272
+ const normType = hasType ? normalizeProtocolTypeUrl(String(stmt.type)) : "";
1273
+ if (hasTypeUrl && hasType && normUrl !== normType) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolCompatibilityAddon: statement has conflicting typeUrl (${normUrl}) and type (${normType})`);
1274
+ const canonicalInputUrl = normUrl || normType;
1275
+ let resolvedTypeUrl = canonicalInputUrl;
1276
+ if (isDomainCoupledProtocolAlias(canonicalInputUrl)) {
1277
+ if (this.mode === "SUNSET_READ_ONLY_ARCHIVE" && currentBlockHeight >= this.sunsetActivationHeight) {
1278
+ this.rejectedAfterSunsetCount += 1;
1279
+ throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolCompatibilityAddon: domain-coupled protocol alias ${canonicalInputUrl} is disabled in SUNSET_READ_ONLY_ARCHIVE mode at height ${currentBlockHeight}`);
1280
+ }
1281
+ const mapped = resolveDomainAgnosticVNextProtocol(canonicalInputUrl);
1282
+ this.recordTranslation(warnings, canonicalInputUrl, mapped, "DOMAIN_COUPLED_ALIAS", `Use domain-agnostic L1 primitive ${mapped}`);
1283
+ resolvedTypeUrl = mapped;
1284
+ } else if (isDeprecatedLegacyWriteProtocol(canonicalInputUrl)) {
1285
+ if (this.mode === "SUNSET_READ_ONLY_ARCHIVE" && currentBlockHeight >= this.sunsetActivationHeight) {
1286
+ this.rejectedAfterSunsetCount += 1;
1287
+ assertLegacyProtocolNotSunset({
1288
+ typeUrl: canonicalInputUrl,
1289
+ currentBlockHeight,
1290
+ sunsetActivationHeight: this.sunsetActivationHeight
1291
+ });
1292
+ }
1293
+ const spec = getLegacyProtocolReplacementSpec(canonicalInputUrl);
1294
+ if (spec.isMiotx || canonicalInputUrl === "fg:t:create_rollup_block" || canonicalInputUrl === "fg:t:rollup_block" || canonicalInputUrl === "fg:t:rollup_state") throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolCompatibilityAddon: multi-statement/rollup protocol ${canonicalInputUrl} cannot be nested inside statementTemplates`);
1295
+ this.recordTranslation(warnings, spec.legacyTypeUrl, spec.vnextReplacementTypeUrl, spec.category, spec.migrationGuidance);
1296
+ resolvedTypeUrl = spec.vnextReplacementTypeUrl;
1297
+ }
1298
+ const rawItx = stmt.itx && typeof stmt.itx === "object" && !Array.isArray(stmt.itx) ? { ...stmt.itx } : {};
1299
+ assertNoProtoPollutionKeys(rawItx, "stmt.itx");
1300
+ if (Array.isArray(rawItx.statementTemplates)) rawItx.statementTemplates = rawItx.statementTemplates.map((tpl) => this.translateStatementTemplateRecursively(tpl, warnings, currentBlockHeight, depth + 1));
1301
+ if (rawItx.data?.value && Array.isArray(rawItx.data.value.statementTemplates)) rawItx.data = {
1302
+ ...rawItx.data,
1303
+ value: {
1304
+ ...rawItx.data.value,
1305
+ statementTemplates: rawItx.data.value.statementTemplates.map((tpl) => this.translateStatementTemplateRecursively(tpl, warnings, currentBlockHeight, depth + 1))
1306
+ }
1307
+ };
1308
+ if (rawItx.contractAsset?.data?.value && Array.isArray(rawItx.contractAsset.data.value.statementTemplates)) rawItx.contractAsset = {
1309
+ ...rawItx.contractAsset,
1310
+ data: {
1311
+ ...rawItx.contractAsset.data,
1312
+ value: {
1313
+ ...rawItx.contractAsset.data.value,
1314
+ statementTemplates: rawItx.contractAsset.data.value.statementTemplates.map((tpl) => this.translateStatementTemplateRecursively(tpl, warnings, currentBlockHeight, depth + 1))
1315
+ }
1316
+ }
1317
+ };
1318
+ const shortType = resolvedTypeUrl.startsWith("fg:t:") ? resolvedTypeUrl.slice(5) : resolvedTypeUrl;
1319
+ return {
1320
+ ...stmt,
1321
+ type: shortType,
1322
+ typeUrl: resolvedTypeUrl,
1323
+ itx: rawItx
1324
+ };
1325
+ }
1326
+ /**
1327
+ * Translates any legacy single transaction (`transfer_v2`, `transfer_v3`, `exchange_v2`, `acquire_asset_v2/v3`,
1328
+ * `mint_asset_v2`, `update_asset_v2`, `create_factory_v2`, `deposit_token_v2`, `withdraw_token_v2`),
1329
+ * domain-coupled statement (`contract_nft`, `give_karma`, `claim_karma`, `evm_bridge_settlement`),
1330
+ * or `TransactionBlockInput` into a 100% pure, domain-agnostic VNext `TransactionBlockInput`.
1331
+ */
1332
+ translateToVNextTransactionBlock(txOrBlock, options) {
1333
+ if (!txOrBlock || typeof txOrBlock !== "object" || Array.isArray(txOrBlock)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolCompatibilityAddon: txOrBlock must be a plain object");
1334
+ assertNoProtoPollutionKeys(txOrBlock, "txOrBlock");
1335
+ const currentBlockHeight = options?.currentBlockHeight ?? DEFAULT_LEGACY_PROTOCOL_SUNSET_HEIGHT;
1336
+ if (!Number.isSafeInteger(currentBlockHeight) || currentBlockHeight < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolCompatibilityAddon: currentBlockHeight must be a non-negative safe integer");
1337
+ const warnings = [];
1338
+ if ("statements" in txOrBlock && Array.isArray(txOrBlock.statements)) {
1339
+ const inputBlock = txOrBlock;
1340
+ if (inputBlock.statements.length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolCompatibilityAddon: TransactionBlock must contain at least one statement");
1341
+ if (this.mode === "SUNSET_READ_ONLY_ARCHIVE" && currentBlockHeight >= this.sunsetActivationHeight) {
1342
+ try {
1343
+ assertTransactionBlockVNextPure(inputBlock, {
1344
+ currentBlockHeight,
1345
+ sunsetActivationHeight: this.sunsetActivationHeight,
1346
+ requireStrictCanonicalWhitelist: true
1347
+ });
1348
+ } catch (err) {
1349
+ this.rejectedAfterSunsetCount += 1;
1350
+ throw err;
1351
+ }
1352
+ this.totalPassthroughVNextTxs += 1;
1353
+ return Object.freeze({
1354
+ transactionBlock: inputBlock,
1355
+ wasTranslated: false,
1356
+ compatibilityMode: this.mode,
1357
+ deprecationWarnings: Object.freeze([])
1358
+ });
1359
+ }
1360
+ const expandedStatements = [];
1361
+ const origStepLastExpandedIndex = [];
1362
+ for (let i = 0; i < inputBlock.statements.length; i++) {
1363
+ const rawStmt = inputBlock.statements[i];
1364
+ if (!rawStmt || typeof rawStmt !== "object" || Array.isArray(rawStmt)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolCompatibilityAddon: statement[${i}] must be an object`);
1365
+ const hasTypeUrl$1 = rawStmt.typeUrl !== void 0 && rawStmt.typeUrl !== null && String(rawStmt.typeUrl).trim() !== "";
1366
+ const hasType$1 = rawStmt.type !== void 0 && rawStmt.type !== null && String(rawStmt.type).trim() !== "";
1367
+ if (!hasTypeUrl$1 && !hasType$1) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, `LegacyProtocolCompatibilityAddon: statement[${i}] is missing type or typeUrl`);
1368
+ const normUrl$1 = hasTypeUrl$1 ? normalizeProtocolTypeUrl(String(rawStmt.typeUrl)) : "";
1369
+ const normType$1 = hasType$1 ? normalizeProtocolTypeUrl(String(rawStmt.type)) : "";
1370
+ if (hasTypeUrl$1 && hasType$1 && normUrl$1 !== normType$1) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolCompatibilityAddon: statement[${i}] has conflicting typeUrl (${normUrl$1}) and type (${normType$1})`);
1371
+ const stmtTypeUrl = normUrl$1 || normType$1;
1372
+ const baseOffset = expandedStatements.length;
1373
+ if (isDeprecatedLegacyWriteProtocol(stmtTypeUrl)) {
1374
+ const spec = getLegacyProtocolReplacementSpec(stmtTypeUrl);
1375
+ const compiledSub = compileLegacyTxToVNextTransactionBlock({
1376
+ ...rawStmt,
1377
+ from: rawStmt.from ?? inputBlock.from,
1378
+ typeUrl: stmtTypeUrl
1379
+ });
1380
+ this.recordTranslation(warnings, spec.legacyTypeUrl, spec.vnextReplacementTypeUrl, spec.category, spec.migrationGuidance);
1381
+ for (const subStmt of compiledSub.transactionBlock.statements) {
1382
+ const shiftedItx = baseOffset > 0 ? this.remapStepReferencesInValue(subStmt.itx, (localIdx) => baseOffset + localIdx) : subStmt.itx;
1383
+ expandedStatements.push({
1384
+ ...subStmt,
1385
+ id: `${rawStmt.id ?? `stmt_${i}`}_${subStmt.id ?? expandedStatements.length}`,
1386
+ itx: shiftedItx
1387
+ });
1388
+ }
1389
+ origStepLastExpandedIndex.push(expandedStatements.length - 1);
1390
+ } else {
1391
+ const translatedStmt = this.translateStatementTemplateRecursively(rawStmt, warnings, currentBlockHeight, 0);
1392
+ const remappedItx = this.remapStepReferencesInValue(translatedStmt.itx, (origIdx) => origIdx < origStepLastExpandedIndex.length ? origStepLastExpandedIndex[origIdx] : origIdx);
1393
+ expandedStatements.push({
1394
+ ...translatedStmt,
1395
+ itx: remappedItx
1396
+ });
1397
+ origStepLastExpandedIndex.push(expandedStatements.length - 1);
1398
+ }
1399
+ }
1400
+ const translatedBlock = {
1401
+ ...inputBlock,
1402
+ statements: expandedStatements,
1403
+ enforceZeroSum: inputBlock.enforceZeroSum !== false
1404
+ };
1405
+ const footprint$1 = require_transaction_block.extractStateFootprint(translatedBlock);
1406
+ const finalBlock$1 = {
1407
+ ...translatedBlock,
1408
+ readSet: footprint$1.readSet,
1409
+ writeSet: footprint$1.writeSet
1410
+ };
1411
+ assertTransactionBlockVNextPure(finalBlock$1, {
1412
+ currentBlockHeight,
1413
+ sunsetActivationHeight: this.sunsetActivationHeight,
1414
+ requireStrictCanonicalWhitelist: true
1415
+ });
1416
+ const wasTranslated$1 = warnings.length > 0;
1417
+ if (wasTranslated$1) this.totalTranslatedTxs += 1;
1418
+ else this.totalPassthroughVNextTxs += 1;
1419
+ return Object.freeze({
1420
+ transactionBlock: finalBlock$1,
1421
+ wasTranslated: wasTranslated$1,
1422
+ compatibilityMode: this.mode,
1423
+ deprecationWarnings: Object.freeze(warnings)
1424
+ });
1425
+ }
1426
+ const rawRecord = txOrBlock;
1427
+ const hasTypeUrl = rawRecord.typeUrl !== void 0 && rawRecord.typeUrl !== null && String(rawRecord.typeUrl).trim() !== "";
1428
+ const hasType = rawRecord.type !== void 0 && rawRecord.type !== null && String(rawRecord.type).trim() !== "";
1429
+ const hasRecordKind = rawRecord.recordKind !== void 0 && rawRecord.recordKind !== null && String(rawRecord.recordKind).trim() !== "";
1430
+ if (!hasTypeUrl && !hasType && !hasRecordKind) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidSunset, "LegacyProtocolCompatibilityAddon: typeUrl, type, or statements[] is required");
1431
+ const normUrl = hasTypeUrl ? normalizeProtocolTypeUrl(String(rawRecord.typeUrl)) : "";
1432
+ const normType = hasType ? normalizeProtocolTypeUrl(String(rawRecord.type)) : "";
1433
+ if (hasTypeUrl && hasType && normUrl !== normType) {
1434
+ if (this.mode === "SUNSET_READ_ONLY_ARCHIVE" && currentBlockHeight >= this.sunsetActivationHeight) this.rejectedAfterSunsetCount += 1;
1435
+ throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolCompatibilityAddon: transaction has conflicting typeUrl (${normUrl}) and type (${normType})`);
1436
+ }
1437
+ const rawKind = String(rawRecord.typeUrl ?? rawRecord.type ?? rawRecord.recordKind ?? "").trim();
1438
+ const canonicalUrl = normUrl || normType || normalizeProtocolTypeUrl(rawKind);
1439
+ if (this.mode === "SUNSET_READ_ONLY_ARCHIVE" && currentBlockHeight >= this.sunsetActivationHeight) try {
1440
+ assertLegacyProtocolNotSunset({
1441
+ typeUrl: canonicalUrl,
1442
+ currentBlockHeight,
1443
+ sunsetActivationHeight: this.sunsetActivationHeight
1444
+ });
1445
+ if (isDomainCoupledProtocolAlias(canonicalUrl)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenSunset, `LegacyProtocolCompatibilityAddon: domain-coupled protocol alias ${canonicalUrl} is disabled in SUNSET_READ_ONLY_ARCHIVE mode`);
1446
+ } catch (err) {
1447
+ this.rejectedAfterSunsetCount += 1;
1448
+ throw err;
1449
+ }
1450
+ if (isDeprecatedLegacyWriteProtocol(canonicalUrl)) {
1451
+ const spec = getLegacyProtocolReplacementSpec(canonicalUrl);
1452
+ const compiled = compileLegacyTxToVNextTransactionBlock(rawRecord);
1453
+ this.recordTranslation(warnings, spec.legacyTypeUrl, spec.vnextReplacementTypeUrl, spec.category, spec.migrationGuidance);
1454
+ this.totalTranslatedTxs += 1;
1455
+ return Object.freeze({
1456
+ transactionBlock: compiled.transactionBlock,
1457
+ wasTranslated: true,
1458
+ compatibilityMode: this.mode,
1459
+ deprecationWarnings: Object.freeze(warnings),
1460
+ archiveSummary: compiled.archiveSummary
1461
+ });
1462
+ }
1463
+ const fromDid = assertCleanString(rawRecord.from ?? rawRecord.itx?.from, "from");
1464
+ const wrappedStmt = this.translateStatementTemplateRecursively({
1465
+ id: "stmt_0",
1466
+ typeUrl: canonicalUrl,
1467
+ from: fromDid,
1468
+ delegator: typeof rawRecord.delegator === "string" ? rawRecord.delegator : void 0,
1469
+ itx: rawRecord.itx && typeof rawRecord.itx === "object" && !Array.isArray(rawRecord.itx) ? rawRecord.itx : rawRecord
1470
+ }, warnings, currentBlockHeight, 0);
1471
+ const rawBlock = {
1472
+ id: typeof rawRecord.txHash === "string" ? `vnext:${rawRecord.txHash}` : void 0,
1473
+ from: fromDid,
1474
+ statements: [wrappedStmt],
1475
+ enforceZeroSum: true
1476
+ };
1477
+ const footprint = require_transaction_block.extractStateFootprint(rawBlock);
1478
+ const finalBlock = {
1479
+ ...rawBlock,
1480
+ readSet: footprint.readSet,
1481
+ writeSet: footprint.writeSet
1482
+ };
1483
+ assertTransactionBlockVNextPure(finalBlock, {
1484
+ currentBlockHeight,
1485
+ sunsetActivationHeight: this.sunsetActivationHeight,
1486
+ requireStrictCanonicalWhitelist: true
1487
+ });
1488
+ const wasTranslated = warnings.length > 0;
1489
+ if (wasTranslated) this.totalTranslatedTxs += 1;
1490
+ else this.totalPassthroughVNextTxs += 1;
1491
+ return Object.freeze({
1492
+ transactionBlock: finalBlock,
1493
+ wasTranslated,
1494
+ compatibilityMode: this.mode,
1495
+ deprecationWarnings: Object.freeze(warnings)
1496
+ });
1497
+ }
1498
+ /**
1499
+ * End-to-end execution through the Compatibility Add-On Layer:
1500
+ * 1. Translates legacy `V1/V2/V3`, `miotx`, or domain-coupled protocols into a pure VNext `TransactionBlockInput`
1501
+ * (when in `'ADDON_TRANSLATE_AND_EXECUTE'` mode) or rejects them fail-closed (when in `'SUNSET_READ_ONLY_ARCHIVE'` mode).
1502
+ * 2. Executes the resulting pure VNext `TransactionBlockInput` on the VNext `OverlayStateDB` engine.
1503
+ */
1504
+ async executeWithCompatibilityAddon(txOrBlock, options) {
1505
+ const translationResult = this.translateToVNextTransactionBlock(txOrBlock, { currentBlockHeight: options.currentBlockHeight });
1506
+ return {
1507
+ executionResult: await executeVNextTransactionBlock(translationResult.transactionBlock, {
1508
+ statedb: options.statedb,
1509
+ executeStatement: options.executeStatement,
1510
+ currentBlockHeight: options.currentBlockHeight,
1511
+ sunsetActivationHeight: this.sunsetActivationHeight,
1512
+ dryRun: options.dryRun
1513
+ }),
1514
+ translationResult
1515
+ };
1516
+ }
1517
+ };
1518
+
1519
+ //#endregion
1520
+ exports.DEFAULT_LEGACY_PROTOCOL_SUNSET_HEIGHT = DEFAULT_LEGACY_PROTOCOL_SUNSET_HEIGHT;
1521
+ exports.DEPRECATED_LEGACY_PROTOCOL_TYPE_URLS = DEPRECATED_LEGACY_PROTOCOL_TYPE_URLS;
1522
+ exports.DEPRECATED_MIOTX_AND_TRADE_TYPE_URLS = DEPRECATED_MIOTX_AND_TRADE_TYPE_URLS;
1523
+ exports.DEPRECATED_MIOTX_PROTOCOL_TYPE_URLS = DEPRECATED_MIOTX_PROTOCOL_TYPE_URLS;
1524
+ exports.DEPRECATED_ROLLUP_AND_BRIDGE_TYPE_URLS = DEPRECATED_ROLLUP_AND_BRIDGE_TYPE_URLS;
1525
+ exports.DEPRECATED_VERSIONED_ASSET_TYPE_URLS = DEPRECATED_VERSIONED_ASSET_TYPE_URLS;
1526
+ exports.DOMAIN_COUPLED_PROTOCOL_ALIAS_MAP = DOMAIN_COUPLED_PROTOCOL_ALIAS_MAP;
1527
+ exports.LegacyProtocolCompatibilityAddon = LegacyProtocolCompatibilityAddon;
1528
+ exports.MAX_LEGACY_MIOTX_ASSETS_PER_ENTRY = MAX_LEGACY_MIOTX_ASSETS_PER_ENTRY;
1529
+ exports.MAX_LEGACY_MIOTX_PARTICIPANTS = MAX_LEGACY_MIOTX_PARTICIPANTS;
1530
+ exports.MAX_LEGACY_MIOTX_TOKENS_PER_ENTRY = MAX_LEGACY_MIOTX_TOKENS_PER_ENTRY;
1531
+ exports.VNEXT_CANONICAL_WRITE_PROTOCOL_TYPE_URLS = VNEXT_CANONICAL_WRITE_PROTOCOL_TYPE_URLS;
1532
+ exports.assertLegacyProtocolNotSunset = assertLegacyProtocolNotSunset;
1533
+ exports.assertTransactionBlockVNextPure = assertTransactionBlockVNextPure;
1534
+ exports.compileLegacyTxToVNextTransactionBlock = compileLegacyTxToVNextTransactionBlock;
1535
+ exports.executeVNextTransactionBlock = executeVNextTransactionBlock;
1536
+ exports.getLegacyProtocolReplacementSpec = getLegacyProtocolReplacementSpec;
1537
+ exports.isDeprecatedLegacyWriteProtocol = isDeprecatedLegacyWriteProtocol;
1538
+ exports.isDomainCoupledProtocolAlias = isDomainCoupledProtocolAlias;
1539
+ exports.isMiotxLegacyProtocol = isMiotxLegacyProtocol;
1540
+ exports.isVNextCanonicalWriteProtocol = isVNextCanonicalWriteProtocol;
1541
+ exports.normalizeProtocolTypeUrl = normalizeProtocolTypeUrl;
1542
+ exports.parseLegacyTxReadOnlyArchiveRecord = parseLegacyTxReadOnlyArchiveRecord;
1543
+ exports.resolveDomainAgnosticVNextProtocol = resolveDomainAgnosticVNextProtocol;