@ocap/tx-protocols 1.30.24 → 1.30.25

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 (101) hide show
  1. package/esm/execute.d.mts +6 -2
  2. package/esm/execute.mjs +214 -25
  3. package/esm/index.d.mts +25 -2
  4. package/esm/index.mjs +2 -2
  5. package/esm/pipes/ensure-cost.mjs +2 -2
  6. package/esm/pipes/write-ledger.mjs +7 -0
  7. package/esm/protocols/account/delegate.mjs +7 -6
  8. package/esm/protocols/account/migrate.mjs +2 -2
  9. package/esm/protocols/account/revoke-delegate.mjs +1 -1
  10. package/esm/protocols/asset/acquire-v2.mjs +25 -6
  11. package/esm/protocols/asset/acquire-v3.d.mts +11 -1
  12. package/esm/protocols/asset/acquire-v3.mjs +78 -9
  13. package/esm/protocols/asset/consume.mjs +1 -1
  14. package/esm/protocols/asset/create.mjs +1 -1
  15. package/esm/protocols/asset/mint.mjs +8 -2
  16. package/esm/protocols/asset/pipes/verify-itx-address.mjs +1 -1
  17. package/esm/protocols/asset/update.mjs +1 -1
  18. package/esm/protocols/factory/create.mjs +4 -3
  19. package/esm/protocols/governance/claim-stake.mjs +2 -2
  20. package/esm/protocols/governance/return-stake.mjs +2 -2
  21. package/esm/protocols/governance/revoke-stake.mjs +2 -2
  22. package/esm/protocols/governance/slash-stake.mjs +2 -2
  23. package/esm/protocols/governance/stake.mjs +2 -2
  24. package/esm/protocols/rollup/claim-reward.mjs +5 -4
  25. package/esm/protocols/rollup/close.mjs +1 -1
  26. package/esm/protocols/rollup/create-block.mjs +1 -1
  27. package/esm/protocols/rollup/create.mjs +1 -1
  28. package/esm/protocols/rollup/join.mjs +2 -2
  29. package/esm/protocols/rollup/leave.mjs +1 -1
  30. package/esm/protocols/rollup/migrate.mjs +1 -1
  31. package/esm/protocols/rollup/pause.mjs +1 -1
  32. package/esm/protocols/rollup/pipes/verify-evidence.mjs +5 -2
  33. package/esm/protocols/rollup/pipes/verify-signers.mjs +5 -3
  34. package/esm/protocols/rollup/resume.mjs +1 -1
  35. package/esm/protocols/rollup/update.mjs +4 -4
  36. package/esm/protocols/token/create.mjs +2 -2
  37. package/esm/protocols/token/deposit-v2.mjs +2 -2
  38. package/esm/protocols/token/withdraw-v2.mjs +13 -9
  39. package/esm/protocols/token-factory/burn.mjs +4 -4
  40. package/esm/protocols/token-factory/create.mjs +2 -2
  41. package/esm/protocols/token-factory/mint.mjs +2 -2
  42. package/esm/protocols/token-factory/update.mjs +7 -5
  43. package/esm/protocols/trade/exchange-v2.d.mts +3 -1
  44. package/esm/protocols/trade/exchange-v2.mjs +69 -11
  45. package/esm/protocols/trade/transfer-v2.mjs +39 -23
  46. package/esm/protocols/trade/transfer-v3.d.mts +11 -1
  47. package/esm/protocols/trade/transfer-v3.mjs +102 -11
  48. package/esm/tx-timer.d.mts +5 -0
  49. package/esm/tx-timer.mjs +13 -0
  50. package/esm/util.mjs +2 -1
  51. package/lib/execute.cjs +211 -20
  52. package/lib/execute.d.cts +6 -2
  53. package/lib/index.cjs +3 -1
  54. package/lib/index.d.cts +25 -2
  55. package/lib/pipes/ensure-cost.cjs +2 -2
  56. package/lib/pipes/write-ledger.cjs +7 -0
  57. package/lib/protocols/account/delegate.cjs +7 -6
  58. package/lib/protocols/account/migrate.cjs +2 -2
  59. package/lib/protocols/account/revoke-delegate.cjs +1 -1
  60. package/lib/protocols/asset/acquire-v2.cjs +24 -5
  61. package/lib/protocols/asset/acquire-v3.cjs +77 -8
  62. package/lib/protocols/asset/acquire-v3.d.cts +11 -1
  63. package/lib/protocols/asset/consume.cjs +1 -1
  64. package/lib/protocols/asset/create.cjs +1 -1
  65. package/lib/protocols/asset/mint.cjs +7 -1
  66. package/lib/protocols/asset/pipes/verify-itx-address.cjs +1 -1
  67. package/lib/protocols/asset/update.cjs +1 -1
  68. package/lib/protocols/factory/create.cjs +4 -3
  69. package/lib/protocols/governance/claim-stake.cjs +2 -2
  70. package/lib/protocols/governance/return-stake.cjs +2 -2
  71. package/lib/protocols/governance/revoke-stake.cjs +2 -2
  72. package/lib/protocols/governance/slash-stake.cjs +2 -2
  73. package/lib/protocols/governance/stake.cjs +2 -2
  74. package/lib/protocols/rollup/claim-reward.cjs +5 -4
  75. package/lib/protocols/rollup/close.cjs +1 -1
  76. package/lib/protocols/rollup/create-block.cjs +1 -1
  77. package/lib/protocols/rollup/create.cjs +1 -1
  78. package/lib/protocols/rollup/join.cjs +2 -2
  79. package/lib/protocols/rollup/leave.cjs +1 -1
  80. package/lib/protocols/rollup/migrate.cjs +1 -1
  81. package/lib/protocols/rollup/pause.cjs +1 -1
  82. package/lib/protocols/rollup/pipes/verify-evidence.cjs +5 -2
  83. package/lib/protocols/rollup/pipes/verify-signers.cjs +5 -4
  84. package/lib/protocols/rollup/resume.cjs +1 -1
  85. package/lib/protocols/rollup/update.cjs +4 -4
  86. package/lib/protocols/token/create.cjs +2 -2
  87. package/lib/protocols/token/deposit-v2.cjs +2 -2
  88. package/lib/protocols/token/withdraw-v2.cjs +13 -9
  89. package/lib/protocols/token-factory/burn.cjs +4 -4
  90. package/lib/protocols/token-factory/create.cjs +2 -2
  91. package/lib/protocols/token-factory/mint.cjs +2 -2
  92. package/lib/protocols/token-factory/update.cjs +7 -5
  93. package/lib/protocols/trade/exchange-v2.cjs +68 -10
  94. package/lib/protocols/trade/exchange-v2.d.cts +3 -1
  95. package/lib/protocols/trade/transfer-v2.cjs +39 -23
  96. package/lib/protocols/trade/transfer-v3.cjs +101 -10
  97. package/lib/protocols/trade/transfer-v3.d.cts +11 -1
  98. package/lib/tx-timer.cjs +13 -0
  99. package/lib/tx-timer.d.cts +5 -0
  100. package/lib/util.cjs +2 -1
  101. package/package.json +16 -16
package/esm/execute.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { TxTimer } from "./tx-timer.mjs";
2
- import { CustomError } from "@ocap/util/lib/error";
3
2
  import { Blacklist } from "@ocap/state";
3
+ import { CustomError } from "@ocap/util/lib/error";
4
4
  import { IAccountState, IGasContext } from "@ocap/types";
5
5
 
6
6
  //#region src/execute.d.ts
@@ -34,6 +34,8 @@ interface IExecutionContext extends IGasContext {
34
34
  stateCommitHash?: string;
35
35
  /** Transaction execution timer */
36
36
  timer?: TxTimer;
37
+ /** Per-invocation identifier for in-flight deduplication across retries */
38
+ executionId?: symbol;
37
39
  }
38
40
  /** Protocol runner interface */
39
41
  interface IProtocolRunner {
@@ -53,9 +55,11 @@ interface IExecuteOptions {
53
55
  }
54
56
  /** Execute function type */
55
57
  type ExecuteFn = (context: IExecutionContext, protocols: ProtocolsMap, isRetrySupported?: boolean) => Promise<IExecutionContext>;
58
+ declare const toUnsignedEvidenceKey: (unsignedTxHash: string) => string;
59
+ declare const UNSIGNED_TX_EVIDENCE_DATA_PREFIX = "unsigned-tx:";
56
60
  declare const createExecute: ({
57
61
  filter,
58
62
  runAsLambda
59
63
  }: IExecuteOptions) => ExecuteFn;
60
64
  //#endregion
61
- export { createExecute as default };
65
+ export { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, createExecute as default, toUnsignedEvidenceKey };
package/esm/execute.mjs CHANGED
@@ -2,7 +2,10 @@ import ensure_cost_default from "./pipes/ensure-cost.mjs";
2
2
  import ensure_gas_default from "./pipes/ensure-gas.mjs";
3
3
  import { WriteLedger } from "./pipes/write-ledger.mjs";
4
4
  import { TxTimer } from "./tx-timer.mjs";
5
- import { Runner, pipes } from "@ocap/tx-pipeline";
5
+ import { toTxHash } from "@ocap/mcrypto";
6
+ import { PENDING_DEDUP_ACTIVATION_HEIGHT, account, evidence, parseNonceBn, resolveDedupActivationHeight } from "@ocap/state";
7
+ import { Runner, assertCanonicalActiveTx, isDedupHeightActive, pipes, resolveEffectiveHeight } from "@ocap/tx-pipeline";
8
+ import { BN } from "@ocap/util";
6
9
  import { CustomError } from "@ocap/util/lib/error";
7
10
  import camelCase from "lodash/camelCase.js";
8
11
  import get from "lodash/get.js";
@@ -37,8 +40,119 @@ const flushEvents = (context, extra = {}) => {
37
40
  context.events = [];
38
41
  };
39
42
  const shouldPersistTx = (err) => !err || Boolean(get(err, "props.persist"));
43
+ const toUnsignedEvidenceKey = (unsignedTxHash) => toTxHash(Buffer.from(`unsigned-tx:${unsignedTxHash}`));
44
+ const UNSIGNED_TX_EVIDENCE_DATA_PREFIX = "unsigned-tx:";
45
+ const hasEvidenceStore = (statedb) => Boolean(statedb && typeof statedb.evidence?.get === "function" && typeof statedb.evidence?.create === "function");
46
+ const stateDbSyncMap = /* @__PURE__ */ new WeakMap();
47
+ const getOrCreateSyncState = (target) => {
48
+ let state = stateDbSyncMap.get(target);
49
+ if (!state) {
50
+ state = {
51
+ inFlightUnsignedTxHashes: /* @__PURE__ */ new Map(),
52
+ inFlightTxHashes: /* @__PURE__ */ new Map(),
53
+ preWriteLockPromise: Promise.resolve()
54
+ };
55
+ stateDbSyncMap.set(target, state);
56
+ }
57
+ return state;
58
+ };
59
+ /**
60
+ * Determine whether `unsignedTxHash` deduplication in `statedb.evidence` is active
61
+ * for the current execution context.
62
+ */
63
+ const isUnsignedDedupActive = async (context) => {
64
+ if (!context.unsignedTxHash) return false;
65
+ return isDedupHeightActive(context);
66
+ };
40
67
  const createExecute = ({ filter, runAsLambda }) => {
68
+ const fallbackSyncTarget = {};
69
+ const getSyncState = (context) => {
70
+ return getOrCreateSyncState((context?.statedb && typeof context.statedb === "object" ? context.statedb : null) || (context?.ledger && typeof context.ledger === "object" ? context.ledger : null) || fallbackSyncTarget);
71
+ };
72
+ const withPreWriteLock = async (context, fn) => {
73
+ const syncState = getSyncState(context);
74
+ const prev = syncState.preWriteLockPromise;
75
+ let release;
76
+ syncState.preWriteLockPromise = new Promise((r) => {
77
+ release = r;
78
+ });
79
+ await prev;
80
+ try {
81
+ return await fn();
82
+ } finally {
83
+ release();
84
+ }
85
+ };
86
+ const releaseInFlight = (execId, ...contexts) => {
87
+ for (const c of contexts) {
88
+ const syncState = getSyncState(c);
89
+ if (c?.txHash && syncState.inFlightTxHashes.get(c.txHash) === execId) syncState.inFlightTxHashes.delete(c.txHash);
90
+ if (c?.unsignedTxHash && syncState.inFlightUnsignedTxHashes.get(c.unsignedTxHash) === execId) syncState.inFlightUnsignedTxHashes.delete(c.unsignedTxHash);
91
+ }
92
+ };
93
+ const runSinglePipe = (pipeFn, ctx) => new Promise((resolve, reject) => {
94
+ Promise.resolve(pipeFn(ctx, (err) => {
95
+ if (err) return reject(err);
96
+ resolve();
97
+ })).catch(reject);
98
+ });
99
+ const hasCommittedUnsignedTx = async (context) => {
100
+ if (!context.unsignedTxHash || !hasEvidenceStore(context.statedb)) return false;
101
+ const unsignedKey = toUnsignedEvidenceKey(context.unsignedTxHash);
102
+ const exist = await context.statedb.evidence.get(unsignedKey, { txn: context.txn });
103
+ return Boolean(exist);
104
+ };
105
+ const recordUnsignedTxInStateDb = async (context, txHash) => {
106
+ if (!context.unsignedTxHash || !hasEvidenceStore(context.statedb)) return;
107
+ if (!await isUnsignedDedupActive(context)) return;
108
+ const unsignedKey = toUnsignedEvidenceKey(context.unsignedTxHash);
109
+ if (!await context.statedb.evidence.get(unsignedKey, { txn: context.txn })) {
110
+ const evState = evidence.create({
111
+ hash: unsignedKey,
112
+ data: `${UNSIGNED_TX_EVIDENCE_DATA_PREFIX}${txHash}`
113
+ }, {
114
+ txHash,
115
+ txTime: context.txTime || (/* @__PURE__ */ new Date(0)).toISOString()
116
+ });
117
+ await context.statedb.evidence.create(unsignedKey, evState, { txn: context.txn });
118
+ }
119
+ };
120
+ /**
121
+ * Post-activation sender nonce precheck, run under the pre-write lock BEFORE WriteLedger.
122
+ *
123
+ * Every persisted pre-activation tx has `nonce <= sender.nonce` once the offline migration
124
+ * restored each account's max historical nonce. Rejecting stale nonces here (instead of
125
+ * relying on each protocol's `account.update` after WriteLedger) means a signature-malleated
126
+ * twin of ANY historical tx is refused without appending a ledger row and without depending
127
+ * on every protocol path updating the sender nonce. This is what lets the migration skip the
128
+ * full historical `unsigned-tx:` evidence backfill.
129
+ *
130
+ * - Sender account missing (first tx, e.g. declare) or non-account sender: skip; the protocol
131
+ * decides as before.
132
+ * - Sender migrated (statedb resolves `tx.from` to its successor): reject like
133
+ * VerifyAccountMigration, but before the ledger write.
134
+ *
135
+ * Activation boundary: only runs when the tx is already active at the expected sequence. A tx
136
+ * that is pre-activation here but lands on the activation sequence after WriteLedger skips this
137
+ * precheck once; the post-write nonce/dedup checks and the protocol's account.update still apply.
138
+ */
139
+ const assertSenderNonceFresh = async (context) => {
140
+ const from = context.tx?.from;
141
+ const accountStore = context.statedb?.account;
142
+ if (!from || typeof accountStore?.get !== "function") return;
143
+ const senderState = await accountStore.get(from, context);
144
+ if (!senderState) return;
145
+ if (senderState.address !== from && senderState.address !== account.ensureChecksumAddress(from)) throw new CustomError("ACCOUNT_MIGRATED", `account ${from} is migrated`);
146
+ const incomingNonceBn = parseNonceBn(context.tx?.nonce);
147
+ const currentNonceBn = parseNonceBn(senderState.nonce) ?? new BN(0);
148
+ if (!incomingNonceBn || incomingNonceBn.lte(currentNonceBn)) throw new CustomError("INVALID_NONCE", "nonce must be greater in newer transactions");
149
+ };
41
150
  const pre = new Runner("pre-execute");
151
+ pre.use(async (context, next) => {
152
+ const dedupHeight = resolveDedupActivationHeight(context);
153
+ if (dedupHeight > 0 && dedupHeight < PENDING_DEDUP_ACTIVATION_HEIGHT) await resolveEffectiveHeight(context);
154
+ return next();
155
+ });
42
156
  pre.use(pipes.DecodeTx);
43
157
  pre.use(pipes.VerifyBlocked({
44
158
  filter,
@@ -48,26 +162,81 @@ const createExecute = ({ filter, runAsLambda }) => {
48
162
  pre.use(pipes.VerifyTx);
49
163
  pre.use(pipes.VerifyServiceFee);
50
164
  pre.use(async (context, next) => {
165
+ const syncState = getSyncState(context);
166
+ const execId = context.executionId;
167
+ const inFlightTxOwner = context.txHash ? syncState.inFlightTxHashes.get(context.txHash) : void 0;
168
+ if (inFlightTxOwner && inFlightTxOwner !== execId) return next(new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction"));
51
169
  if (filter.has(context.txHash)) {
52
170
  if (await context.statedb.tx.get(context.txHash, context)) return next(new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction"));
53
171
  }
172
+ if (await isUnsignedDedupActive(context)) {
173
+ const inFlightUnsignedOwner = context.unsignedTxHash ? syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash) : void 0;
174
+ if (inFlightUnsignedOwner && inFlightUnsignedOwner !== execId || await hasCommittedUnsignedTx(context)) return next(new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction"));
175
+ }
54
176
  filter.add(context.txHash);
55
177
  return next();
56
178
  });
57
179
  pre.use(pipes.VerifyTxSize);
58
180
  pre.use(pipes.VerifySignature);
59
- pre.use(WriteLedger);
181
+ pre.use(async (context, next) => {
182
+ try {
183
+ await withPreWriteLock(context, async () => {
184
+ const syncState = getSyncState(context);
185
+ if (context.height === void 0 && !context.ledgerSequence) {
186
+ delete context.expectedLedgerSequence;
187
+ delete context.dedupActive;
188
+ const dedupHeight = resolveDedupActivationHeight(context);
189
+ if (dedupHeight > 0 && dedupHeight < PENDING_DEDUP_ACTIVATION_HEIGHT) await resolveEffectiveHeight(context);
190
+ }
191
+ const isActiveNow = await isUnsignedDedupActive(context);
192
+ context.dedupActive = isActiveNow;
193
+ const execId = context.executionId || Symbol("tx-exec");
194
+ context.executionId = execId;
195
+ if (context.txHash) {
196
+ const existingTxOwner = syncState.inFlightTxHashes.get(context.txHash);
197
+ if (existingTxOwner && existingTxOwner !== execId) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
198
+ }
199
+ if (isActiveNow) {
200
+ assertCanonicalActiveTx(context);
201
+ const nonceBn = parseNonceBn(context.tx?.nonce);
202
+ if (!nonceBn || nonceBn.lte(new BN(0))) throw new CustomError("INVALID_NONCE", "tx.nonce should be a positive integer");
203
+ await assertSenderNonceFresh(context);
204
+ if (context.unsignedTxHash) {
205
+ const existingUnsignedOwner = syncState.inFlightUnsignedTxHashes.get(context.unsignedTxHash);
206
+ if (existingUnsignedOwner && existingUnsignedOwner !== execId) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
207
+ }
208
+ if (await hasCommittedUnsignedTx(context)) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
209
+ }
210
+ if (context.txHash) syncState.inFlightTxHashes.set(context.txHash, execId);
211
+ if (isActiveNow && context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
212
+ await runSinglePipe(WriteLedger, context);
213
+ delete context.dedupActive;
214
+ const isActiveAfterWrite = await isUnsignedDedupActive(context);
215
+ context.dedupActive = isActiveAfterWrite;
216
+ if (isActiveAfterWrite) {
217
+ if (!isActiveNow) assertCanonicalActiveTx(context);
218
+ const nonceBn = parseNonceBn(context.tx?.nonce);
219
+ if (!nonceBn || nonceBn.lte(new BN(0))) throw new CustomError("INVALID_NONCE", "tx.nonce should be a positive integer");
220
+ if (await hasCommittedUnsignedTx(context)) throw new CustomError("DUPLICATE_TX", "Can not execute duplicate transaction");
221
+ if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
222
+ }
223
+ });
224
+ return next();
225
+ } catch (err) {
226
+ return next(err);
227
+ }
228
+ });
60
229
  const ensureGasFeePaid = (context) => {
61
230
  const gasRunner = new Runner("ensure-gas-fee-paid");
62
231
  gasRunner.use(ensureTxGas);
63
232
  gasRunner.use(ensureTxCost);
64
233
  gasRunner.use(async (ctx, next) => {
65
- const { tx, statedb, senderUpdates, updateVaults } = ctx;
66
- if (ctx.senderState && ctx.states && tx) {
234
+ const { tx: tx$1, statedb, senderUpdates, updateVaults } = ctx;
235
+ if (ctx.senderState && ctx.states && tx$1) {
67
236
  const senderState = ctx.stateSnapshot?.[ctx.senderState.address] || ctx.senderState;
68
237
  const updates = ctx.states.account.update(senderState, {
69
- nonce: tx.nonce,
70
- pk: tx.pk,
238
+ nonce: tx$1.nonce,
239
+ pk: tx$1.pk,
71
240
  ...senderUpdates
72
241
  }, ctx);
73
242
  await statedb.account.update(senderState.address, updates, ctx);
@@ -118,6 +287,7 @@ const createExecute = ({ filter, runAsLambda }) => {
118
287
  txState = states.tx.create(context, txStatus);
119
288
  }
120
289
  await context.statedb.tx.create(txState.hash, txState, context);
290
+ await recordUnsignedTxInStateDb(context, txState.hash);
121
291
  context.timer?.mark("txstate");
122
292
  context.timer?.mark("commit");
123
293
  flushEvents(context, { txState });
@@ -155,6 +325,8 @@ const createExecute = ({ filter, runAsLambda }) => {
155
325
  });
156
326
  });
157
327
  if (typeof runAsLambda === "function") return async (context, protocols) => {
328
+ const executionId = Symbol("tx-exec");
329
+ context.executionId = executionId;
158
330
  let ctx = context;
159
331
  context.timer = context.timer || new TxTimer();
160
332
  let entryFinalized = false;
@@ -172,14 +344,24 @@ const createExecute = ({ filter, runAsLambda }) => {
172
344
  "extra",
173
345
  "logger",
174
346
  "ledgerSequence",
175
- "timer"
347
+ "height",
348
+ "timer",
349
+ "executionId"
176
350
  ]);
177
351
  ctx.txn = txn;
352
+ if (savedLedgerSequence !== void 0) ctx.ledgerSequence = savedLedgerSequence;
178
353
  ctx.timer?.mark("lockWait");
179
- await execute(ctx, protocols, true);
180
- if (ctx.ledgerSequence && !savedLedgerSequence) savedLedgerSequence = ctx.ledgerSequence;
354
+ try {
355
+ await execute(ctx, protocols, true);
356
+ } finally {
357
+ if (ctx.ledgerSequence && !savedLedgerSequence) {
358
+ savedLedgerSequence = ctx.ledgerSequence;
359
+ context.ledgerSequence = ctx.ledgerSequence;
360
+ }
361
+ }
181
362
  const state = getStates(context).tx.create(ctx, "OK");
182
363
  await context.statedb.tx.create(state.hash, state, ctx);
364
+ await recordUnsignedTxInStateDb(ctx, state.hash);
183
365
  ctx.timer?.mark("txstate");
184
366
  return state;
185
367
  }, {
@@ -249,6 +431,7 @@ const createExecute = ({ filter, runAsLambda }) => {
249
431
  await ensureGasFeePaid(ctx);
250
432
  const state = getStates(context).tx.create(ctx, txStatus);
251
433
  await ctx.statedb.tx.create(state.hash, state, ctx);
434
+ await recordUnsignedTxInStateDb(ctx, state.hash);
252
435
  ctx.timer?.mark("txstate");
253
436
  return state;
254
437
  }, {
@@ -345,31 +528,37 @@ const createExecute = ({ filter, runAsLambda }) => {
345
528
  }
346
529
  }
347
530
  merge(context, ctx);
531
+ releaseInFlight(executionId, ctx, context);
348
532
  }
349
533
  return ctx;
350
534
  };
351
535
  return async (context, protocols) => {
536
+ const executionId = Symbol("tx-exec");
537
+ context.executionId = executionId;
352
538
  context.timer = context.timer || new TxTimer();
353
- const result = await execute(context, protocols);
354
- if (result.ledger && result.txHash && result.ledgerSequence && result.txBase64) try {
355
- await result.ledger.finalizeEntry(result.txHash, "", result.ledgerSequence, result.txBase64);
356
- } catch (err) {
357
- result.logger?.error("Failed to finalize ledger entry (fallback)", {
358
- txHash: result.txHash,
359
- error: err
539
+ try {
540
+ return await execute(context, protocols);
541
+ } finally {
542
+ releaseInFlight(executionId, context);
543
+ if (context.ledger && context.txHash && context.ledgerSequence && context.txBase64) try {
544
+ await context.ledger.finalizeEntry(context.txHash, "", context.ledgerSequence, context.txBase64);
545
+ } catch (err) {
546
+ context.logger?.error("Failed to finalize ledger entry (fallback)", {
547
+ txHash: context.txHash,
548
+ error: err
549
+ });
550
+ }
551
+ context.timer?.mark("finalize");
552
+ context.ledger?.createCheckpointIfNeeded()?.catch((err) => {
553
+ context.logger?.error("Background checkpoint creation failed", {
554
+ txHash: context.txHash,
555
+ error: err
556
+ });
360
557
  });
361
558
  }
362
- result.timer?.mark("finalize");
363
- result.ledger?.createCheckpointIfNeeded()?.catch((err) => {
364
- result.logger?.error("Background checkpoint creation failed", {
365
- txHash: result.txHash,
366
- error: err
367
- });
368
- });
369
- return result;
370
559
  };
371
560
  };
372
561
  var execute_default = createExecute;
373
562
 
374
563
  //#endregion
375
- export { execute_default as default };
564
+ export { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, execute_default as default, toUnsignedEvidenceKey };
package/esm/index.d.mts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { COUNTER_NAMES, CounterName, QueueState, STAGE_LABELS, StageLabel, TxMeta, TxStatus, TxTimer, TxTimerSummaryV2 } from "./tx-timer.mjs";
2
+ import { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, toUnsignedEvidenceKey } from "./execute.mjs";
2
3
  import { TokenInput } from "./protocols/trade/transfer-v2.mjs";
3
4
  import { MultiInput } from "./protocols/trade/transfer-v3.mjs";
4
5
  import { TokenInput as TokenInput$1 } from "./protocols/trade/exchange-v2.mjs";
@@ -18,8 +19,8 @@ import { MultiInput as MultiInput$5, TokenCondition as TokenCondition$2 } from "
18
19
  import { TokenChange as TokenChange$1 } from "./protocols/rollup/create-block.mjs";
19
20
  import { TokenChange as TokenChange$2 } from "./protocols/rollup/claim-reward.mjs";
20
21
  import { WriteLedger } from "./pipes/write-ledger.mjs";
21
- import * as _ocap_tx_pipeline0 from "@ocap/tx-pipeline";
22
22
  import * as states from "@ocap/state";
23
+ import * as _ocap_tx_pipeline0 from "@ocap/tx-pipeline";
23
24
  import * as _ocap_util0 from "@ocap/util";
24
25
  import * as _ocap_message0 from "@ocap/message";
25
26
  import * as _ocap_types0 from "@ocap/types";
@@ -78,6 +79,11 @@ declare const createExecutor: ({
78
79
  outputAssets?: string[];
79
80
  tokenStates?: _ocap_types0.ITokenState[];
80
81
  assetStates?: _ocap_types0.IAssetState[];
82
+ delegatorState?: _ocap_types0.IAccountState;
83
+ delegationState?: _ocap_types0.IDelegateState;
84
+ msSignerStates?: _ocap_types0.IAccountState[];
85
+ delegatorStates?: (_ocap_types0.IAccountState | null)[];
86
+ delegationStates?: _ocap_types0.IDelegateState[];
81
87
  }>;
82
88
  exchangeV2: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TExchangeV2Tx> & _ocap_types0.IWithSender & _ocap_types0.IWithReceiver & Partial<_ocap_types0.IWithDelegator> & Partial<_ocap_types0.IWithSigners> & Partial<_ocap_types0.IWithDelegation> & {
83
89
  senderAssets?: string[];
@@ -95,6 +101,7 @@ declare const createExecutor: ({
95
101
  };
96
102
  tokenStates?: _ocap_types0.ITokenState[];
97
103
  receiver?: string;
104
+ delegationStates?: _ocap_types0.IDelegateState[];
98
105
  priv?: {
99
106
  senderAssets?: _ocap_types0.IAssetState[];
100
107
  receiverAssets?: _ocap_types0.IAssetState[];
@@ -192,6 +199,11 @@ declare const createExecutor: ({
192
199
  mintedAsset?: Record<string, unknown>;
193
200
  mintedAddress?: string;
194
201
  tokenUpdates?: Record<string, string>;
202
+ delegatorState?: _ocap_types0.IAccountState;
203
+ delegationState?: _ocap_types0.IDelegateState;
204
+ msSignerStates?: _ocap_types0.IAccountState[];
205
+ delegatorStates?: (_ocap_types0.IAccountState | null)[];
206
+ delegationStates?: _ocap_types0.IDelegateState[];
195
207
  }>;
196
208
  mintAsset: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TMintAssetTx> & Partial<_ocap_types0.IWithSender> & Partial<_ocap_types0.IWithFactory> & Partial<_ocap_types0.IWithOwner> & Partial<_ocap_types0.IWithReceiver> & {
197
209
  duplicateAsset?: _ocap_types0.IAssetState;
@@ -437,6 +449,11 @@ declare const defaultExecutor: {
437
449
  outputAssets?: string[];
438
450
  tokenStates?: _ocap_types0.ITokenState[];
439
451
  assetStates?: _ocap_types0.IAssetState[];
452
+ delegatorState?: _ocap_types0.IAccountState;
453
+ delegationState?: _ocap_types0.IDelegateState;
454
+ msSignerStates?: _ocap_types0.IAccountState[];
455
+ delegatorStates?: (_ocap_types0.IAccountState | null)[];
456
+ delegationStates?: _ocap_types0.IDelegateState[];
440
457
  }>;
441
458
  exchangeV2: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TExchangeV2Tx> & _ocap_types0.IWithSender & _ocap_types0.IWithReceiver & Partial<_ocap_types0.IWithDelegator> & Partial<_ocap_types0.IWithSigners> & Partial<_ocap_types0.IWithDelegation> & {
442
459
  senderAssets?: string[];
@@ -454,6 +471,7 @@ declare const defaultExecutor: {
454
471
  };
455
472
  tokenStates?: _ocap_types0.ITokenState[];
456
473
  receiver?: string;
474
+ delegationStates?: _ocap_types0.IDelegateState[];
457
475
  priv?: {
458
476
  senderAssets?: _ocap_types0.IAssetState[];
459
477
  receiverAssets?: _ocap_types0.IAssetState[];
@@ -551,6 +569,11 @@ declare const defaultExecutor: {
551
569
  mintedAsset?: Record<string, unknown>;
552
570
  mintedAddress?: string;
553
571
  tokenUpdates?: Record<string, string>;
572
+ delegatorState?: _ocap_types0.IAccountState;
573
+ delegationState?: _ocap_types0.IDelegateState;
574
+ msSignerStates?: _ocap_types0.IAccountState[];
575
+ delegatorStates?: (_ocap_types0.IAccountState | null)[];
576
+ delegationStates?: _ocap_types0.IDelegateState[];
554
577
  }>;
555
578
  mintAsset: _ocap_tx_pipeline0.Runner<_ocap_types0.IReadyContext<_ocap_types0.TMintAssetTx> & Partial<_ocap_types0.IWithSender> & Partial<_ocap_types0.IWithFactory> & Partial<_ocap_types0.IWithOwner> & Partial<_ocap_types0.IWithReceiver> & {
556
579
  duplicateAsset?: _ocap_types0.IAssetState;
@@ -757,4 +780,4 @@ declare const defaultExecutor: {
757
780
  };
758
781
  declare const execute: (context: unknown, done?: (err: Error | null, res?: unknown) => void) => any;
759
782
  //#endregion
760
- export { COUNTER_NAMES, type CounterName, type QueueState, STAGE_LABELS, type StageLabel, type TxMeta, type TxStatus, TxTimer, type TxTimerSummaryV2, WriteLedger, createExecutor, defaultExecutor as default, execute };
783
+ export { COUNTER_NAMES, type CounterName, type QueueState, STAGE_LABELS, type StageLabel, type TxMeta, type TxStatus, TxTimer, type TxTimerSummaryV2, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, createExecutor, defaultExecutor as default, execute, toUnsignedEvidenceKey };
package/esm/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { WriteLedger } from "./pipes/write-ledger.mjs";
2
2
  import { COUNTER_NAMES, STAGE_LABELS, TxTimer } from "./tx-timer.mjs";
3
- import execute_default from "./execute.mjs";
3
+ import execute_default, { UNSIGNED_TX_EVIDENCE_DATA_PREFIX, toUnsignedEvidenceKey } from "./execute.mjs";
4
4
  import delegate_default from "./protocols/account/delegate.mjs";
5
5
  import migrate_default from "./protocols/account/migrate.mjs";
6
6
  import revoke_delegate_default from "./protocols/account/revoke-delegate.mjs";
@@ -99,4 +99,4 @@ const { execute } = defaultExecutor;
99
99
  var src_default = defaultExecutor;
100
100
 
101
101
  //#endregion
102
- export { COUNTER_NAMES, STAGE_LABELS, TxTimer, WriteLedger, createExecutor, src_default as default, execute };
102
+ export { COUNTER_NAMES, STAGE_LABELS, TxTimer, UNSIGNED_TX_EVIDENCE_DATA_PREFIX, WriteLedger, createExecutor, src_default as default, execute, toUnsignedEvidenceKey };
@@ -1,10 +1,10 @@
1
1
  import { applyTokenUpdates, isGasStakeValid } from "../util.mjs";
2
+ import { account } from "@ocap/state";
3
+ import { BN, fromTokenToUnit, fromUnitToToken, hexToNumber } from "@ocap/util";
2
4
  import { CustomError } from "@ocap/util/lib/error";
3
5
  import { toAddress } from "@arcblock/did";
4
6
  import { toStakeAddress } from "@arcblock/did-util";
5
7
  import * as JWT from "@arcblock/jwt";
6
- import { account } from "@ocap/state";
7
- import { BN, fromTokenToUnit, fromUnitToToken, hexToNumber } from "@ocap/util";
8
8
  import noop from "lodash/noop.js";
9
9
  import Debug from "debug";
10
10
 
@@ -49,6 +49,13 @@ const WriteLedger = async (context, next) => {
49
49
  });
50
50
  return next();
51
51
  }
52
+ if (context.ledgerSequence !== void 0) {
53
+ debug("Transaction already written to ledger in previous attempt, skipping write", {
54
+ txHash,
55
+ sequence: context.ledgerSequence
56
+ });
57
+ return next();
58
+ }
52
59
  try {
53
60
  let txExtra;
54
61
  if (extra?.txExtra || extra?.gasStakeHeaders) {
@@ -1,14 +1,15 @@
1
1
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
2
2
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
3
+ import { account, delegation } from "@ocap/state";
3
4
  import { Runner, pipes } from "@ocap/tx-pipeline";
5
+ import { scopeMatchAny } from "@ocap/util";
4
6
  import { CustomError } from "@ocap/util/lib/error";
5
7
  import get from "lodash/get.js";
6
8
  import pick from "lodash/pick.js";
7
9
  import { toDelegateAddress } from "@arcblock/did-util";
8
- import { account, delegation } from "@ocap/state";
9
- import { scopeMatchAny } from "@ocap/util";
10
10
  import Debug from "debug";
11
11
  import { formatMessage } from "@ocap/message";
12
+ import { getListField } from "@ocap/util/lib/get-list-field";
12
13
  import cloneDeep from "lodash/cloneDeep.js";
13
14
  import { v, vBN, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
14
15
 
@@ -133,15 +134,15 @@ runner.use(pipes.TakeStateSnapshot());
133
134
  runner.use(async (context, next) => {
134
135
  const { tx: tx$1, itx, formattedItx, validatedItx, statedb, senderState, receiverState, delegationState, senderUpdates, updateVaults } = context;
135
136
  const ops = formattedItx?.ops || [];
136
- const opsList = validatedItx?.opsList || [];
137
- const deny = itx.denyList || [];
137
+ const opsList = getListField(validatedItx, "ops");
138
+ const deny = getListField(itx, "deny");
138
139
  const validUntil = itx.validUntil || 0;
139
140
  const merged = cloneDeep(ops).reduce((acc, x, i) => {
140
141
  const tokens = x.limit?.tokens || [];
141
142
  const assets = x.limit?.assets || [];
142
143
  acc[x.typeUrl] = { limit: {
143
144
  tokens: tokens.map((y, j) => {
144
- const input = opsList[i]?.limit?.tokensList?.[j] || {};
145
+ const input = getListField(opsList[i]?.limit, "tokens")[j] || {};
145
146
  return Object.assign(y, pick(input, [
146
147
  "txCount",
147
148
  "txAllowance",
@@ -155,7 +156,7 @@ runner.use(async (context, next) => {
155
156
  });
156
157
  }),
157
158
  assets: assets.map((y, j) => {
158
- const input = opsList[i]?.limit?.assetsList?.[j] || {};
159
+ const input = getListField(opsList[i]?.limit, "assets")[j] || {};
159
160
  return Object.assign(y, pick(input, [
160
161
  "txCount",
161
162
  "validUntil",
@@ -1,13 +1,13 @@
1
1
  import { decodeAnySafe } from "../../util.mjs";
2
2
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
3
3
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
4
+ import { types } from "@ocap/mcrypto";
5
+ import { account } from "@ocap/state";
4
6
  import { Runner, pipes } from "@ocap/tx-pipeline";
5
7
  import { CustomError } from "@ocap/util/lib/error";
6
8
  import { fromPublicKey, toTypeInfo } from "@arcblock/did";
7
- import { account } from "@ocap/state";
8
9
  import Debug from "debug";
9
10
  import { v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
10
- import { types } from "@ocap/mcrypto";
11
11
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
12
12
  import flatten from "lodash/flatten.js";
13
13
  import uniq from "lodash/uniq.js";
@@ -1,10 +1,10 @@
1
1
  import ensure_cost_default from "../../pipes/ensure-cost.mjs";
2
2
  import ensure_gas_default from "../../pipes/ensure-gas.mjs";
3
+ import { account, delegation } from "@ocap/state";
3
4
  import { Runner, pipes } from "@ocap/tx-pipeline";
4
5
  import { CustomError } from "@ocap/util/lib/error";
5
6
  import get from "lodash/get.js";
6
7
  import { toDelegateAddress } from "@arcblock/did-util";
7
- import { account, delegation } from "@ocap/state";
8
8
  import Debug from "debug";
9
9
  import { getListField } from "@ocap/util/lib/get-list-field";
10
10
  import cloneDeep from "lodash/cloneDeep.js";
@@ -7,10 +7,11 @@ import verify_itx_address_default from "./pipes/verify-itx-address.mjs";
7
7
  import verify_itx_assets_default from "./pipes/verify-itx-assets.mjs";
8
8
  import verify_itx_variables_default from "./pipes/verify-itx-variables.mjs";
9
9
  import verify_mint_limit_default from "./pipes/verify-mint-limit.mjs";
10
- import { Runner, pipes } from "@ocap/tx-pipeline";
11
- import { CustomError } from "@ocap/util/lib/error";
12
10
  import { account, asset, delegation, factory } from "@ocap/state";
11
+ import { Runner, pipes, verifyAssetHierarchy } from "@ocap/tx-pipeline";
12
+ import { CustomError } from "@ocap/util/lib/error";
13
13
  import Debug from "debug";
14
+ import { getListField } from "@ocap/util/lib/get-list-field";
14
15
  import { schemas, v, vDID, vStripUnknown, vValidate } from "@arcblock/validator";
15
16
  import { promisify } from "node:util";
16
17
 
@@ -79,15 +80,23 @@ runner.use(pipes.ExtractState({
79
80
  status: "INVALID_FACTORY_STATE",
80
81
  table: "factory"
81
82
  }));
83
+ runner.use(extract_factory_tokens_default);
82
84
  runner.use(pipes.VerifyDelegation({
83
85
  type: "signature",
84
86
  signerKey: "senderState",
85
87
  delegatorKey: "delegatorState",
86
88
  getRequirements: (context) => {
87
- return context.factoryState.input.tokens.map((x) => ({
89
+ const ctx = context;
90
+ const tokens = ctx.factoryTokens || [];
91
+ const assets = getListField(ctx.itx, "assets") || [];
92
+ return [...tokens.map((x) => ({
88
93
  type: "token",
89
- ...x
90
- }));
94
+ address: x.address,
95
+ value: String(x.value)
96
+ })), ...assets.map((x) => ({
97
+ type: "asset",
98
+ address: x
99
+ }))];
91
100
  }
92
101
  }));
93
102
  runner.use(pipes.ExtractState({
@@ -133,13 +142,18 @@ runner.use(pipes.ExtractState({
133
142
  status: "OK",
134
143
  table: "factory"
135
144
  }));
136
- runner.use(extract_factory_tokens_default);
137
145
  runner.use(pipes.ExtractState({
138
146
  from: "tokenAddress",
139
147
  to: "tokenStates",
140
148
  status: "INVALID_TOKEN",
141
149
  table: "token"
142
150
  }));
151
+ runner.use(pipes.verifyTokenAccess({
152
+ statesKey: "tokenStates",
153
+ listFieldKey: "spenders",
154
+ accountKeys: ["senderState"],
155
+ errorMessage: "Account {address} is not allowed to use token {tokenAddress}"
156
+ }));
143
157
  runner.use(verify_mint_limit_default);
144
158
  runner.use(verify_itx_variables_default);
145
159
  runner.use(verify_itx_address_default("acquire-v2"));
@@ -165,6 +179,11 @@ runner.use(pipes.VerifyUpdater({
165
179
  ownerKey: "assetOwner"
166
180
  }));
167
181
  runner.use(verify_itx_assets_default);
182
+ runner.use(async (context, next) => {
183
+ const { itx, assetOwner, assetStates = [] } = context;
184
+ const consumedAssets = assetStates.map((x) => x.address);
185
+ return next(await verifyAssetHierarchy([itx.address], assetOwner?.address, context, void 0, consumedAssets) || void 0);
186
+ });
168
187
  runner.use(ensure_gas_default((context) => {
169
188
  const result = {
170
189
  create: 1,
@@ -1,5 +1,5 @@
1
1
  import { Runner } from "@ocap/tx-pipeline";
2
- import { IAccountState, IAssetFactoryState, IAssetState, IReadyContext, ITokenState, IWithAsset, IWithFactory, IWithOwner, IWithReceiver, IWithSender, IWithSigners, TAcquireAssetV3Tx } from "@ocap/types";
2
+ import { IAccountState, IAssetFactoryState, IAssetState, IDelegateState, IReadyContext, ITokenState, IWithAsset, IWithFactory, IWithOwner, IWithReceiver, IWithSender, IWithSigners, TAcquireAssetV3Tx } from "@ocap/types";
3
3
 
4
4
  //#region src/protocols/asset/acquire-v3.d.ts
5
5
  /** Token input type */
@@ -53,6 +53,16 @@ type Context = IReadyContext<TAcquireAssetV3Tx> & Partial<IWithSender> & Partial
53
53
  mintedAddress?: string;
54
54
  /** Token updates for factory (non-instant settlement) */
55
55
  tokenUpdates?: Record<string, string>;
56
+ /** Delegator account state for tx.delegator */
57
+ delegatorState?: IAccountState;
58
+ /** Explicit delegation state for tx.delegator */
59
+ delegationState?: IDelegateState;
60
+ /** Signer states extracted from tx.signatures */
61
+ msSignerStates?: IAccountState[];
62
+ /** Delegator states extracted from tx.signatures */
63
+ delegatorStates?: (IAccountState | null)[];
64
+ /** Explicit delegation states for tx.signatures */
65
+ delegationStates?: IDelegateState[];
56
66
  };
57
67
  declare const runner: Runner<Context>;
58
68
  //#endregion