@ocap/resolver 1.31.0 → 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.
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
@@ -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
@@ -250,6 +250,7 @@ var OCAPResolver = class {
250
250
  * @param params.validateTokenConfig should we validate token supply and token-holder balance, should be disabled when starting an existing chain
251
251
  */
252
252
  constructor({ statedb, indexdb, ledger, config, filter, validateTokenConfig = true, logger }) {
253
+ this.inFlightPreFlights = 0;
253
254
  if (!statedb) throw new Error("OCAP Resolver requires a valid statedb implementation to work");
254
255
  if (!indexdb) throw new Error("OCAP Resolver requires a valid indexdb implementation to work");
255
256
  if (!ledger) throw new Error("OCAP Resolver requires a valid ledger implementation to work");
@@ -293,7 +294,8 @@ var OCAPResolver = class {
293
294
  request: ctx.request
294
295
  });
295
296
  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");
297
+ const maxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
298
+ if (this.queue.length + this.inFlightPreFlights >= maxRequest) throw new CustomError("FORBIDDEN", "Chain is busy");
297
299
  assertRawWireEnvelope(txBase64, this.config);
298
300
  const timer = new TxTimer();
299
301
  timer.setQueueState({
@@ -316,6 +318,14 @@ var OCAPResolver = class {
316
318
  }
317
319
  };
318
320
  return new Promise((resolve, reject) => {
321
+ this.inFlightPreFlights += 1;
322
+ let preFlightSlotReleased = false;
323
+ const releasePreFlightSlot = () => {
324
+ if (!preFlightSlotReleased) {
325
+ preFlightSlotReleased = true;
326
+ this.inFlightPreFlights = Math.max(0, this.inFlightPreFlights - 1);
327
+ }
328
+ };
319
329
  const enqueueAfterPreFlight = async () => {
320
330
  try {
321
331
  await this.initializationPromise;
@@ -352,9 +362,16 @@ var OCAPResolver = class {
352
362
  } catch (strikeErr) {
353
363
  this.logger?.warn?.("Failed to record security strike", { error: strikeErr });
354
364
  }
365
+ releasePreFlightSlot();
355
366
  reject(preFlightErr);
356
367
  return;
357
368
  }
369
+ releasePreFlightSlot();
370
+ const currentMaxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
371
+ if (this.queue.length >= currentMaxRequest) {
372
+ reject(new CustomError("FORBIDDEN", "Chain is busy"));
373
+ return;
374
+ }
358
375
  const task = async () => {
359
376
  timer.mark("queueWait");
360
377
  try {
@@ -362,27 +379,134 @@ var OCAPResolver = class {
362
379
  if (result?.txHash && result?.securityWarning) setTxSecurityWarningForHash(result.txHash, result.securityWarning, this.statedb);
363
380
  resolve(result.txHash);
364
381
  } catch (err) {
382
+ await this._indexRejectedLedgerTx(context, err);
365
383
  reject(err);
366
384
  }
367
385
  };
368
386
  this.queue.push(task);
369
387
  };
370
- enqueueAfterPreFlight().catch(reject);
388
+ enqueueAfterPreFlight().catch((err) => {
389
+ releasePreFlightSlot();
390
+ reject(err);
391
+ });
371
392
  });
372
393
  }
394
+ async _indexRejectedLedgerTx(ctx, err) {
395
+ if (!this.indexdb?.tx?.insert) return;
396
+ const ledgerSequence = Number(ctx.ledgerSequence ?? 0);
397
+ const rawTxHash = typeof ctx.txHash === "string" ? ctx.txHash.trim() : "";
398
+ if (!(ledgerSequence > 0) || !rawTxHash) return;
399
+ const txHash = rawTxHash.toUpperCase();
400
+ let rejectedRow;
401
+ try {
402
+ if (await Promise.resolve(this.statedb?.tx?.get?.(txHash)).catch(() => null)) return;
403
+ if (await Promise.resolve(this.indexdb.tx.get?.(txHash)).catch(() => null)) return;
404
+ const txType = typeof ctx.txType === "string" ? ctx.txType : "";
405
+ const type = txType ? txType.split(":").pop() || "" : "";
406
+ let typeName = "";
407
+ if (txType) try {
408
+ typeName = fromTypeUrl(txType);
409
+ } catch {
410
+ typeName = "";
411
+ }
412
+ const txObj = ctx.tx && typeof ctx.tx === "object" ? ctx.tx : {};
413
+ const from = typeof txObj.from === "string" ? txObj.from : "";
414
+ const delegator = typeof txObj.delegator === "string" ? txObj.delegator : "";
415
+ const toStrOrBase64 = (val) => {
416
+ if (typeof val === "string") return val;
417
+ if (val instanceof Uint8Array || Buffer.isBuffer(val)) return Buffer.from(val).toString("base64");
418
+ return "";
419
+ };
420
+ const sourceItx = ctx.itxJson && typeof ctx.itxJson === "object" ? ctx.itxJson : ctx.itx && typeof ctx.itx === "object" ? ctx.itx : null;
421
+ const itxJson = sourceItx ? { ...sourceItx } : {
422
+ ...typeName ? { _type: typeName } : {},
423
+ type_url: txType
424
+ };
425
+ if (!itxJson.type_url && txType) itxJson.type_url = txType;
426
+ if (!itxJson._type && typeName) itxJson._type = typeName;
427
+ const syntheticTx = {
428
+ valid: false,
429
+ code: String(err?.code || "INTERNAL"),
430
+ tx: {
431
+ from,
432
+ delegator,
433
+ itxJson
434
+ }
435
+ };
436
+ const sender = deriveTxSender(syntheticTx, ctx);
437
+ const gasPayer = "";
438
+ const time = typeof ctx.txTime === "string" && ctx.txTime || (/* @__PURE__ */ new Date()).toISOString();
439
+ const code = syntheticTx.code;
440
+ const accounts = uniq([
441
+ from,
442
+ delegator,
443
+ sender
444
+ ].filter(Boolean));
445
+ rejectedRow = {
446
+ hash: txHash,
447
+ type,
448
+ code,
449
+ valid: false,
450
+ time,
451
+ sender,
452
+ receiver: "",
453
+ gasPayer,
454
+ gasUsed: "0",
455
+ tx: {
456
+ chainId: String(txObj.chainId || this.config?.chainId || ""),
457
+ from,
458
+ delegator,
459
+ nonce: txObj.nonce ?? 0,
460
+ pk: toStrOrBase64(txObj.pk),
461
+ signature: toStrOrBase64(txObj.signature),
462
+ signaturesList: Array.isArray(txObj.signaturesList) ? txObj.signaturesList : [],
463
+ signatures: Array.isArray(txObj.signatures) ? txObj.signatures : [],
464
+ serviceFee: "0",
465
+ gasFee: "0",
466
+ gasPaid: "0",
467
+ gasPayer,
468
+ itx: {
469
+ typeUrl: txType,
470
+ ...typeName ? { __typename: typeName } : {}
471
+ },
472
+ itxJson
473
+ },
474
+ receipts: [],
475
+ tokenSymbols: [],
476
+ accounts
477
+ };
478
+ await this.indexdb.tx.insert(rejectedRow);
479
+ } catch (indexErr) {
480
+ await this.recordIndexFailure({
481
+ table: "tx",
482
+ event: "create",
483
+ entityId: txHash,
484
+ payload: rejectedRow ?? { hash: txHash },
485
+ error: indexErr
486
+ });
487
+ }
488
+ }
373
489
  getTxSecurityWarning(txHash) {
374
490
  return getTxSecurityWarningByHash(txHash, this.statedb);
375
491
  }
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);
492
+ async getTx({ hash }, ctx) {
493
+ if (patterns.txHash.test(hash)) {
494
+ const normalizedHash = hash.toUpperCase();
495
+ const stateTx = await this._getState({
496
+ table: "tx",
497
+ id: normalizedHash,
498
+ dataKey: "tx.itxJson.data",
499
+ onRead: (tx) => this.formatTx(tx, ctx),
500
+ expandContext: false,
501
+ ctx
502
+ });
503
+ if (stateTx) return stateTx;
504
+ if (this.indexdb?.tx?.get) {
505
+ const indexedTx = await Promise.resolve(this.indexdb.tx.get(normalizedHash)).catch(() => null);
506
+ if (indexedTx && (indexedTx.valid === false || indexedTx.valid === 0 || indexedTx.code !== "OK")) return this.formatTx(indexedTx, ctx);
507
+ }
508
+ }
509
+ return null;
386
510
  }
387
511
  getBlock() {
388
512
  return null;
@@ -1410,18 +1534,28 @@ var OCAPResolver = class {
1410
1534
  async _formatTx(tx, ctx) {
1411
1535
  if (!tx) return tx;
1412
1536
  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
- });
1537
+ const rawTypeUrl = tx.tx?.itx?.typeUrl || (tx.tx?.itx)?.__typename || tx.tx?.itxJson?.type_url || (tx.tx?.itxJson)?._type || "";
1538
+ let parsedTypeUrl = rawTypeUrl;
1539
+ if (rawTypeUrl.startsWith("fg:t:")) try {
1540
+ parsedTypeUrl = fromTypeUrl(rawTypeUrl);
1541
+ } catch {
1542
+ parsedTypeUrl = rawTypeUrl;
1543
+ }
1544
+ if (parsedTypeUrl) {
1545
+ tx.sender = getTxSender({
1546
+ tx: tx.tx,
1547
+ itx: tx.tx?.itxJson || {},
1548
+ typeUrl: parsedTypeUrl
1549
+ });
1550
+ tx.receiver = getTxReceiver({
1551
+ tx: tx.tx,
1552
+ itx: tx.tx?.itxJson || {},
1553
+ typeUrl: parsedTypeUrl
1554
+ });
1555
+ }
1556
+ if (!tx.sender && tx.valid === false) tx.sender = deriveTxSender(tx);
1424
1557
  }
1558
+ if (!tx.gasPayer) tx.gasPayer = deriveTxGasPayer(tx);
1425
1559
  if (!tx.receipts) tx.receipts = getTxReceipts(tx, { config: this.config });
1426
1560
  const typeUrl = get(tx, "tx.itxJson.type_url");
1427
1561
  if (typeUrl === "fg:t:revoke_withdraw" || typeUrl === "fg:t:approve_withdraw") {
@@ -1496,7 +1630,7 @@ var OCAPResolver = class {
1496
1630
  }));
1497
1631
  }
1498
1632
  async getTxTokenSymbols(tx) {
1499
- if (!tx) return [];
1633
+ if (!tx || !tx.tx?.itxJson) return [];
1500
1634
  const rollupTxs = [
1501
1635
  "DepositTokenV2Tx",
1502
1636
  "WithdrawTokenV2Tx",
@@ -1505,43 +1639,56 @@ var OCAPResolver = class {
1505
1639
  "CreateRollupBlockTx",
1506
1640
  "ClaimBlockRewardTx"
1507
1641
  ];
1508
- const typeUrl = tx.tx.itxJson._type || "";
1642
+ const itxJson = tx.tx.itxJson;
1643
+ const typeUrl = itxJson._type || "";
1509
1644
  const tokens = [];
1510
1645
  if (isDefaultTokenChanged(tx, this.config.token)) tokens.push(this.tokenItx);
1511
1646
  if (typeUrl === "AcquireAssetV2Tx") {
1512
- const factoryInput = (await this.indexdb.factory.get(tx.tx.itxJson.factory))?.input;
1513
- if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1647
+ if (typeof itxJson.factory === "string" && itxJson.factory) {
1648
+ const factoryInput = (await this.indexdb.factory.get(itxJson.factory))?.input;
1649
+ if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1650
+ }
1514
1651
  } 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 || []);
1652
+ tokens.push(...itxJson.sender?.tokens || []);
1653
+ tokens.push(...itxJson.receiver?.tokens || []);
1654
+ } else if (typeUrl === "TransferV2Tx") tokens.push(...itxJson.tokens || []);
1518
1655
  else if ([
1519
1656
  "TransferV3Tx",
1520
1657
  "AcquireAssetV3Tx",
1521
1658
  "StakeTx"
1522
- ].includes(typeUrl)) tokens.push(...uniqBy((tx.tx.itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1659
+ ].includes(typeUrl)) tokens.push(...uniqBy((itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1523
1660
  else if ([
1524
1661
  "RevokeStakeTx",
1525
1662
  "SlashStakeTx",
1526
1663
  "ReturnStakeTx"
1527
- ].includes(typeUrl)) tokens.push(...uniqBy((tx.tx.itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1664
+ ].includes(typeUrl)) tokens.push(...uniqBy((itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1528
1665
  else if (typeUrl === "ClaimStakeTx") {
1529
- const revokeTx = await this.indexdb.tx.get(tx.tx.itxJson.evidence.hash);
1666
+ const evidenceHash = itxJson.evidence?.hash;
1667
+ const revokeTx = typeof evidenceHash === "string" && evidenceHash ? await this.indexdb.tx.get(evidenceHash) : null;
1530
1668
  if (revokeTx) {
1531
1669
  const revokeTxAny = revokeTx;
1532
1670
  tokens.push(...uniqBy((revokeTxAny.tx?.itxJson?.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1533
1671
  } else this.logger.warn("Revoke stake tx not found", { tx });
1534
1672
  } 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 });
1673
+ if (typeof itxJson.rollup === "string" && itxJson.rollup) {
1674
+ const rollup = await this.indexdb.rollup.get(itxJson.rollup);
1675
+ if (rollup) tokens.push({
1676
+ address: rollup.tokenAddress,
1677
+ value: "0"
1678
+ });
1679
+ }
1680
+ } else if (typeUrl === "CreateTokenTx") {
1681
+ if (typeof itxJson.address === "string" && itxJson.address) return [extractTokenMeta(itxJson.address, [itxJson])];
1682
+ return [];
1683
+ } else if (typeUrl === "MintTokenTx" || typeUrl === "BurnTokenTx") {
1684
+ if (typeof itxJson.tokenFactory === "string" && itxJson.tokenFactory) {
1685
+ const token = await this.indexdb.tokenFactory.get(itxJson.tokenFactory);
1686
+ if (token) tokens.push({ address: token.tokenAddress });
1687
+ }
1688
+ } else if (typeUrl === "CreateTokenFactoryTx") {
1689
+ const tokenAddr = itxJson.token?.address;
1690
+ if (typeof tokenAddr === "string" && tokenAddr) tokens.push({ address: tokenAddr });
1691
+ }
1545
1692
  if (tokens.length > 0) return this.formatTokenArray(tokens);
1546
1693
  return [];
1547
1694
  }
package/lib/index.cjs CHANGED
@@ -264,6 +264,7 @@ var OCAPResolver = class {
264
264
  * @param params.validateTokenConfig should we validate token supply and token-holder balance, should be disabled when starting an existing chain
265
265
  */
266
266
  constructor({ statedb, indexdb, ledger, config, filter, validateTokenConfig = true, logger }) {
267
+ this.inFlightPreFlights = 0;
267
268
  if (!statedb) throw new Error("OCAP Resolver requires a valid statedb implementation to work");
268
269
  if (!indexdb) throw new Error("OCAP Resolver requires a valid indexdb implementation to work");
269
270
  if (!ledger) throw new Error("OCAP Resolver requires a valid ledger implementation to work");
@@ -307,7 +308,8 @@ var OCAPResolver = class {
307
308
  request: ctx.request
308
309
  });
309
310
  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");
311
+ const maxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
312
+ if (this.queue.length + this.inFlightPreFlights >= maxRequest) throw new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy");
311
313
  (0, _ocap_tx_protocols.assertRawWireEnvelope)(txBase64, this.config);
312
314
  const timer = new _ocap_tx_protocols.TxTimer();
313
315
  timer.setQueueState({
@@ -330,6 +332,14 @@ var OCAPResolver = class {
330
332
  }
331
333
  };
332
334
  return new Promise((resolve, reject) => {
335
+ this.inFlightPreFlights += 1;
336
+ let preFlightSlotReleased = false;
337
+ const releasePreFlightSlot = () => {
338
+ if (!preFlightSlotReleased) {
339
+ preFlightSlotReleased = true;
340
+ this.inFlightPreFlights = Math.max(0, this.inFlightPreFlights - 1);
341
+ }
342
+ };
333
343
  const enqueueAfterPreFlight = async () => {
334
344
  try {
335
345
  await this.initializationPromise;
@@ -366,9 +376,16 @@ var OCAPResolver = class {
366
376
  } catch (strikeErr) {
367
377
  this.logger?.warn?.("Failed to record security strike", { error: strikeErr });
368
378
  }
379
+ releasePreFlightSlot();
369
380
  reject(preFlightErr);
370
381
  return;
371
382
  }
383
+ releasePreFlightSlot();
384
+ const currentMaxRequest = Number(process.env.TX_MAX_REQUEST) || txRequestConfig.maxRequest;
385
+ if (this.queue.length >= currentMaxRequest) {
386
+ reject(new _ocap_util_lib_error.CustomError("FORBIDDEN", "Chain is busy"));
387
+ return;
388
+ }
372
389
  const task = async () => {
373
390
  timer.mark("queueWait");
374
391
  try {
@@ -376,27 +393,134 @@ var OCAPResolver = class {
376
393
  if (result?.txHash && result?.securityWarning) (0, _ocap_tx_protocols.setTxSecurityWarningForHash)(result.txHash, result.securityWarning, this.statedb);
377
394
  resolve(result.txHash);
378
395
  } catch (err) {
396
+ await this._indexRejectedLedgerTx(context, err);
379
397
  reject(err);
380
398
  }
381
399
  };
382
400
  this.queue.push(task);
383
401
  };
384
- enqueueAfterPreFlight().catch(reject);
402
+ enqueueAfterPreFlight().catch((err) => {
403
+ releasePreFlightSlot();
404
+ reject(err);
405
+ });
385
406
  });
386
407
  }
408
+ async _indexRejectedLedgerTx(ctx, err) {
409
+ if (!this.indexdb?.tx?.insert) return;
410
+ const ledgerSequence = Number(ctx.ledgerSequence ?? 0);
411
+ const rawTxHash = typeof ctx.txHash === "string" ? ctx.txHash.trim() : "";
412
+ if (!(ledgerSequence > 0) || !rawTxHash) return;
413
+ const txHash = rawTxHash.toUpperCase();
414
+ let rejectedRow;
415
+ try {
416
+ if (await Promise.resolve(this.statedb?.tx?.get?.(txHash)).catch(() => null)) return;
417
+ if (await Promise.resolve(this.indexdb.tx.get?.(txHash)).catch(() => null)) return;
418
+ const txType = typeof ctx.txType === "string" ? ctx.txType : "";
419
+ const type = txType ? txType.split(":").pop() || "" : "";
420
+ let typeName = "";
421
+ if (txType) try {
422
+ typeName = (0, _ocap_message.fromTypeUrl)(txType);
423
+ } catch {
424
+ typeName = "";
425
+ }
426
+ const txObj = ctx.tx && typeof ctx.tx === "object" ? ctx.tx : {};
427
+ const from = typeof txObj.from === "string" ? txObj.from : "";
428
+ const delegator = typeof txObj.delegator === "string" ? txObj.delegator : "";
429
+ const toStrOrBase64 = (val) => {
430
+ if (typeof val === "string") return val;
431
+ if (val instanceof Uint8Array || Buffer.isBuffer(val)) return Buffer.from(val).toString("base64");
432
+ return "";
433
+ };
434
+ const sourceItx = ctx.itxJson && typeof ctx.itxJson === "object" ? ctx.itxJson : ctx.itx && typeof ctx.itx === "object" ? ctx.itx : null;
435
+ const itxJson = sourceItx ? { ...sourceItx } : {
436
+ ...typeName ? { _type: typeName } : {},
437
+ type_url: txType
438
+ };
439
+ if (!itxJson.type_url && txType) itxJson.type_url = txType;
440
+ if (!itxJson._type && typeName) itxJson._type = typeName;
441
+ const syntheticTx = {
442
+ valid: false,
443
+ code: String(err?.code || "INTERNAL"),
444
+ tx: {
445
+ from,
446
+ delegator,
447
+ itxJson
448
+ }
449
+ };
450
+ const sender = (0, _ocap_indexdb_lib_util.deriveTxSender)(syntheticTx, ctx);
451
+ const gasPayer = "";
452
+ const time = typeof ctx.txTime === "string" && ctx.txTime || (/* @__PURE__ */ new Date()).toISOString();
453
+ const code = syntheticTx.code;
454
+ const accounts = (0, lodash_uniq.default)([
455
+ from,
456
+ delegator,
457
+ sender
458
+ ].filter(Boolean));
459
+ rejectedRow = {
460
+ hash: txHash,
461
+ type,
462
+ code,
463
+ valid: false,
464
+ time,
465
+ sender,
466
+ receiver: "",
467
+ gasPayer,
468
+ gasUsed: "0",
469
+ tx: {
470
+ chainId: String(txObj.chainId || this.config?.chainId || ""),
471
+ from,
472
+ delegator,
473
+ nonce: txObj.nonce ?? 0,
474
+ pk: toStrOrBase64(txObj.pk),
475
+ signature: toStrOrBase64(txObj.signature),
476
+ signaturesList: Array.isArray(txObj.signaturesList) ? txObj.signaturesList : [],
477
+ signatures: Array.isArray(txObj.signatures) ? txObj.signatures : [],
478
+ serviceFee: "0",
479
+ gasFee: "0",
480
+ gasPaid: "0",
481
+ gasPayer,
482
+ itx: {
483
+ typeUrl: txType,
484
+ ...typeName ? { __typename: typeName } : {}
485
+ },
486
+ itxJson
487
+ },
488
+ receipts: [],
489
+ tokenSymbols: [],
490
+ accounts
491
+ };
492
+ await this.indexdb.tx.insert(rejectedRow);
493
+ } catch (indexErr) {
494
+ await this.recordIndexFailure({
495
+ table: "tx",
496
+ event: "create",
497
+ entityId: txHash,
498
+ payload: rejectedRow ?? { hash: txHash },
499
+ error: indexErr
500
+ });
501
+ }
502
+ }
387
503
  getTxSecurityWarning(txHash) {
388
504
  return (0, _ocap_tx_protocols.getTxSecurityWarningByHash)(txHash, this.statedb);
389
505
  }
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);
506
+ async getTx({ hash }, ctx) {
507
+ if (_arcblock_validator.patterns.txHash.test(hash)) {
508
+ const normalizedHash = hash.toUpperCase();
509
+ const stateTx = await this._getState({
510
+ table: "tx",
511
+ id: normalizedHash,
512
+ dataKey: "tx.itxJson.data",
513
+ onRead: (tx) => this.formatTx(tx, ctx),
514
+ expandContext: false,
515
+ ctx
516
+ });
517
+ if (stateTx) return stateTx;
518
+ if (this.indexdb?.tx?.get) {
519
+ const indexedTx = await Promise.resolve(this.indexdb.tx.get(normalizedHash)).catch(() => null);
520
+ if (indexedTx && (indexedTx.valid === false || indexedTx.valid === 0 || indexedTx.code !== "OK")) return this.formatTx(indexedTx, ctx);
521
+ }
522
+ }
523
+ return null;
400
524
  }
401
525
  getBlock() {
402
526
  return null;
@@ -1424,18 +1548,28 @@ var OCAPResolver = class {
1424
1548
  async _formatTx(tx, ctx) {
1425
1549
  if (!tx) return tx;
1426
1550
  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
- });
1551
+ const rawTypeUrl = tx.tx?.itx?.typeUrl || (tx.tx?.itx)?.__typename || tx.tx?.itxJson?.type_url || (tx.tx?.itxJson)?._type || "";
1552
+ let parsedTypeUrl = rawTypeUrl;
1553
+ if (rawTypeUrl.startsWith("fg:t:")) try {
1554
+ parsedTypeUrl = (0, _ocap_message.fromTypeUrl)(rawTypeUrl);
1555
+ } catch {
1556
+ parsedTypeUrl = rawTypeUrl;
1557
+ }
1558
+ if (parsedTypeUrl) {
1559
+ tx.sender = (0, _ocap_state_lib_states_tx.getTxSender)({
1560
+ tx: tx.tx,
1561
+ itx: tx.tx?.itxJson || {},
1562
+ typeUrl: parsedTypeUrl
1563
+ });
1564
+ tx.receiver = (0, _ocap_state_lib_states_tx.getTxReceiver)({
1565
+ tx: tx.tx,
1566
+ itx: tx.tx?.itxJson || {},
1567
+ typeUrl: parsedTypeUrl
1568
+ });
1569
+ }
1570
+ if (!tx.sender && tx.valid === false) tx.sender = (0, _ocap_indexdb_lib_util.deriveTxSender)(tx);
1438
1571
  }
1572
+ if (!tx.gasPayer) tx.gasPayer = (0, _ocap_indexdb_lib_util.deriveTxGasPayer)(tx);
1439
1573
  if (!tx.receipts) tx.receipts = (0, _ocap_state_lib_states_tx.getTxReceipts)(tx, { config: this.config });
1440
1574
  const typeUrl = (0, lodash_get.default)(tx, "tx.itxJson.type_url");
1441
1575
  if (typeUrl === "fg:t:revoke_withdraw" || typeUrl === "fg:t:approve_withdraw") {
@@ -1510,7 +1644,7 @@ var OCAPResolver = class {
1510
1644
  }));
1511
1645
  }
1512
1646
  async getTxTokenSymbols(tx) {
1513
- if (!tx) return [];
1647
+ if (!tx || !tx.tx?.itxJson) return [];
1514
1648
  const rollupTxs = [
1515
1649
  "DepositTokenV2Tx",
1516
1650
  "WithdrawTokenV2Tx",
@@ -1519,43 +1653,56 @@ var OCAPResolver = class {
1519
1653
  "CreateRollupBlockTx",
1520
1654
  "ClaimBlockRewardTx"
1521
1655
  ];
1522
- const typeUrl = tx.tx.itxJson._type || "";
1656
+ const itxJson = tx.tx.itxJson;
1657
+ const typeUrl = itxJson._type || "";
1523
1658
  const tokens = [];
1524
1659
  if ((0, _ocap_indexdb_lib_util.isDefaultTokenChanged)(tx, this.config.token)) tokens.push(this.tokenItx);
1525
1660
  if (typeUrl === "AcquireAssetV2Tx") {
1526
- const factoryInput = (await this.indexdb.factory.get(tx.tx.itxJson.factory))?.input;
1527
- if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1661
+ if (typeof itxJson.factory === "string" && itxJson.factory) {
1662
+ const factoryInput = (await this.indexdb.factory.get(itxJson.factory))?.input;
1663
+ if (factoryInput?.tokens) tokens.push(...factoryInput.tokens);
1664
+ }
1528
1665
  } 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 || []);
1666
+ tokens.push(...itxJson.sender?.tokens || []);
1667
+ tokens.push(...itxJson.receiver?.tokens || []);
1668
+ } else if (typeUrl === "TransferV2Tx") tokens.push(...itxJson.tokens || []);
1532
1669
  else if ([
1533
1670
  "TransferV3Tx",
1534
1671
  "AcquireAssetV3Tx",
1535
1672
  "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));
1673
+ ].includes(typeUrl)) tokens.push(...(0, lodash_unionBy.default)((itxJson.inputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1537
1674
  else if ([
1538
1675
  "RevokeStakeTx",
1539
1676
  "SlashStakeTx",
1540
1677
  "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));
1678
+ ].includes(typeUrl)) tokens.push(...(0, lodash_unionBy.default)((itxJson.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1542
1679
  else if (typeUrl === "ClaimStakeTx") {
1543
- const revokeTx = await this.indexdb.tx.get(tx.tx.itxJson.evidence.hash);
1680
+ const evidenceHash = itxJson.evidence?.hash;
1681
+ const revokeTx = typeof evidenceHash === "string" && evidenceHash ? await this.indexdb.tx.get(evidenceHash) : null;
1544
1682
  if (revokeTx) {
1545
1683
  const revokeTxAny = revokeTx;
1546
1684
  tokens.push(...(0, lodash_unionBy.default)((revokeTxAny.tx?.itxJson?.outputs || []).reduce((acc, x) => acc.concat(x.tokens || []), []), "address").filter((x) => x.address));
1547
1685
  } else this.logger.warn("Revoke stake tx not found", { tx });
1548
1686
  } 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 });
1687
+ if (typeof itxJson.rollup === "string" && itxJson.rollup) {
1688
+ const rollup = await this.indexdb.rollup.get(itxJson.rollup);
1689
+ if (rollup) tokens.push({
1690
+ address: rollup.tokenAddress,
1691
+ value: "0"
1692
+ });
1693
+ }
1694
+ } else if (typeUrl === "CreateTokenTx") {
1695
+ if (typeof itxJson.address === "string" && itxJson.address) return [extractTokenMeta(itxJson.address, [itxJson])];
1696
+ return [];
1697
+ } else if (typeUrl === "MintTokenTx" || typeUrl === "BurnTokenTx") {
1698
+ if (typeof itxJson.tokenFactory === "string" && itxJson.tokenFactory) {
1699
+ const token = await this.indexdb.tokenFactory.get(itxJson.tokenFactory);
1700
+ if (token) tokens.push({ address: token.tokenAddress });
1701
+ }
1702
+ } else if (typeUrl === "CreateTokenFactoryTx") {
1703
+ const tokenAddr = itxJson.token?.address;
1704
+ if (typeof tokenAddr === "string" && tokenAddr) tokens.push({ address: tokenAddr });
1705
+ }
1559
1706
  if (tokens.length > 0) return this.formatTokenArray(tokens);
1560
1707
  return [];
1561
1708
  }
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.1",
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.1",
53
+ "@arcblock/did-ext": "1.31.1",
54
+ "@arcblock/did-util": "1.31.1",
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.1",
57
+ "@ocap/config": "1.31.1",
58
+ "@ocap/indexdb": "1.31.1",
59
+ "@ocap/mcrypto": "1.31.1",
60
+ "@ocap/message": "1.31.1",
61
+ "@ocap/state": "1.31.1",
62
+ "@ocap/tx-protocols": "1.31.1",
63
+ "@ocap/types": "1.31.1",
64
+ "@ocap/util": "1.31.1",
65
+ "@ocap/wallet": "1.31.1",
66
66
  "debug": "^4.4.3",
67
67
  "express": "^4.22.1",
68
68
  "lodash": "^4.17.23",