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