@ocap/tx-pipeline 1.30.26 → 1.31.1

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 +46 -4
  25. package/esm/pipes/decode-tx.d.mts +2 -3
  26. package/esm/pipes/decode-tx.mjs +56 -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 +73 -0
  32. package/esm/pipes/pre-flight-waf.mjs +756 -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 +46 -4
  94. package/lib/pipes/decode-itx.d.cts +1 -1
  95. package/lib/pipes/decode-tx.cjs +55 -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 +772 -0
  102. package/lib/pipes/pre-flight-waf.d.cts +73 -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,17 @@
1
+ //#region src/ofac-screening.d.ts
2
+ /**
3
+ * Official Chainalysis OFAC Sanctions Screening Oracle deployed across Ethereum, Base, Arbitrum, and Optimism.
4
+ */
5
+ declare const CHAINALYSIS_OFAC_ORACLE_ADDRESS = "0x40C57923924B5c5c5455c48D93317139ADDaC8fb";
6
+ /**
7
+ * Normalizes an EVM 0x address (lowercased) or OCAP DID (stripping optional `did:abt:` prefix)
8
+ * so sanctions screening cannot be bypassed via mixed-case EIP-55 hex or `did:abt:` prefixing.
9
+ */
10
+ declare function normalizeScreeningAddress(address: string): string;
11
+ /**
12
+ * Screens a list of addresses (EVM 0x addresses or OCAP DIDs) against an OFAC sanctions blocklist.
13
+ * Normalizes EVM hex addresses to lowercase and strips `did:abt:` prefixes to prevent bypasses.
14
+ */
15
+ declare function assertNotOfacSanctioned(addresses: Array<string | undefined | null>, ofacBlocklist?: Iterable<string>): void;
16
+ //#endregion
17
+ export { CHAINALYSIS_OFAC_ORACLE_ADDRESS, assertNotOfacSanctioned, normalizeScreeningAddress };
@@ -0,0 +1,39 @@
1
+ import { CustomError } from "@ocap/util/lib/error";
2
+
3
+ //#region src/ofac-screening.ts
4
+ /**
5
+ * Official Chainalysis OFAC Sanctions Screening Oracle deployed across Ethereum, Base, Arbitrum, and Optimism.
6
+ */
7
+ const CHAINALYSIS_OFAC_ORACLE_ADDRESS = "0x40C57923924B5c5c5455c48D93317139ADDaC8fb";
8
+ /**
9
+ * Normalizes an EVM 0x address (lowercased) or OCAP DID (stripping optional `did:abt:` prefix)
10
+ * so sanctions screening cannot be bypassed via mixed-case EIP-55 hex or `did:abt:` prefixing.
11
+ */
12
+ function normalizeScreeningAddress(address) {
13
+ const trimmed = String(address || "").trim();
14
+ if (!trimmed) return "";
15
+ const withoutDidPrefix = trimmed.replace(/^did:abt:/i, "");
16
+ if (!withoutDidPrefix) return "";
17
+ return /^0x[0-9a-fA-F]+$/.test(withoutDidPrefix) ? withoutDidPrefix.toLowerCase() : withoutDidPrefix;
18
+ }
19
+ /**
20
+ * Screens a list of addresses (EVM 0x addresses or OCAP DIDs) against an OFAC sanctions blocklist.
21
+ * Normalizes EVM hex addresses to lowercase and strips `did:abt:` prefixes to prevent bypasses.
22
+ */
23
+ function assertNotOfacSanctioned(addresses, ofacBlocklist) {
24
+ if (!ofacBlocklist) return;
25
+ const normalizedBlocklist = /* @__PURE__ */ new Set();
26
+ for (const entry of ofacBlocklist) {
27
+ const norm = normalizeScreeningAddress(entry);
28
+ if (norm) normalizedBlocklist.add(norm);
29
+ }
30
+ if (normalizedBlocklist.size === 0) return;
31
+ for (const addr of addresses) {
32
+ if (!addr) continue;
33
+ const normalized = normalizeScreeningAddress(addr);
34
+ if (normalized && normalizedBlocklist.has(normalized)) throw new CustomError("OFAC_SANCTIONED_ADDRESS", `Address ${addr} is blocked by OFAC sanctions screening (oracle: ${CHAINALYSIS_OFAC_ORACLE_ADDRESS})`);
35
+ }
36
+ }
37
+
38
+ //#endregion
39
+ export { CHAINALYSIS_OFAC_ORACLE_ADDRESS, assertNotOfacSanctioned, normalizeScreeningAddress };
@@ -1,6 +1,6 @@
1
- import get from "lodash/get.js";
2
1
  import { isSameDid } from "@ocap/util";
3
2
  import { CustomError } from "@ocap/util/lib/error";
3
+ import get from "lodash/get.js";
4
4
 
5
5
  //#region src/pipes/anti-land-attack.ts
6
6
  function CreateAntiLandAttackPipe({ senderState = "senderState", receiverState = "receiverState" } = {}) {
@@ -17,8 +17,42 @@ import { createMessage, decodeAny, fromTypeUrl, toTypeUrl } from "@ocap/message"
17
17
  * sees a single, stable shape regardless of wire format.
18
18
  */
19
19
  function toJspbObject(typeUrl, inner) {
20
- const msg = createMessage(fromTypeUrl(typeUrl), inner);
21
- return msg?.toObject ? msg.toObject() : inner;
20
+ const typeName = fromTypeUrl(typeUrl);
21
+ const msg = createMessage(typeName, inner);
22
+ const converted = msg?.toObject ? msg.toObject() : inner;
23
+ if (typeName === "DelegateTx" && converted && typeof converted === "object") {
24
+ const rawOps = Array.isArray(inner.opsList) ? inner.opsList : Array.isArray(inner.ops) ? inner.ops : [];
25
+ const outOps = Array.isArray(converted.opsList) ? converted.opsList : [];
26
+ const tokenExtKeys = [
27
+ "maxPerTx",
28
+ "windowLimit",
29
+ "windowSeconds",
30
+ "windowStart",
31
+ "windowSpent",
32
+ "coSignAllowance",
33
+ "coSignRequired",
34
+ "requirePinnedPayee",
35
+ "notifyBeforeDebit",
36
+ "notifyLeadSeconds"
37
+ ];
38
+ for (let i = 0; i < rawOps.length && i < outOps.length; i++) {
39
+ const rawLimit = rawOps[i]?.limit;
40
+ const outLimit = outOps[i]?.limit;
41
+ if (rawLimit && typeof rawLimit === "object" && outLimit && typeof outLimit === "object") {
42
+ if (rawLimit.unlimited !== void 0) outLimit.unlimited = rawLimit.unlimited;
43
+ const rawTokens = Array.isArray(rawLimit.tokensList) ? rawLimit.tokensList : Array.isArray(rawLimit.tokens) ? rawLimit.tokens : [];
44
+ const outTokens = Array.isArray(outLimit.tokensList) ? outLimit.tokensList : [];
45
+ for (let j = 0; j < rawTokens.length && j < outTokens.length; j++) {
46
+ const rt = rawTokens[j];
47
+ const ot = outTokens[j];
48
+ if (rt && typeof rt === "object" && ot && typeof ot === "object") {
49
+ for (const k of tokenExtKeys) if (rt[k] !== void 0) ot[k] = rt[k];
50
+ }
51
+ }
52
+ }
53
+ }
54
+ }
55
+ return converted;
22
56
  }
23
57
  function normalizeItx(raw) {
24
58
  if (!raw || typeof raw !== "object") return null;
@@ -51,15 +85,23 @@ function normalizeItx(raw) {
51
85
  }
52
86
  function DecodeItx(context, next) {
53
87
  try {
88
+ context._preFlightWafScanned = false;
89
+ context._preFlightVerified = false;
90
+ context._preFlightSnapshotApplied = false;
91
+ context._rawTxItxBeforeNormalize = context.tx?.itx;
54
92
  const normalized = normalizeItx(context.tx.itx);
55
93
  if (!normalized) return next(new CustomError("INVALID_TX", "Failed to decode itx"));
56
94
  Object.defineProperty(context, "itx", {
57
95
  value: normalized.value,
58
- enumerable: true
96
+ enumerable: true,
97
+ configurable: true,
98
+ writable: true
59
99
  });
60
100
  Object.defineProperty(context, "txType", {
61
101
  value: normalized.typeUrl,
62
- enumerable: true
102
+ enumerable: true,
103
+ configurable: true,
104
+ writable: true
63
105
  });
64
106
  context.logger?.info("Tx decoded", {
65
107
  txBase64: context.txBase64,
@@ -2,7 +2,6 @@ import { CustomError } from "@ocap/util/lib/error";
2
2
  import { IBaseContext } from "@ocap/types";
3
3
 
4
4
  //#region src/pipes/decode-tx.d.ts
5
- declare function assertCanonicalActiveTx(context: IBaseContext): void;
6
- declare function DecodeTx(context: IBaseContext, next: (err?: CustomError) => void): void | Promise<void>;
5
+ declare function DecodeTx(context: IBaseContext, next: (err?: CustomError) => void): void;
7
6
  //#endregion
8
- export { assertCanonicalActiveTx, DecodeTx as default };
7
+ export { DecodeTx as default };
@@ -1,11 +1,9 @@
1
- import { isDedupHeightActive, tryResolveDedupHeightActiveSync } from "../helpers/dedup-height.mjs";
2
1
  import { name } from "../package.mjs";
3
2
  import { unwrapOpaqueAnyData } from "../helpers/unwrap-opaque-any.mjs";
4
- import get from "lodash/get.js";
3
+ import { toTxHash } from "@ocap/mcrypto";
5
4
  import { fromBase64, toUint8Array } from "@ocap/util";
6
5
  import { CustomError } from "@ocap/util/lib/error";
7
6
  import { decodeAny, encodeAny } from "@ocap/message";
8
- import { toTxHash } from "@ocap/mcrypto";
9
7
  import { CANONICAL_SELF_DESCRIBE_PREFIX, decodeTx, encodeTx } from "@ocap/message/cbor";
10
8
  import { decodeTx as decodeTx$1, encodeTx as encodeTx$1 } from "@ocap/message/protobuf";
11
9
  import { getListField, setListField } from "@ocap/util/lib/get-list-field";
@@ -68,39 +66,6 @@ function hasCborSelfDescribeTag(buf) {
68
66
  return buf.length >= CANONICAL_SELF_DESCRIBE_PREFIX.length && buf[0] === CANONICAL_SELF_DESCRIBE_PREFIX[0] && buf[1] === CANONICAL_SELF_DESCRIBE_PREFIX[1] && buf[2] === CANONICAL_SELF_DESCRIBE_PREFIX[2];
69
67
  }
70
68
  const NON_CANONICAL_MESSAGE = "Transaction encoding is not canonical";
71
- const V1_MULTISIG_TX_TYPES = new Set(["fg:t:exchange", "fg:t:exchange_v2"]);
72
- function assertCanonicalActiveTx(context) {
73
- if (!context?.txBase64) return;
74
- const txBuffer = toUint8Array(fromBase64(context.txBase64));
75
- const isCbor = hasCborSelfDescribeTag(txBuffer);
76
- const unsignedTx = cloneDeep(isCbor ? decodeTx(txBuffer) : decodeTx$1(txBuffer));
77
- unsignedTx.signature = void 0;
78
- const sigs = getListField(unsignedTx, "signatures");
79
- if (sigs.length > 0) {
80
- for (const sig of sigs) if (!isCanonicalSigData(sig.data, isCbor)) throw new CustomError("INVALID_TX", NON_CANONICAL_MESSAGE);
81
- try {
82
- setListField(unsignedTx, "signatures", sigs.map((x) => {
83
- const stripped = omit(x, ["signature", "extra"]);
84
- if (stripped.data) stripped.data = unwrapOpaqueAnyData(decodeAny(stripped.data));
85
- return stripped;
86
- }));
87
- } catch {
88
- throw new CustomError("INVALID_TX", "Can not decode base64 encoded transaction");
89
- }
90
- const unsignedBytes = isCbor ? encodeTx(unsignedTx) : encodeTx$1(unsignedTx);
91
- Object.defineProperty(context, "unsignedTxHash", {
92
- value: toTxHash(unsignedBytes),
93
- enumerable: true,
94
- configurable: true
95
- });
96
- const multiSignV2Txs = get(context, "config.transaction.multiSignV2Txs", []);
97
- const txType = context.txType;
98
- if (txType && !multiSignV2Txs.includes(txType)) {
99
- if (!V1_MULTISIG_TX_TYPES.has(txType)) throw new CustomError("INVALID_SIGNATURE", `Expect 0 multi signatures but found ${sigs.length}`);
100
- if (sigs.length > 1) throw new CustomError("INVALID_SIGNATURE", `Expect 1 multi signatures but found ${sigs.length}`);
101
- }
102
- }
103
- }
104
69
  function DecodeTx(context, next) {
105
70
  let nonCanonical = false;
106
71
  try {
@@ -115,85 +80,61 @@ function DecodeTx(context, next) {
115
80
  const unsignedTx = cloneDeep(tx);
116
81
  unsignedTx.signature = void 0;
117
82
  const sigs = getListField(unsignedTx, "signatures");
118
- const finalizeDecode = (dedupActive) => {
119
- if (sigs.length > 0) {
120
- if (dedupActive) {
121
- for (const sig of sigs) if (!isCanonicalSigData(sig.data, isCbor)) {
122
- nonCanonical = true;
123
- throw new CustomError("INVALID_TX", NON_CANONICAL_MESSAGE);
124
- }
125
- }
126
- setListField(unsignedTx, "signatures", sigs.map((x) => {
127
- const stripped = omit(x, ["signature", "extra"]);
128
- if (stripped.data) if (dedupActive) stripped.data = unwrapOpaqueAnyData(decodeAny(stripped.data));
129
- else try {
130
- stripped.data = unwrapOpaqueAnyData(decodeAny(stripped.data));
131
- } catch {}
132
- return stripped;
133
- }));
134
- }
135
- const unsignedBytes = isCbor ? encodeTx(unsignedTx) : encodeTx$1(unsignedTx);
136
- Object.defineProperty(context, "tx", {
137
- value: tx,
138
- enumerable: true,
139
- configurable: true
140
- });
141
- Object.defineProperty(context, "txEncoding", {
142
- value: isCbor ? "cbor" : "protobuf",
143
- enumerable: true,
144
- configurable: true
145
- });
146
- Object.defineProperty(context, "txSize", {
147
- value: Buffer.byteLength(txBuffer),
148
- enumerable: true,
149
- configurable: true
150
- });
151
- Object.defineProperty(context, "txHash", {
152
- value: toTxHash(txBuffer),
153
- enumerable: true,
154
- configurable: true
155
- });
156
- Object.defineProperty(context, "unsignedTxHash", {
157
- value: toTxHash(unsignedBytes),
158
- enumerable: true,
159
- configurable: true
160
- });
161
- const pinned = context.extra?.txTime;
162
- const pinnedMs = pinned === void 0 || pinned === null || pinned === "" ? NaN : new Date(pinned).getTime();
163
- Object.defineProperty(context, "txTime", {
164
- value: Number.isFinite(pinnedMs) ? new Date(pinnedMs).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
165
- enumerable: true,
166
- configurable: true
167
- });
168
- Object.defineProperty(context, "txBaseGas", {
169
- value: true,
170
- enumerable: true,
171
- writable: true,
172
- configurable: true
173
- });
174
- };
175
83
  if (sigs.length > 0) {
176
- const syncActive = tryResolveDedupHeightActiveSync(context);
177
- if (syncActive === null) return isDedupHeightActive(context).then((dedupActive) => {
178
- try {
179
- finalizeDecode(dedupActive);
180
- } catch (err) {
181
- debug("failed to decode transaction", {
182
- txBase64: context.txBase64,
183
- error: err
184
- });
185
- return next(new CustomError("INVALID_TX", nonCanonical ? NON_CANONICAL_MESSAGE : "Can not decode base64 encoded transaction"));
186
- }
187
- next();
188
- }, (err) => {
189
- debug("failed to resolve dedup height for transaction", {
190
- txBase64: context.txBase64,
191
- error: err
192
- });
193
- return next(err);
194
- });
195
- finalizeDecode(syncActive);
196
- } else finalizeDecode(true);
84
+ for (const sig of sigs) if (!isCanonicalSigData(sig.data, isCbor)) {
85
+ nonCanonical = true;
86
+ throw new CustomError("INVALID_TX", NON_CANONICAL_MESSAGE);
87
+ }
88
+ setListField(unsignedTx, "signatures", sigs.map((x) => {
89
+ const stripped = omit(x, ["signature", "extra"]);
90
+ if (stripped.data) stripped.data = unwrapOpaqueAnyData(decodeAny(stripped.data));
91
+ return stripped;
92
+ }));
93
+ }
94
+ const unsignedBytes = isCbor ? encodeTx(unsignedTx) : encodeTx$1(unsignedTx);
95
+ Object.defineProperty(context, "tx", {
96
+ value: tx,
97
+ enumerable: true,
98
+ configurable: true
99
+ });
100
+ Object.defineProperty(context, "txEncoding", {
101
+ value: isCbor ? "cbor" : "protobuf",
102
+ enumerable: true,
103
+ configurable: true
104
+ });
105
+ Object.defineProperty(context, "txSize", {
106
+ value: Buffer.byteLength(txBuffer),
107
+ enumerable: true,
108
+ configurable: true,
109
+ writable: true
110
+ });
111
+ context._extraSizeCounted = false;
112
+ context._preFlightWafScanned = false;
113
+ context._preFlightVerified = false;
114
+ context._preFlightSnapshotApplied = false;
115
+ Object.defineProperty(context, "txHash", {
116
+ value: toTxHash(txBuffer),
117
+ enumerable: true,
118
+ configurable: true
119
+ });
120
+ Object.defineProperty(context, "unsignedTxHash", {
121
+ value: toTxHash(unsignedBytes),
122
+ enumerable: true,
123
+ configurable: true
124
+ });
125
+ const pinned = context.extra?.txTime;
126
+ const pinnedMs = pinned === void 0 || pinned === null || pinned === "" ? NaN : new Date(pinned).getTime();
127
+ Object.defineProperty(context, "txTime", {
128
+ value: Number.isFinite(pinnedMs) ? new Date(pinnedMs).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
129
+ enumerable: true,
130
+ configurable: true
131
+ });
132
+ Object.defineProperty(context, "txBaseGas", {
133
+ value: true,
134
+ enumerable: true,
135
+ writable: true,
136
+ configurable: true
137
+ });
197
138
  } catch (err) {
198
139
  debug("failed to decode transaction", {
199
140
  txBase64: context.txBase64,
@@ -205,4 +146,4 @@ function DecodeTx(context, next) {
205
146
  }
206
147
 
207
148
  //#endregion
208
- export { assertCanonicalActiveTx, DecodeTx as default };
149
+ export { DecodeTx as default };
@@ -1,6 +1,6 @@
1
- import { account } from "@ocap/state";
2
- import { CustomError } from "@ocap/util/lib/error";
3
1
  import { types } from "@ocap/mcrypto";
2
+ import { CustomError } from "@ocap/util/lib/error";
3
+ import { account } from "@ocap/state";
4
4
  import { getListField } from "@ocap/util/lib/get-list-field";
5
5
  import set from "lodash/set.js";
6
6
  import { toTypeInfo } from "@arcblock/did";
@@ -1,8 +1,8 @@
1
1
  import { name } from "../package.mjs";
2
+ import { types } from "@ocap/mcrypto";
3
+ import { CustomError } from "@ocap/util/lib/error";
2
4
  import { account, tables } from "@ocap/state";
3
5
  import get from "lodash/get.js";
4
- import { CustomError } from "@ocap/util/lib/error";
5
- import { types } from "@ocap/mcrypto";
6
6
  import Debug from "debug";
7
7
  import set from "lodash/set.js";
8
8
  import { toTypeInfo, toTypeInfoStr } from "@arcblock/did";
@@ -61,7 +61,18 @@ function CreateExtractStatePipe({ from, to, table, status = "OK", message }) {
61
61
  return next(new CustomError(status, message ? message(missing, role || table || "") : `Invalid state extracted for ${role || table}: ${missing}`, { persist: true }));
62
62
  }
63
63
  }
64
- set(context, to, Array.isArray(address) ? result : result.shift());
64
+ const dedupedResult = Array.isArray(address) ? (() => {
65
+ const seen = /* @__PURE__ */ new Set();
66
+ return result.filter((r) => {
67
+ const stateObj = r;
68
+ const key = stateObj?.address || stateObj?.hash;
69
+ if (!key) return true;
70
+ if (seen.has(key)) return false;
71
+ seen.add(key);
72
+ return true;
73
+ });
74
+ })() : result;
75
+ set(context, to, Array.isArray(address) ? dedupedResult : result.shift());
65
76
  next();
66
77
  };
67
78
  }
@@ -0,0 +1,61 @@
1
+ import { PipeFunction } from "../runner.mjs";
2
+ import { IBaseContext, IReadyContext } from "@ocap/types";
3
+
4
+ //#region src/pipes/post-execution-invariant-gate.d.ts
5
+ declare const MAX_POST_EXECUTION_WRITE_SET_ENTRIES = 256;
6
+ declare const TRACKED_STATE_TABLES: readonly ["account", "stake", "token", "tokenFactory", "asset", "factory", "delegation", "rollup", "rollupBlock", "evidence", "balance"];
7
+ type TrackedStateTable = (typeof TRACKED_STATE_TABLES)[number];
8
+ interface IStateWriteTracker {
9
+ beforeStates: Map<TrackedStateTable, Map<string, Record<string, unknown> | null>>;
10
+ afterStates: Map<TrackedStateTable, Map<string, Record<string, unknown>>>;
11
+ writtenKeys: Map<TrackedStateTable, Set<string>>;
12
+ addressAliases: Map<string, string>;
13
+ totalWriteOps: number;
14
+ unauthorizedDeletions: number;
15
+ }
16
+ /**
17
+ * Canonicalizes a DID or hex address key so that `did:abt:` prefixes and
18
+ * Ethereum hex casing (`0xabc...` vs EIP-55 `0xAbC...`) always map to a single
19
+ * deterministic key across `beforeStates`, `afterStates`, `stateSnapshot`,
20
+ * and token balance maps.
21
+ */
22
+ declare function normalizeEntityKey(rawKey: unknown): string;
23
+ /**
24
+ * Installs a non-mutating Proxy interceptor over `context.statedb` so every
25
+ * state read (`get`) and state write (`create`, `update`, `updateOrCreate`)
26
+ * during protocol execution is captured in `context._stateWriteTracker`.
27
+ *
28
+ * Even if a protocol mutates a state record in `statedb` without assigning the
29
+ * resulting object back onto `context`, the interceptor captures both the
30
+ * pre-mutation snapshot and the post-mutation state for Gate 2 verification.
31
+ */
32
+ declare function installStateWriteInterceptor<TContext extends IBaseContext = IBaseContext>(context: TContext): IStateWriteTracker;
33
+ /**
34
+ * Rolls back all tracked `statedb` writes recorded in `context._stateWriteTracker`
35
+ * to their pre-execution `beforeStates` (or deletes newly created records).
36
+ *
37
+ * Used by the non-`runAsLambda` execution fallback path in `execute.ts` when a
38
+ * protocol or Gate 2 (`inspectPostExecutionInvariants`) fails after partial or
39
+ * complete `statedb` writes, guaranteeing that no invariant-violating state
40
+ * remains in `statedb` before `ensureGasFeePaid` runs.
41
+ */
42
+ declare function rollbackTrackedStateWrites<TContext extends IBaseContext = IBaseContext>(context: TContext): Promise<void>;
43
+ /**
44
+ * Synchronous/stateless Post-Execution Invariant Gate (Gate 2) verifier.
45
+ *
46
+ * Enforces the 5 Hard Invariants across the transaction's before/after state set:
47
+ * 1. Token Zero-Sum Conservation across `account.tokens + stake.tokens + stake.revokedTokens + tokenFactory.reserveBalance`
48
+ * 2. Official Token (`config.token.address`) Immutable Supply & Non-Negative Canonical Balances
49
+ * 3. Asset Conservation, Non-Destruction (`readonly: true`, `transferrable: false`, `consumedTime`) & Stake Asset Bijection
50
+ * 4. Protocol Stake Protection (`revocable === false` cannot be unlocked or drained)
51
+ * 5. Tombstone Account Protection (`migratedTo.length > 0`), Sender Nonce Monotonicity & RW-Set Containment
52
+ */
53
+ declare function inspectPostExecutionInvariants(context: IBaseContext): void;
54
+ /**
55
+ * Pipeline pipe wrapper around `inspectPostExecutionInvariants`.
56
+ * Can be used directly in a `Runner` pipeline or invoked by `execute.ts`
57
+ * immediately after `protocol.run` and before `statedb.tx.create`.
58
+ */
59
+ declare function CreatePostExecutionInvariantGatePipe<TContext extends IReadyContext = IReadyContext>(): PipeFunction<TContext>;
60
+ //#endregion
61
+ export { CreatePostExecutionInvariantGatePipe, CreatePostExecutionInvariantGatePipe as default, IStateWriteTracker, MAX_POST_EXECUTION_WRITE_SET_ENTRIES, TRACKED_STATE_TABLES, TrackedStateTable, inspectPostExecutionInvariants, installStateWriteInterceptor, normalizeEntityKey, rollbackTrackedStateWrites };