@ocap/resolver 1.31.0 → 1.31.2

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.
package/esm/hooks.d.mts CHANGED
@@ -9,6 +9,12 @@ interface IHooksRollupState {
9
9
  address: string;
10
10
  tokenAddress: string;
11
11
  genesisTime: string;
12
+ /** v2 bridges carry `data.value.version == 2` (bridge/docs/ocap-protocols.md §v2.1) */
13
+ data?: {
14
+ value?: {
15
+ version?: unknown;
16
+ };
17
+ } | null;
12
18
  seedValidators: IRollupValidator[];
13
19
  validators: IRollupValidator[];
14
20
  totalDepositAmount?: string;
package/esm/hooks.mjs CHANGED
@@ -7,7 +7,10 @@ import pick from "lodash/pick.js";
7
7
 
8
8
  //#region src/hooks.ts
9
9
  const debug = createDebug(name);
10
+ /** A v2 bridge has no stake-backed validator records: its operators live in the bridge body (epochs). */
11
+ const isBridgeV2Doc = (doc) => doc?.data?.value?.version === 2;
10
12
  const onCreateRollup = (rollup, _ctx, indexdb) => {
13
+ if (isBridgeV2Doc(rollup)) return;
11
14
  rollup.seedValidators.forEach(async (x) => {
12
15
  const { pk, address, endpoint } = x;
13
16
  try {
@@ -166,6 +169,7 @@ const onClaimBlockReward = async (tx, ctx, indexdb) => {
166
169
  };
167
170
  const onJoinRollup = async (tx, ctx, indexdb) => {
168
171
  try {
172
+ if (isBridgeV2Doc(await indexdb.rollup.get(tx.tx.itxJson.rollup))) return;
169
173
  const address = tx.tx.from;
170
174
  const doc = await ensureRollupValidator(address, tx.tx.itxJson.rollup, ctx, indexdb);
171
175
  doc.endpoint = tx.tx.itxJson.endpoint;
@@ -180,6 +184,7 @@ const onJoinRollup = async (tx, ctx, indexdb) => {
180
184
  };
181
185
  const onLeaveRollup = async (tx, ctx, indexdb) => {
182
186
  try {
187
+ if (isBridgeV2Doc(await indexdb.rollup.get(tx.tx.itxJson.rollup))) return;
183
188
  const address = tx.tx.from;
184
189
  const doc = await ensureRollupValidator(address, tx.tx.itxJson.rollup, ctx, indexdb);
185
190
  doc.leaveTime = tx.time;
package/esm/index.d.mts CHANGED
@@ -24,6 +24,7 @@ declare class OCAPResolver implements IResolver {
24
24
  logger: IPipelineLogger$1;
25
25
  migrationChain?: MigrationChainManager;
26
26
  formatTx: (tx: IResolverTransaction | null, ctx?: IResolverContext$1) => Promise<IResolverTransaction | null>;
27
+ inFlightPreFlights: number;
27
28
  private initializationPromise;
28
29
  /**
29
30
  * Creates an instance of OCAPResolver.
@@ -51,6 +52,7 @@ declare class OCAPResolver implements IResolver {
51
52
  tx: string;
52
53
  extra?: Record<string, unknown>;
53
54
  }, ctx?: IResolverContext$1): Promise<string>;
55
+ _indexRejectedLedgerTx(ctx: Record<string, unknown>, err: unknown): Promise<void>;
54
56
  getTxSecurityWarning(txHash: string): ITxSecurityWarning | undefined;
55
57
  getTx({
56
58
  hash
package/esm/index.mjs CHANGED
@@ -16,7 +16,7 @@ import { formatSearchResult, rebuildIndexFromState } from "@ocap/indexdb";
16
16
  import { types } from "@ocap/mcrypto";
17
17
  import { fromTypeUrl } from "@ocap/message";
18
18
  import * as states from "@ocap/state";
19
- import { TxTimer, assertRawWireEnvelope, assertTxAdmission, classifyErrorStrikeCategory, createExecutor, getTxSecurityWarningByHash, inspectTransactionPreFlight, recordActorSecurityStrike, resolveVerifiedStrikeActors, setTxSecurityWarningForHash } from "@ocap/tx-protocols";
19
+ import { TxTimer, assertRawWireEnvelope, assertStatelessTxRules, assertTxAdmission, classifyErrorStrikeCategory, createExecutor, getTxSecurityWarningByHash, inspectTransactionPreFlight, recordActorSecurityStrike, resolveVerifiedStrikeActors, setTxSecurityWarningForHash } from "@ocap/tx-protocols";
20
20
  import { decodeAnySafe } from "@ocap/tx-protocols/lib/util";
21
21
  import { DEFAULT_TOKEN_DECIMAL } from "@ocap/util/lib/constant";
22
22
  import { CustomError } from "@ocap/util/lib/error";
@@ -29,7 +29,7 @@ import set from "lodash/set.js";
29
29
  import uniqBy from "lodash/unionBy.js";
30
30
  import uniq from "lodash/uniq.js";
31
31
  import Queue from "queue";
32
- import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenFactory, createIndexedTransaction, isDefaultTokenChanged } from "@ocap/indexdb/lib/util";
32
+ import { createIndexedAccount, createIndexedAsset, createIndexedDelegation, createIndexedFactory, createIndexedRollup, createIndexedRollupBlock, createIndexedStake, createIndexedToken, createIndexedTokenFactory, createIndexedTransaction, deriveTxGasPayer, deriveTxSender, isDefaultTokenChanged } from "@ocap/indexdb/lib/util";
33
33
  import { attachPaidTxGas, getTxReceipts, getTxReceiver, getTxSender, mergeTxReceipts } from "@ocap/state/lib/states/tx";
34
34
 
35
35
  //#region src/index.ts
@@ -135,6 +135,10 @@ const maxGasOps = {
135
135
  create: 2,
136
136
  update: 13
137
137
  },
138
+ "fg:t:release_bridge_token": {
139
+ create: 3,
140
+ update: 20
141
+ },
138
142
  "fg:t:create_rollup": {
139
143
  create: 2,
140
144
  update: 2
@@ -250,6 +254,7 @@ var OCAPResolver = class {
250
254
  * @param params.validateTokenConfig should we validate token supply and token-holder balance, should be disabled when starting an existing chain
251
255
  */
252
256
  constructor({ statedb, indexdb, ledger, config, filter, validateTokenConfig = true, logger }) {
257
+ this.inFlightPreFlights = 0;
253
258
  if (!statedb) throw new Error("OCAP Resolver requires a valid statedb implementation to work");
254
259
  if (!indexdb) throw new Error("OCAP Resolver requires a valid indexdb implementation to work");
255
260
  if (!ledger) throw new Error("OCAP Resolver requires a valid ledger implementation to work");
@@ -293,7 +298,8 @@ var OCAPResolver = class {
293
298
  request: ctx.request
294
299
  });
295
300
  if (process.env.CHAIN_MODE === "readonly") throw new CustomError("FORBIDDEN", "This chain node is running in readonly mode");
296
- if (this.queue.length >= txRequestConfig.maxRequest) throw new CustomError("FORBIDDEN", "Chain is busy");
301
+ const maxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
302
+ if (this.queue.length + this.inFlightPreFlights >= maxRequest) throw new CustomError("FORBIDDEN", "Chain is busy");
297
303
  assertRawWireEnvelope(txBase64, this.config);
298
304
  const timer = new TxTimer();
299
305
  timer.setQueueState({
@@ -316,10 +322,19 @@ var OCAPResolver = class {
316
322
  }
317
323
  };
318
324
  return new Promise((resolve, reject) => {
325
+ this.inFlightPreFlights += 1;
326
+ let preFlightSlotReleased = false;
327
+ const releasePreFlightSlot = () => {
328
+ if (!preFlightSlotReleased) {
329
+ preFlightSlotReleased = true;
330
+ this.inFlightPreFlights = Math.max(0, this.inFlightPreFlights - 1);
331
+ }
332
+ };
319
333
  const enqueueAfterPreFlight = async () => {
320
334
  try {
321
335
  await this.initializationPromise;
322
336
  await inspectTransactionPreFlight(context);
337
+ await assertStatelessTxRules(context);
323
338
  const preTx = context.tx;
324
339
  const preTxHash = context.txHash;
325
340
  if (preTx) await assertTxAdmission({
@@ -352,9 +367,16 @@ var OCAPResolver = class {
352
367
  } catch (strikeErr) {
353
368
  this.logger?.warn?.("Failed to record security strike", { error: strikeErr });
354
369
  }
370
+ releasePreFlightSlot();
355
371
  reject(preFlightErr);
356
372
  return;
357
373
  }
374
+ releasePreFlightSlot();
375
+ const currentMaxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
376
+ if (this.queue.length >= currentMaxRequest) {
377
+ reject(new CustomError("FORBIDDEN", "Chain is busy"));
378
+ return;
379
+ }
358
380
  const task = async () => {
359
381
  timer.mark("queueWait");
360
382
  try {
@@ -362,27 +384,134 @@ var OCAPResolver = class {
362
384
  if (result?.txHash && result?.securityWarning) setTxSecurityWarningForHash(result.txHash, result.securityWarning, this.statedb);
363
385
  resolve(result.txHash);
364
386
  } catch (err) {
387
+ await this._indexRejectedLedgerTx(context, err);
365
388
  reject(err);
366
389
  }
367
390
  };
368
391
  this.queue.push(task);
369
392
  };
370
- enqueueAfterPreFlight().catch(reject);
393
+ enqueueAfterPreFlight().catch((err) => {
394
+ releasePreFlightSlot();
395
+ reject(err);
396
+ });
371
397
  });
372
398
  }
399
+ async _indexRejectedLedgerTx(ctx, err) {
400
+ if (!this.indexdb?.tx?.insert) return;
401
+ const ledgerSequence = Number(ctx.ledgerSequence ?? 0);
402
+ const rawTxHash = typeof ctx.txHash === "string" ? ctx.txHash.trim() : "";
403
+ if (!(ledgerSequence > 0) || !rawTxHash) return;
404
+ const txHash = rawTxHash.toUpperCase();
405
+ let rejectedRow;
406
+ try {
407
+ if (await Promise.resolve(this.statedb?.tx?.get?.(txHash)).catch(() => null)) return;
408
+ if (await Promise.resolve(this.indexdb.tx.get?.(txHash)).catch(() => null)) return;
409
+ const txType = typeof ctx.txType === "string" ? ctx.txType : "";
410
+ const type = txType ? txType.split(":").pop() || "" : "";
411
+ let typeName = "";
412
+ if (txType) try {
413
+ typeName = fromTypeUrl(txType);
414
+ } catch {
415
+ typeName = "";
416
+ }
417
+ const txObj = ctx.tx && typeof ctx.tx === "object" ? ctx.tx : {};
418
+ const from = typeof txObj.from === "string" ? txObj.from : "";
419
+ const delegator = typeof txObj.delegator === "string" ? txObj.delegator : "";
420
+ const toStrOrBase64 = (val) => {
421
+ if (typeof val === "string") return val;
422
+ if (val instanceof Uint8Array || Buffer.isBuffer(val)) return Buffer.from(val).toString("base64");
423
+ return "";
424
+ };
425
+ const sourceItx = ctx.itxJson && typeof ctx.itxJson === "object" ? ctx.itxJson : ctx.itx && typeof ctx.itx === "object" ? ctx.itx : null;
426
+ const itxJson = sourceItx ? { ...sourceItx } : {
427
+ ...typeName ? { _type: typeName } : {},
428
+ type_url: txType
429
+ };
430
+ if (!itxJson.type_url && txType) itxJson.type_url = txType;
431
+ if (!itxJson._type && typeName) itxJson._type = typeName;
432
+ const syntheticTx = {
433
+ valid: false,
434
+ code: String(err?.code || "INTERNAL"),
435
+ tx: {
436
+ from,
437
+ delegator,
438
+ itxJson
439
+ }
440
+ };
441
+ const sender = deriveTxSender(syntheticTx, ctx);
442
+ const gasPayer = "";
443
+ const time = typeof ctx.txTime === "string" && ctx.txTime || (/* @__PURE__ */ new Date()).toISOString();
444
+ const code = syntheticTx.code;
445
+ const accounts = uniq([
446
+ from,
447
+ delegator,
448
+ sender
449
+ ].filter(Boolean));
450
+ rejectedRow = {
451
+ hash: txHash,
452
+ type,
453
+ code,
454
+ valid: false,
455
+ time,
456
+ sender,
457
+ receiver: "",
458
+ gasPayer,
459
+ gasUsed: "0",
460
+ tx: {
461
+ chainId: String(txObj.chainId || this.config?.chainId || ""),
462
+ from,
463
+ delegator,
464
+ nonce: txObj.nonce ?? 0,
465
+ pk: toStrOrBase64(txObj.pk),
466
+ signature: toStrOrBase64(txObj.signature),
467
+ signaturesList: Array.isArray(txObj.signaturesList) ? txObj.signaturesList : [],
468
+ signatures: Array.isArray(txObj.signatures) ? txObj.signatures : [],
469
+ serviceFee: "0",
470
+ gasFee: "0",
471
+ gasPaid: "0",
472
+ gasPayer,
473
+ itx: {
474
+ typeUrl: txType,
475
+ ...typeName ? { __typename: typeName } : {}
476
+ },
477
+ itxJson
478
+ },
479
+ receipts: [],
480
+ tokenSymbols: [],
481
+ accounts
482
+ };
483
+ await this.indexdb.tx.insert(rejectedRow);
484
+ } catch (indexErr) {
485
+ await this.recordIndexFailure({
486
+ table: "tx",
487
+ event: "create",
488
+ entityId: txHash,
489
+ payload: rejectedRow ?? { hash: txHash },
490
+ error: indexErr
491
+ });
492
+ }
493
+ }
373
494
  getTxSecurityWarning(txHash) {
374
495
  return getTxSecurityWarningByHash(txHash, this.statedb);
375
496
  }
376
- getTx({ hash }, ctx) {
377
- if (patterns.txHash.test(hash)) return this._getState({
378
- table: "tx",
379
- id: hash.toUpperCase(),
380
- dataKey: "tx.itxJson.data",
381
- onRead: (tx) => this.formatTx(tx, ctx),
382
- expandContext: false,
383
- ctx
384
- });
385
- return Promise.resolve(null);
497
+ async getTx({ hash }, ctx) {
498
+ if (patterns.txHash.test(hash)) {
499
+ const normalizedHash = hash.toUpperCase();
500
+ const stateTx = await this._getState({
501
+ table: "tx",
502
+ id: normalizedHash,
503
+ dataKey: "tx.itxJson.data",
504
+ onRead: (tx) => this.formatTx(tx, ctx),
505
+ expandContext: false,
506
+ ctx
507
+ });
508
+ if (stateTx) return stateTx;
509
+ if (this.indexdb?.tx?.get) {
510
+ const indexedTx = await Promise.resolve(this.indexdb.tx.get(normalizedHash)).catch(() => null);
511
+ if (indexedTx && (indexedTx.valid === false || indexedTx.valid === 0 || indexedTx.code !== "OK")) return this.formatTx(indexedTx, ctx);
512
+ }
513
+ }
514
+ return null;
386
515
  }
387
516
  getBlock() {
388
517
  return null;
@@ -1410,18 +1539,28 @@ var OCAPResolver = class {
1410
1539
  async _formatTx(tx, ctx) {
1411
1540
  if (!tx) return tx;
1412
1541
  if (!tx.sender && !tx.receiver) {
1413
- const typeUrl$1 = fromTypeUrl(tx.tx.itx.typeUrl);
1414
- tx.sender = getTxSender({
1415
- tx: tx.tx,
1416
- itx: tx.tx.itxJson,
1417
- typeUrl: typeUrl$1
1418
- });
1419
- tx.receiver = getTxReceiver({
1420
- tx: tx.tx,
1421
- itx: tx.tx.itxJson,
1422
- typeUrl: typeUrl$1
1423
- });
1542
+ const rawTypeUrl = tx.tx?.itx?.typeUrl || (tx.tx?.itx)?.__typename || tx.tx?.itxJson?.type_url || (tx.tx?.itxJson)?._type || "";
1543
+ let parsedTypeUrl = rawTypeUrl;
1544
+ if (rawTypeUrl.startsWith("fg:t:")) try {
1545
+ parsedTypeUrl = fromTypeUrl(rawTypeUrl);
1546
+ } catch {
1547
+ parsedTypeUrl = rawTypeUrl;
1548
+ }
1549
+ if (parsedTypeUrl) {
1550
+ tx.sender = getTxSender({
1551
+ tx: tx.tx,
1552
+ itx: tx.tx?.itxJson || {},
1553
+ typeUrl: parsedTypeUrl
1554
+ });
1555
+ tx.receiver = getTxReceiver({
1556
+ tx: tx.tx,
1557
+ itx: tx.tx?.itxJson || {},
1558
+ typeUrl: parsedTypeUrl
1559
+ });
1560
+ }
1561
+ if (!tx.sender && tx.valid === false) tx.sender = deriveTxSender(tx);
1424
1562
  }
1563
+ if (!tx.gasPayer) tx.gasPayer = deriveTxGasPayer(tx);
1425
1564
  if (!tx.receipts) tx.receipts = getTxReceipts(tx, { config: this.config });
1426
1565
  const typeUrl = get(tx, "tx.itxJson.type_url");
1427
1566
  if (typeUrl === "fg:t:revoke_withdraw" || typeUrl === "fg:t:approve_withdraw") {
@@ -1496,7 +1635,7 @@ var OCAPResolver = class {
1496
1635
  }));
1497
1636
  }
1498
1637
  async getTxTokenSymbols(tx) {
1499
- if (!tx) return [];
1638
+ if (!tx || !tx.tx?.itxJson) return [];
1500
1639
  const rollupTxs = [
1501
1640
  "DepositTokenV2Tx",
1502
1641
  "WithdrawTokenV2Tx",
@@ -1505,43 +1644,56 @@ var OCAPResolver = class {
1505
1644
  "CreateRollupBlockTx",
1506
1645
  "ClaimBlockRewardTx"
1507
1646
  ];
1508
- const typeUrl = tx.tx.itxJson._type || "";
1647
+ const itxJson = tx.tx.itxJson;
1648
+ const typeUrl = itxJson._type || "";
1509
1649
  const tokens = [];
1510
1650
  if (isDefaultTokenChanged(tx, this.config.token)) tokens.push(this.tokenItx);
1511
1651
  if (typeUrl === "AcquireAssetV2Tx") {
1512
- const factoryInput = (await this.indexdb.factory.get(tx.tx.itxJson.factory))?.input;
1513
- if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1652
+ if (typeof itxJson.factory === "string" && itxJson.factory) {
1653
+ const factoryInput = (await this.indexdb.factory.get(itxJson.factory))?.input;
1654
+ if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1655
+ }
1514
1656
  } else if (typeUrl === "ExchangeV2Tx") {
1515
- tokens.push(...tx.tx.itxJson.sender?.tokens || []);
1516
- tokens.push(...tx.tx.itxJson.receiver?.tokens || []);
1517
- } else if (typeUrl === "TransferV2Tx") tokens.push(...tx.tx.itxJson.tokens || []);
1657
+ tokens.push(...itxJson.sender?.tokens || []);
1658
+ tokens.push(...itxJson.receiver?.tokens || []);
1659
+ } else if (typeUrl === "TransferV2Tx") tokens.push(...itxJson.tokens || []);
1518
1660
  else if ([
1519
1661
  "TransferV3Tx",
1520
1662
  "AcquireAssetV3Tx",
1521
1663
  "StakeTx"
1522
- ].includes(typeUrl)) tokens.push(...uniqBy((tx.tx.itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1664
+ ].includes(typeUrl)) tokens.push(...uniqBy((itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1523
1665
  else if ([
1524
1666
  "RevokeStakeTx",
1525
1667
  "SlashStakeTx",
1526
1668
  "ReturnStakeTx"
1527
- ].includes(typeUrl)) tokens.push(...uniqBy((tx.tx.itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1669
+ ].includes(typeUrl)) tokens.push(...uniqBy((itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1528
1670
  else if (typeUrl === "ClaimStakeTx") {
1529
- const revokeTx = await this.indexdb.tx.get(tx.tx.itxJson.evidence.hash);
1671
+ const evidenceHash = itxJson.evidence?.hash;
1672
+ const revokeTx = typeof evidenceHash === "string" && evidenceHash ? await this.indexdb.tx.get(evidenceHash) : null;
1530
1673
  if (revokeTx) {
1531
1674
  const revokeTxAny = revokeTx;
1532
1675
  tokens.push(...uniqBy((revokeTxAny.tx?.itxJson?.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1533
1676
  } else this.logger.warn("Revoke stake tx not found", { tx });
1534
1677
  } else if (rollupTxs.includes(typeUrl)) {
1535
- const rollup = await this.indexdb.rollup.get(tx.tx.itxJson.rollup);
1536
- if (rollup) tokens.push({
1537
- address: rollup.tokenAddress,
1538
- value: "0"
1539
- });
1540
- } else if (typeUrl === "CreateTokenTx") return [extractTokenMeta(tx.tx.itxJson.address, [tx.tx.itxJson])];
1541
- else if (typeUrl === "MintTokenTx" || typeUrl === "BurnTokenTx") {
1542
- const token = await this.indexdb.tokenFactory.get(tx.tx.itxJson.tokenFactory);
1543
- if (token) tokens.push({ address: token.tokenAddress });
1544
- } else if (typeUrl === "CreateTokenFactoryTx") tokens.push({ address: tx.tx.itxJson.token.address });
1678
+ if (typeof itxJson.rollup === "string" && itxJson.rollup) {
1679
+ const rollup = await this.indexdb.rollup.get(itxJson.rollup);
1680
+ if (rollup) tokens.push({
1681
+ address: rollup.tokenAddress,
1682
+ value: "0"
1683
+ });
1684
+ }
1685
+ } else if (typeUrl === "CreateTokenTx") {
1686
+ if (typeof itxJson.address === "string" && itxJson.address) return [extractTokenMeta(itxJson.address, [itxJson])];
1687
+ return [];
1688
+ } else if (typeUrl === "MintTokenTx" || typeUrl === "BurnTokenTx") {
1689
+ if (typeof itxJson.tokenFactory === "string" && itxJson.tokenFactory) {
1690
+ const token = await this.indexdb.tokenFactory.get(itxJson.tokenFactory);
1691
+ if (token) tokens.push({ address: token.tokenAddress });
1692
+ }
1693
+ } else if (typeUrl === "CreateTokenFactoryTx") {
1694
+ const tokenAddr = itxJson.token?.address;
1695
+ if (typeof tokenAddr === "string" && tokenAddr) tokens.push({ address: tokenAddr });
1696
+ }
1545
1697
  if (tokens.length > 0) return this.formatTokenArray(tokens);
1546
1698
  return [];
1547
1699
  }
package/lib/hooks.cjs CHANGED
@@ -11,7 +11,10 @@ lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
11
11
 
12
12
  //#region src/hooks.ts
13
13
  const debug$1 = (0, debug.default)(require_package.name);
14
+ /** A v2 bridge has no stake-backed validator records: its operators live in the bridge body (epochs). */
15
+ const isBridgeV2Doc = (doc) => doc?.data?.value?.version === 2;
14
16
  const onCreateRollup = (rollup, _ctx, indexdb) => {
17
+ if (isBridgeV2Doc(rollup)) return;
15
18
  rollup.seedValidators.forEach(async (x) => {
16
19
  const { pk, address, endpoint } = x;
17
20
  try {
@@ -170,6 +173,7 @@ const onClaimBlockReward = async (tx, ctx, indexdb) => {
170
173
  };
171
174
  const onJoinRollup = async (tx, ctx, indexdb) => {
172
175
  try {
176
+ if (isBridgeV2Doc(await indexdb.rollup.get(tx.tx.itxJson.rollup))) return;
173
177
  const address = tx.tx.from;
174
178
  const doc = await ensureRollupValidator(address, tx.tx.itxJson.rollup, ctx, indexdb);
175
179
  doc.endpoint = tx.tx.itxJson.endpoint;
@@ -184,6 +188,7 @@ const onJoinRollup = async (tx, ctx, indexdb) => {
184
188
  };
185
189
  const onLeaveRollup = async (tx, ctx, indexdb) => {
186
190
  try {
191
+ if (isBridgeV2Doc(await indexdb.rollup.get(tx.tx.itxJson.rollup))) return;
187
192
  const address = tx.tx.from;
188
193
  const doc = await ensureRollupValidator(address, tx.tx.itxJson.rollup, ctx, indexdb);
189
194
  doc.leaveTime = tx.time;
package/lib/hooks.d.cts CHANGED
@@ -9,6 +9,12 @@ interface IHooksRollupState {
9
9
  address: string;
10
10
  tokenAddress: string;
11
11
  genesisTime: string;
12
+ /** v2 bridges carry `data.value.version == 2` (bridge/docs/ocap-protocols.md §v2.1) */
13
+ data?: {
14
+ value?: {
15
+ version?: unknown;
16
+ };
17
+ } | null;
12
18
  seedValidators: IRollupValidator[];
13
19
  validators: IRollupValidator[];
14
20
  totalDepositAmount?: string;
package/lib/index.cjs CHANGED
@@ -149,6 +149,10 @@ const maxGasOps = {
149
149
  create: 2,
150
150
  update: 13
151
151
  },
152
+ "fg:t:release_bridge_token": {
153
+ create: 3,
154
+ update: 20
155
+ },
152
156
  "fg:t:create_rollup": {
153
157
  create: 2,
154
158
  update: 2
@@ -264,6 +268,7 @@ var OCAPResolver = class {
264
268
  * @param params.validateTokenConfig should we validate token supply and token-holder balance, should be disabled when starting an existing chain
265
269
  */
266
270
  constructor({ statedb, indexdb, ledger, config, filter, validateTokenConfig = true, logger }) {
271
+ this.inFlightPreFlights = 0;
267
272
  if (!statedb) throw new Error("OCAP Resolver requires a valid statedb implementation to work");
268
273
  if (!indexdb) throw new Error("OCAP Resolver requires a valid indexdb implementation to work");
269
274
  if (!ledger) throw new Error("OCAP Resolver requires a valid ledger implementation to work");
@@ -307,7 +312,8 @@ var OCAPResolver = class {
307
312
  request: ctx.request
308
313
  });
309
314
  if (process.env.CHAIN_MODE === "readonly") throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "This chain node is running in readonly mode");
310
- if (this.queue.length >= txRequestConfig.maxRequest) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy");
315
+ const maxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
316
+ if (this.queue.length + this.inFlightPreFlights >= maxRequest) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy");
311
317
  (0, _ocap_tx_protocols.assertRawWireEnvelope)(txBase64, this.config);
312
318
  const timer = new _ocap_tx_protocols.TxTimer();
313
319
  timer.setQueueState({
@@ -330,10 +336,19 @@ var OCAPResolver = class {
330
336
  }
331
337
  };
332
338
  return new Promise((resolve, reject) => {
339
+ this.inFlightPreFlights += 1;
340
+ let preFlightSlotReleased = false;
341
+ const releasePreFlightSlot = () => {
342
+ if (!preFlightSlotReleased) {
343
+ preFlightSlotReleased = true;
344
+ this.inFlightPreFlights = Math.max(0, this.inFlightPreFlights - 1);
345
+ }
346
+ };
333
347
  const enqueueAfterPreFlight = async () => {
334
348
  try {
335
349
  await this.initializationPromise;
336
350
  await (0, _ocap_tx_protocols.inspectTransactionPreFlight)(context);
351
+ await (0, _ocap_tx_protocols.assertStatelessTxRules)(context);
337
352
  const preTx = context.tx;
338
353
  const preTxHash = context.txHash;
339
354
  if (preTx) await (0, _ocap_tx_protocols.assertTxAdmission)({
@@ -366,9 +381,16 @@ var OCAPResolver = class {
366
381
  } catch (strikeErr) {
367
382
  this.logger?.warn?.("Failed to record security strike", { error: strikeErr });
368
383
  }
384
+ releasePreFlightSlot();
369
385
  reject(preFlightErr);
370
386
  return;
371
387
  }
388
+ releasePreFlightSlot();
389
+ const currentMaxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
390
+ if (this.queue.length >= currentMaxRequest) {
391
+ reject(new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy"));
392
+ return;
393
+ }
372
394
  const task = async () => {
373
395
  timer.mark("queueWait");
374
396
  try {
@@ -376,27 +398,134 @@ var OCAPResolver = class {
376
398
  if (result?.txHash && result?.securityWarning) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(result.txHash, result.securityWarning, this.statedb);
377
399
  resolve(result.txHash);
378
400
  } catch (err) {
401
+ await this._indexRejectedLedgerTx(context, err);
379
402
  reject(err);
380
403
  }
381
404
  };
382
405
  this.queue.push(task);
383
406
  };
384
- enqueueAfterPreFlight().catch(reject);
407
+ enqueueAfterPreFlight().catch((err) => {
408
+ releasePreFlightSlot();
409
+ reject(err);
410
+ });
385
411
  });
386
412
  }
413
+ async _indexRejectedLedgerTx(ctx, err) {
414
+ if (!this.indexdb?.tx?.insert) return;
415
+ const ledgerSequence = Number(ctx.ledgerSequence ?? 0);
416
+ const rawTxHash = typeof ctx.txHash === "string" ? ctx.txHash.trim() : "";
417
+ if (!(ledgerSequence > 0) || !rawTxHash) return;
418
+ const txHash = rawTxHash.toUpperCase();
419
+ let rejectedRow;
420
+ try {
421
+ if (await Promise.resolve(this.statedb?.tx?.get?.(txHash)).catch(() => null)) return;
422
+ if (await Promise.resolve(this.indexdb.tx.get?.(txHash)).catch(() => null)) return;
423
+ const txType = typeof ctx.txType === "string" ? ctx.txType : "";
424
+ const type = txType ? txType.split(":").pop() || "" : "";
425
+ let typeName = "";
426
+ if (txType) try {
427
+ typeName = (0, _ocap_message.fromTypeUrl)(txType);
428
+ } catch {
429
+ typeName = "";
430
+ }
431
+ const txObj = ctx.tx && typeof ctx.tx === "object" ? ctx.tx : {};
432
+ const from = typeof txObj.from === "string" ? txObj.from : "";
433
+ const delegator = typeof txObj.delegator === "string" ? txObj.delegator : "";
434
+ const toStrOrBase64 = (val) => {
435
+ if (typeof val === "string") return val;
436
+ if (val instanceof Uint8Array || Buffer.isBuffer(val)) return Buffer.from(val).toString("base64");
437
+ return "";
438
+ };
439
+ const sourceItx = ctx.itxJson && typeof ctx.itxJson === "object" ? ctx.itxJson : ctx.itx && typeof ctx.itx === "object" ? ctx.itx : null;
440
+ const itxJson = sourceItx ? { ...sourceItx } : {
441
+ ...typeName ? { _type: typeName } : {},
442
+ type_url: txType
443
+ };
444
+ if (!itxJson.type_url && txType) itxJson.type_url = txType;
445
+ if (!itxJson._type && typeName) itxJson._type = typeName;
446
+ const syntheticTx = {
447
+ valid: false,
448
+ code: String(err?.code || "INTERNAL"),
449
+ tx: {
450
+ from,
451
+ delegator,
452
+ itxJson
453
+ }
454
+ };
455
+ const sender = (0, _ocap_indexdb_lib_util.deriveTxSender)(syntheticTx, ctx);
456
+ const gasPayer = "";
457
+ const time = typeof ctx.txTime === "string" && ctx.txTime || (/* @__PURE__ */ new Date()).toISOString();
458
+ const code = syntheticTx.code;
459
+ const accounts = (0, lodash_uniq.default)([
460
+ from,
461
+ delegator,
462
+ sender
463
+ ].filter(Boolean));
464
+ rejectedRow = {
465
+ hash: txHash,
466
+ type,
467
+ code,
468
+ valid: false,
469
+ time,
470
+ sender,
471
+ receiver: "",
472
+ gasPayer,
473
+ gasUsed: "0",
474
+ tx: {
475
+ chainId: String(txObj.chainId || this.config?.chainId || ""),
476
+ from,
477
+ delegator,
478
+ nonce: txObj.nonce ?? 0,
479
+ pk: toStrOrBase64(txObj.pk),
480
+ signature: toStrOrBase64(txObj.signature),
481
+ signaturesList: Array.isArray(txObj.signaturesList) ? txObj.signaturesList : [],
482
+ signatures: Array.isArray(txObj.signatures) ? txObj.signatures : [],
483
+ serviceFee: "0",
484
+ gasFee: "0",
485
+ gasPaid: "0",
486
+ gasPayer,
487
+ itx: {
488
+ typeUrl: txType,
489
+ ...typeName ? { __typename: typeName } : {}
490
+ },
491
+ itxJson
492
+ },
493
+ receipts: [],
494
+ tokenSymbols: [],
495
+ accounts
496
+ };
497
+ await this.indexdb.tx.insert(rejectedRow);
498
+ } catch (indexErr) {
499
+ await this.recordIndexFailure({
500
+ table: "tx",
501
+ event: "create",
502
+ entityId: txHash,
503
+ payload: rejectedRow ?? { hash: txHash },
504
+ error: indexErr
505
+ });
506
+ }
507
+ }
387
508
  getTxSecurityWarning(txHash) {
388
509
  return (0, _ocap_tx_protocols.getTxSecurityWarningByHash)(txHash, this.statedb);
389
510
  }
390
- getTx({ hash }, ctx) {
391
- if (_arcblock_validator.patterns.txHash.test(hash)) return this._getState({
392
- table: "tx",
393
- id: hash.toUpperCase(),
394
- dataKey: "tx.itxJson.data",
395
- onRead: (tx) => this.formatTx(tx, ctx),
396
- expandContext: false,
397
- ctx
398
- });
399
- return Promise.resolve(null);
511
+ async getTx({ hash }, ctx) {
512
+ if (_arcblock_validator.patterns.txHash.test(hash)) {
513
+ const normalizedHash = hash.toUpperCase();
514
+ const stateTx = await this._getState({
515
+ table: "tx",
516
+ id: normalizedHash,
517
+ dataKey: "tx.itxJson.data",
518
+ onRead: (tx) => this.formatTx(tx, ctx),
519
+ expandContext: false,
520
+ ctx
521
+ });
522
+ if (stateTx) return stateTx;
523
+ if (this.indexdb?.tx?.get) {
524
+ const indexedTx = await Promise.resolve(this.indexdb.tx.get(normalizedHash)).catch(() => null);
525
+ if (indexedTx && (indexedTx.valid === false || indexedTx.valid === 0 || indexedTx.code !== "OK")) return this.formatTx(indexedTx, ctx);
526
+ }
527
+ }
528
+ return null;
400
529
  }
401
530
  getBlock() {
402
531
  return null;
@@ -1424,18 +1553,28 @@ var OCAPResolver = class {
1424
1553
  async _formatTx(tx, ctx) {
1425
1554
  if (!tx) return tx;
1426
1555
  if (!tx.sender && !tx.receiver) {
1427
- const typeUrl$1 = (0, _ocap_message.fromTypeUrl)(tx.tx.itx.typeUrl);
1428
- tx.sender = (0, _ocap_state_lib_states_tx.getTxSender)({
1429
- tx: tx.tx,
1430
- itx: tx.tx.itxJson,
1431
- typeUrl: typeUrl$1
1432
- });
1433
- tx.receiver = (0, _ocap_state_lib_states_tx.getTxReceiver)({
1434
- tx: tx.tx,
1435
- itx: tx.tx.itxJson,
1436
- typeUrl: typeUrl$1
1437
- });
1556
+ const rawTypeUrl = tx.tx?.itx?.typeUrl || (tx.tx?.itx)?.__typename || tx.tx?.itxJson?.type_url || (tx.tx?.itxJson)?._type || "";
1557
+ let parsedTypeUrl = rawTypeUrl;
1558
+ if (rawTypeUrl.startsWith("fg:t:")) try {
1559
+ parsedTypeUrl = (0, _ocap_message.fromTypeUrl)(rawTypeUrl);
1560
+ } catch {
1561
+ parsedTypeUrl = rawTypeUrl;
1562
+ }
1563
+ if (parsedTypeUrl) {
1564
+ tx.sender = (0, _ocap_state_lib_states_tx.getTxSender)({
1565
+ tx: tx.tx,
1566
+ itx: tx.tx?.itxJson || {},
1567
+ typeUrl: parsedTypeUrl
1568
+ });
1569
+ tx.receiver = (0, _ocap_state_lib_states_tx.getTxReceiver)({
1570
+ tx: tx.tx,
1571
+ itx: tx.tx?.itxJson || {},
1572
+ typeUrl: parsedTypeUrl
1573
+ });
1574
+ }
1575
+ if (!tx.sender && tx.valid === false) tx.sender = (0, _ocap_indexdb_lib_util.deriveTxSender)(tx);
1438
1576
  }
1577
+ if (!tx.gasPayer) tx.gasPayer = (0, _ocap_indexdb_lib_util.deriveTxGasPayer)(tx);
1439
1578
  if (!tx.receipts) tx.receipts = (0, _ocap_state_lib_states_tx.getTxReceipts)(tx, { config: this.config });
1440
1579
  const typeUrl = (0, lodash_get.default)(tx, "tx.itxJson.type_url");
1441
1580
  if (typeUrl === "fg:t:revoke_withdraw" || typeUrl === "fg:t:approve_withdraw") {
@@ -1510,7 +1649,7 @@ var OCAPResolver = class {
1510
1649
  }));
1511
1650
  }
1512
1651
  async getTxTokenSymbols(tx) {
1513
- if (!tx) return [];
1652
+ if (!tx || !tx.tx?.itxJson) return [];
1514
1653
  const rollupTxs = [
1515
1654
  "DepositTokenV2Tx",
1516
1655
  "WithdrawTokenV2Tx",
@@ -1519,43 +1658,56 @@ var OCAPResolver = class {
1519
1658
  "CreateRollupBlockTx",
1520
1659
  "ClaimBlockRewardTx"
1521
1660
  ];
1522
- const typeUrl = tx.tx.itxJson._type || "";
1661
+ const itxJson = tx.tx.itxJson;
1662
+ const typeUrl = itxJson._type || "";
1523
1663
  const tokens = [];
1524
1664
  if ((0, _ocap_indexdb_lib_util.isDefaultTokenChanged)(tx, this.config.token)) tokens.push(this.tokenItx);
1525
1665
  if (typeUrl === "AcquireAssetV2Tx") {
1526
- const factoryInput = (await this.indexdb.factory.get(tx.tx.itxJson.factory))?.input;
1527
- if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1666
+ if (typeof itxJson.factory === "string" && itxJson.factory) {
1667
+ const factoryInput = (await this.indexdb.factory.get(itxJson.factory))?.input;
1668
+ if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1669
+ }
1528
1670
  } else if (typeUrl === "ExchangeV2Tx") {
1529
- tokens.push(...tx.tx.itxJson.sender?.tokens || []);
1530
- tokens.push(...tx.tx.itxJson.receiver?.tokens || []);
1531
- } else if (typeUrl === "TransferV2Tx") tokens.push(...tx.tx.itxJson.tokens || []);
1671
+ tokens.push(...itxJson.sender?.tokens || []);
1672
+ tokens.push(...itxJson.receiver?.tokens || []);
1673
+ } else if (typeUrl === "TransferV2Tx") tokens.push(...itxJson.tokens || []);
1532
1674
  else if ([
1533
1675
  "TransferV3Tx",
1534
1676
  "AcquireAssetV3Tx",
1535
1677
  "StakeTx"
1536
- ].includes(typeUrl)) tokens.push(...(0, lodash_unionBy.default)((tx.tx.itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1678
+ ].includes(typeUrl)) tokens.push(...(0, lodash_unionBy.default)((itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1537
1679
  else if ([
1538
1680
  "RevokeStakeTx",
1539
1681
  "SlashStakeTx",
1540
1682
  "ReturnStakeTx"
1541
- ].includes(typeUrl)) tokens.push(...(0, lodash_unionBy.default)((tx.tx.itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1683
+ ].includes(typeUrl)) tokens.push(...(0, lodash_unionBy.default)((itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1542
1684
  else if (typeUrl === "ClaimStakeTx") {
1543
- const revokeTx = await this.indexdb.tx.get(tx.tx.itxJson.evidence.hash);
1685
+ const evidenceHash = itxJson.evidence?.hash;
1686
+ const revokeTx = typeof evidenceHash === "string" && evidenceHash ? await this.indexdb.tx.get(evidenceHash) : null;
1544
1687
  if (revokeTx) {
1545
1688
  const revokeTxAny = revokeTx;
1546
1689
  tokens.push(...(0, lodash_unionBy.default)((revokeTxAny.tx?.itxJson?.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1547
1690
  } else this.logger.warn("Revoke stake tx not found", { tx });
1548
1691
  } else if (rollupTxs.includes(typeUrl)) {
1549
- const rollup = await this.indexdb.rollup.get(tx.tx.itxJson.rollup);
1550
- if (rollup) tokens.push({
1551
- address: rollup.tokenAddress,
1552
- value: "0"
1553
- });
1554
- } else if (typeUrl === "CreateTokenTx") return [extractTokenMeta(tx.tx.itxJson.address, [tx.tx.itxJson])];
1555
- else if (typeUrl === "MintTokenTx" || typeUrl === "BurnTokenTx") {
1556
- const token = await this.indexdb.tokenFactory.get(tx.tx.itxJson.tokenFactory);
1557
- if (token) tokens.push({ address: token.tokenAddress });
1558
- } else if (typeUrl === "CreateTokenFactoryTx") tokens.push({ address: tx.tx.itxJson.token.address });
1692
+ if (typeof itxJson.rollup === "string" && itxJson.rollup) {
1693
+ const rollup = await this.indexdb.rollup.get(itxJson.rollup);
1694
+ if (rollup) tokens.push({
1695
+ address: rollup.tokenAddress,
1696
+ value: "0"
1697
+ });
1698
+ }
1699
+ } else if (typeUrl === "CreateTokenTx") {
1700
+ if (typeof itxJson.address === "string" && itxJson.address) return [extractTokenMeta(itxJson.address, [itxJson])];
1701
+ return [];
1702
+ } else if (typeUrl === "MintTokenTx" || typeUrl === "BurnTokenTx") {
1703
+ if (typeof itxJson.tokenFactory === "string" && itxJson.tokenFactory) {
1704
+ const token = await this.indexdb.tokenFactory.get(itxJson.tokenFactory);
1705
+ if (token) tokens.push({ address: token.tokenAddress });
1706
+ }
1707
+ } else if (typeUrl === "CreateTokenFactoryTx") {
1708
+ const tokenAddr = itxJson.token?.address;
1709
+ if (typeof tokenAddr === "string" && tokenAddr) tokens.push({ address: tokenAddr });
1710
+ }
1559
1711
  if (tokens.length > 0) return this.formatTokenArray(tokens);
1560
1712
  return [];
1561
1713
  }
package/lib/index.d.cts CHANGED
@@ -24,6 +24,7 @@ declare class OCAPResolver implements IResolver {
24
24
  logger: IPipelineLogger$1;
25
25
  migrationChain?: MigrationChainManager;
26
26
  formatTx: (tx: IResolverTransaction | null, ctx?: IResolverContext$1) => Promise<IResolverTransaction | null>;
27
+ inFlightPreFlights: number;
27
28
  private initializationPromise;
28
29
  /**
29
30
  * Creates an instance of OCAPResolver.
@@ -51,6 +52,7 @@ declare class OCAPResolver implements IResolver {
51
52
  tx: string;
52
53
  extra?: Record<string, unknown>;
53
54
  }, ctx?: IResolverContext$1): Promise<string>;
55
+ _indexRejectedLedgerTx(ctx: Record<string, unknown>, err: unknown): Promise<void>;
54
56
  getTxSecurityWarning(txHash: string): ITxSecurityWarning | undefined;
55
57
  getTx({
56
58
  hash
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.31.0",
6
+ "version": "1.31.2",
7
7
  "description": "GraphQL resolver built upon ocap statedb and GQL layer",
8
8
  "type": "module",
9
9
  "main": "./lib/index.cjs",
@@ -49,20 +49,20 @@
49
49
  "tsdown": "^0.18.4"
50
50
  },
51
51
  "dependencies": {
52
- "@arcblock/did": "1.31.0",
53
- "@arcblock/did-ext": "1.31.0",
54
- "@arcblock/did-util": "1.31.0",
52
+ "@arcblock/did": "1.31.2",
53
+ "@arcblock/did-ext": "1.31.2",
54
+ "@arcblock/did-util": "1.31.2",
55
55
  "@arcblock/nft-display": "^3.2.3",
56
- "@arcblock/validator": "1.31.0",
57
- "@ocap/config": "1.31.0",
58
- "@ocap/indexdb": "1.31.0",
59
- "@ocap/mcrypto": "1.31.0",
60
- "@ocap/message": "1.31.0",
61
- "@ocap/state": "1.31.0",
62
- "@ocap/tx-protocols": "1.31.0",
63
- "@ocap/types": "1.31.0",
64
- "@ocap/util": "1.31.0",
65
- "@ocap/wallet": "1.31.0",
56
+ "@arcblock/validator": "1.31.2",
57
+ "@ocap/config": "1.31.2",
58
+ "@ocap/indexdb": "1.31.2",
59
+ "@ocap/mcrypto": "1.31.2",
60
+ "@ocap/message": "1.31.2",
61
+ "@ocap/state": "1.31.2",
62
+ "@ocap/tx-protocols": "1.31.2",
63
+ "@ocap/types": "1.31.2",
64
+ "@ocap/util": "1.31.2",
65
+ "@ocap/wallet": "1.31.2",
66
66
  "debug": "^4.4.3",
67
67
  "express": "^4.22.1",
68
68
  "lodash": "^4.17.23",